You are on page 1of 1672

DOTNET

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Table of Contents
Page No Topics
1 Coding Best Practices
5 Construction Coding & Debugging
23 Construction – Design
27 RDBMS
63 Programming in SQL Server
113 Object Orientation
115 Introduction
121 Element of Object Orientation
122 Object Orientation – A Conceptual Look
126 Object Orientation- Basic Principle
137 Class
138 Abstraction
140 Encapsulation
141 Identity
143 Object Relationships

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
2
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Table of Contents
Page No Topics
145 Introduction to .Net Framework
155 C# 2.0 Visuals Studio 2005
157 Introduction to C#
171 Visual Studio 2005 – IDE
172 C# Programming Language
206 Debugging In Visual Studio 2005
214 Visual Studio Class Designer
219 Class & Object
230 Properties
233 Property Visibility
236 Partial Class
243 Static Class
246 Structures
250 C# Programming Language Part 2
251 Inheritance

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
3
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Table of Contents
Page Topics
No
267 Operator Overloading & Type conversion
271 Interface
282 Indexers
285 Nested Classes
290 UML for Beginners
312 Generics
329 Callbacks
335 Anonymous Methods
343 Events
346 Exception Handling
350 Inline Warning
352 Refactoring Support under Visual Studio
2005
365 Programming with .Net Framework
366 Assembly and CLR
378 Application Domains
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
4
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Table of Contents
Page Topics
No
382 Threads
393 File Handling
406 Serialization
413 ADO .NET 2.0
494 Microsoft Application Blocks for .Net
495 Data Access Application Block
504 Exception Management Application Block
515 Introduction to Nunit
524 FxCop 1.32
530 HTML
549 CSS

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
5
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Table of Contents
Page Topics
No
556 XML
573 Java Script
589 ASP .NET Session Topics
590 Introduction to ASP .Net
597 ASP .NET Web Forms
607 Master pages
618 Themes and Skins
623 ASP .Net Controls
680 Advanced Control
702 Server Side Data Access
743 Web Application Management

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
6
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Table of Contents
Page Topics
No
780 Web Site Management
829 Best Practices with .Net Framework

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
7
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generic Modules

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Coding Best Practices

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Objective
• Get to know about effective development
practices

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
10
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Target Audience
• SE
• SSE

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
11
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Prerequisites for the course
• Familiarity in writing, debugging and running
simple programs in C will be helpful

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
12
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
H/w & S/w Required
None

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
13
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Session Plan
Day 1
• Coding Best Practices

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
14
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
1. Coding Best Practices
• What is Software Construction?
• Why is Construction or Implementation
Important?
• Construction - Coding and Debugging
 Why Coding Standards are important?
 Good Naming Convention
 Each method should do one thing
 Do not write monolithic code
 Defensive Programming
 Name all magic numbers

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
15
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
• Techniques for Writing Clean Code
• Code Tuning
 When to Tune
 Common Sources of Inefficiency
• Error Handling
• Application Security
• Construction - Design
 Layering the application
 Reasons for Layering
 Qualities that make up good layers

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
16
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Construction
Coding & Debugging

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Software Construction
What is Software Construction?
The following are the distinct activities that go into software
development
• Problem definition
• Requirements analysis
• Implementation Planning
• High-level design, or architecture
• Detailed design
• Construction, or implementation (Design, Coding and
Debugging)
• Unit testing
• Integration
• System testing
• Corrective maintenance
• Functional enhancements

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
18
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Software Construction
Why is Construction or Implementation Important?
• Construction is a large part of software development
• Construction is pivotal activity in software development
• Construction’s product, the source code, is often the only
accurate description of software
• Construction is the only activity that guaranteed to be done

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
19
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Why Coding Standards are important?

• Lead to greater consistency within your code and the code of your
teammates
• Easier to understand, which in turn means it is easier to develop
and to maintain
• Reduces overall cost of applications that we create
• We can transition our work to another developer, or to another
team of developers, so that they can continue to maintain and
enhance the work without having to invest an unreasonable effort
to understand our code.
• Code that is difficult to understand runs the risk of being scrapped
and rewritten
• Maintainability – The ease with which you can modify a software
system to change or add capabilities, improve performance, or
correct defects

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
20
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Why Coding Standards are important?
• Flexibility – The extent to which you can modify a system for uses or
environments other than those for which it was specifically designed
• Portability – The ease with which you can modify a system to operate in an
environment different from that for which it was specifically designed for
• Reusability – The extent to which and the ease with which you can use parts
of a system in other systems
• Readability – The ease with which you can read and understand the source
code of a system, especially at the detailed-statement level

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
21
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Why Coding Standards are important?

When you go against a standard, document it.


All standards, except for this one, can be broken.
• If you do so, you must document why you broke the standard, the
potential implications of breaking the standard, and any conditions
that may/must occur before the standard can be applied to this
situation.
• The bottom line is that you need to understand each standard,
understand when to apply them, and just as importantly when not to
apply them.
• Recognize that an application spends the majority of its existence
being maintained, not developed, Coding standards can help to make
code easier to maintain and to enhance, as well as to develop. Never
forget that the code that you write today may still be in use many
years from now and will likely be maintained and enhanced by
somebody other than you. You must strive to make your code as
“clean” and understandable as possible.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
22
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Coding Standards
Good Naming Convention
• Use full English descriptors that accurately describe the
variable/field/class
Example:
firstName
grandTotal
CorporateCustomer
• Use terminology applicable to the domain
• Use mixed case to make names readable
• Use abbreviations sparingly, but if you do so then use them intelligently
• Avoid long names (< 15 characters is a good idea)
• Avoid names that are similar or differ only in case
• Capitalize the first letter of standard acronyms
• Follow the customer coding standards, if any

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
23
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Coding Standards
Good Documentation
• Comments should add to the clarity of your code
• Avoid decoration, i.e. do not use banner-like comments
• Keep comments simple
• Write the documentation before you write the code
• Document why something is being done, not just what
• Document What and why the member function does what it does.The
known bugs in the method, all concurrency issues in the method etc.,
Example:
if ( grandTotal >= 1000.00)
{
grandTotal = grandTotal * 0.95;
}
Any one can figure out that a 5% discount is being given on orders of
$1,000 or more. Why is this being done? Is there a business rule that
says that large orders get a discount? Is there a limited-time special on
large orders or is it a permanent program?

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
24
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Coding Standards
• Each method should do one thing
A sure sign that a method is designed improperly is that its
functionality (as opposed to its implementation) can't be succinctly
described as a single action or the computation of a single value.
• Smaller methods are easier to understand
It's probably self-evident, but several small methods, all with good
names and documentation comments, are easier to understand than
a single large method with the same functionality
Smaller methods are also usually easy to debug than monolithic
methods, because the correctness of a smaller piece of code can be
verified more easily than a larger one
• Do not write monolithic code. Try to modularize the code within
an function (Structured Programming). The characteristics of
Structured Programming are
Code broken into modules
Each module has one and only one function
There is one and only one logical entry and exit to each module
Modules are loosely coupled
No GOTO statements

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
25
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Coding Standards
• Defensive Programming – doesn’t mean being defensive about
your programming.
 check for null values
 check for size of data structures, before use
 IF block should have ELSE block, wherever applicable

Example:
if (a = null) {
statement1;
}
else (a.length = 3 ) {
statement 2;
}
else {
default statement;
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
26
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Coding Standards
• Analyze all queries at unit level (like Query Plan in Oracle) and ensure
that it is using the appropriate index
• Through out the design and coding phase, keep an eye on the
scalability of design and code.
• Name all magic numbers
Many programs need to use numeric constants. It is almost always
best to assign names to these values rather than using raw numbers.
The often cited reason is that the number may change and localizing
the usage of the actual constant value makes it possible to modify the
program without hunting in many places for the incorrect value.
• Do not hard-code values in programs (even as static variables/ class-
attribute-values) what can be stored in database.
Example:
if (intFistMark >= PASS_MARK) {
statement 1
}
else {
statement 2
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
27
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Coding Standards
• Always try to answer questions like
• Does our design permit easy addition of objects/ removal of
objects?
• What would happen if the number of records exceed so and so?‘
• Identify the boundaries/ limitations imposed by our design.
• Share this information with user to get their feedback and try to
eliminate or broaden the limitations that are in our control.
• Declaring variables
• Most C programmers put a blank line between the variable
declarations and the rest of the program
• There's nothing wrong with commenting a variable to describe what
it contains. For example
 int intCount; /* busy signals from tech support. */
• However, cleverly named variables may avoid this situation. For
example
 int intBusySignals;
• Place Constants on the Left Side of Comparisons
 if( PASS_MARK == intMark )

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
28
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Coding Standards
• Do not hardcode error messages, instead try to read it from
Database.
• Avoid redundant coding,
Example
String strName = null;
Statement 1
strName = getName();

Instead of following example


String strName = new String();
Statement 1
strName = getName();

This will unnecessarily occupy two memory locations

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
29
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Coding Standards
• Avoid creation of variables inside a loop
Example
for (int I = 0; I < 10 ; I ++) {
int intSum = 0;
….
}
• Keep the scope of the variable as limited as possible. Declare
the variables only when needed.
• Try to minimize database calls where possible. Especially so
with display of static master data values like in list boxes etc.
 This does not mean that we should not store such data in
database.
 Think of reading the database values and storing them in session
variables etc. depending on the staticity of data
• Try to de reference all variables after its use

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
30
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Techniques for Writing Clean Code
• Document your code
• Paragraph/Indent your code
• Paragraph and punctuate multi-line statements
• Use white space
• Follow the thirty-second rule
• Write short, single command lines
• Specify the order of message sends
• Use less code - Using existing libraries, Get rid of unused
functions
• Reduce preconditions - Code which is very persnickety about
how it's invoked makes everything else harder to maintain.
Examples are requiring that methods be called in a certain
order, and requiring that a certain method be called only
once.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
31
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Code Optimization
Code tuning is the practice of modifying correct code in
ways that make it run more efficiently. Tuning doesn’t
change the design; it changes only the implementation

When to Tune
• Use a high-quality design
• Make the program right
• Make it modular and easily modifiable so that it’s easy to
work on later

When the above steps are complete and correct,


check the performance. If the program lumbers, make it
fast and small. Don’t optimize until you know you need to
• Tune only the code which is called frequently in the code
and which takes more time.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
32
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Code Optimization
Common Sources of Inefficiency
• Input/output operations – One of the most significant
sources of inefficiency is unnecessary I/O.
Example:
Sorting contents of small file. The options are
 Sorting in memory
 Sorting on disk
Sorting in-memory access is on the order of 1000
times faster than accessing data in an
external file
• Formatted printing routines
• Paging – An operation that causes the operating system to
swap pages of memory is much slower than an operation
that works on only one page of memory

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
33
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Code Optimization
• Paging – An operation that causes the operating
system to swap pages of memory is much slower than
an operation that works on only one page of memory
Example:
for (int column = 0; column < 1000; column++)
{
for (int row = 0; row < 5; row++) {
table[row, col] = 0;
}
}
Each row of table is 1000 elements long, that means
each row of table is 2000 bytes long, or about a page long.
Each time the program accesses a different row, the
operating system has to switch memory pages, which is
5000 times.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
34
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Code Optimization
for (int row = 0; row < 5; row++) {
for (int column = 0; column < 1000; column+
+) {
table[row, col] = 0;
}
}
In this case, the above code will switch the memory
pages just 5 times, so it performs in a total time of a few
milliseconds rather than several thousand
milliseconds.
• System calls – Calls to system routines are often expensive.
System routines include input/output operations to disk, key
board, screen, printer, or other device; memory-
management routines; and certain utility routines.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
35
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Code Optimization Techniques
Loops
Because loops are executed many times, the hot spots in
program are often inside loops. The technique is to make the
loop itself faster.

Unswitching
Switching refers to making a decision inside a loop every time
it’s executed.
If the decision doesn’t change while the loop is executing, we
can unswitch the loop making the decision outside the loop

Example of Switched Loop


for (int I = 0; I < count; I++)
{
if ( SumType == Net )
NetSum = NetSum + Amount [ I ];
else
GrossSum = GrossSum + Amount [ I ]
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
36
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Code Optimization Techniques
Example of Unswitched Loop
if ( SumType == Net ) {
for (int I = 0; I < count; I++) {
NetSum = NetSum + Amount [ I ];
}
} else {
for (int I = 0; I < count; I++)
{
GrossSum = GrossSum + Amount [ I ]
}
}

The for statement is repeated, so the code uses more space,


but the time savings speak for themselves.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
37
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Code Optimization Techniques
Jamming
Jamming, or “fusion” is the result of combining two loops
that operate on the same set of elements. The gain lies in
cutting the loop overhead from two loops to one.

Example of Separate Loops that could be Jammed


for (int I = 1; I < num; I++ ) {
{
EmployeeName [ I ] = “”;
}
………
for (int I = 1; I < num; I++ ) {
{
EmployeeEarnings[ I ] = 0;
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
38
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Code Optimization Techniques
Example of a Jammed Loop
for (int I = 1; I < num; I++ ) {
EmployeeName [ I ] = “”;
EmployeeEarnings[ I ] = 0;
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
39
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Code Optimization Techniques
Unrolling
The goal of loop unrollings is to reduce the amount of loop
housekeeping.

Unrolling a loop is a fast solution and works well when we are


dealing with a small number of elements, its not practical when
we have a large number of elements or when you don’t
know in advance how many elements we’ll have.
Example of Separate Loop that can be Unrolled
I = 1;
while (I <= num) {
a [ I ] = I;
I = I + 1;
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
40
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Code Optimization Techniques
Example of a Loop That’s Bean Unrolled Once
I = 1;
while (I < num) {
a [ I ] = I;
a [ I + 1 ] = I;
I = I + 2;
}
if (I == num)
a [ I ] = I;

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
41
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Code Optimization Techniques
Minimizing the Work Inside Loops
One key to writing effective loops is to minimize the work done inside
a loop. If we can evaluate a statement or part of a statement
outside a loop so that only the result is used inside the loop, do so.

It’s good programming practice, and, in some cases, it improves


readability

Example of Complicated Pinter Expression Inside a Loop


for ( int I = 0; I < num ; I ++) {
NetRate [ I ] = BaseRate [ I ] * Rates -> Discounts -> Factors - > Net;
}
Example of Simplifying a Complicated Pinter Expression
QuantityDiscount = Rates -> Discounts -> Factors - > Net;
for ( int I = 0; I < num ; I ++) {
NetRate [ I ] = BaseRate [ I ] * QuantityDiscount;
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
42
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Code Optimization Techniques
Making the Busiest Loop on the Inside
When we have nested loops, think about which loop to be on
the outside and which one on the inside.

Example of Nested Loop That Can be Improved


for ( int column = 0; I < 100 ; I ++) {
for ( int row = 0; j < 5 ; j ++) {
Sum = Sum + table [ row, column ] ;
}
}

The key to improving the loops is that the outer loop


executes much more often than inner loop. Each time the loop
executes, it has to initialize the loop index, increment it on
each pass through the loop, and check it after each

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
43
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Code Optimization Techniques
Avoid invoking unnecessary methods
If the value returned by the methods are not going to
change then don’t invoke the methods unnecessarily.

String str = new String(“Hello”);


for(int i =0; i<str.length(); i++){
….
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
44
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Code Optimization Techniques

String str = “Hello”;


int iNameLength = str.length();
for(int i =0; i< iNameLength; i++){
….
}

•The reduction of method invocation str.length will improve the


performance a bit.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
45
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Code Optimization Techniques
Stop testing when we know the Answer
Much of programming consists of manipulating logic, stop
once you have determined the answer

Example of Not Stopping after we know the Answer

NegativeTrue = false;
for ( int I = 0; I < num; I++ ) {
if ( Input [ I ] < 0 ) {
NegativeFound = true;
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
46
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Code Optimization Techniques
Example of Stopping after we know the Answer
NegativeTrue = false;
for ( int I = 0; I < num; I++ ) {
if ( Input [ I ] < 0 ) {
NegativeFound = true;
break;
}
}

Alternate for multiple IF clause


If there is a need to use multiple IF, look for some other
logical statements like ‘switch’ – ‘case’

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
47
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Debugging
How to Debug your Program/Application
Inserting log statements into your code is a low-tech
method for debugging it. Logging equips the developer
with detailed context for application failures.

Log4j Project
• Log4j is a fast and flexible framework for logging application
debugging messages.
• With log4j it is possible to enable logging at runtime without
modifying the application binary. The log4j package is
designed so that these statements can remain in shipped
code without incurring a heavy performance cost. Logging
behavior can be controlled by editing a configuration file,
without touching the application binary.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
48
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Debugging
Log4j Supports following projects
• Log4Cxx (c++)
• Log4j
• Log4Net
• Log4Perl
• Log4PLSQL
• JDK1.4's util.logging framework

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
49
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Error Handling
No program or program fragment can be considered
complete until appropriate error handling has been added.

Unexpected program failures are a disaster - at the best,


they cause frustration because the program user must
repeat minutes or hours of work, but in mission-critical
applications, even the most trivial program error, if not
processed correctly, has the potential to kill someone.

If an error is fatal, in the sense that a program cannot


sensibly continue, then the program must be able to "die
gracefully". This means that it must
 Inform its user(s) why it died, and
 save as much of the program state as possible.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
50
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Application Security
Overview
A decade ago, applications were
 Physically secure
 Housed in central data centers – not distributed
 External access mediated
 Security issues rarely reported
Now, applications are externally accessible
 Suppliers directly connected
 Customers directly connected
 Customers and partners directly sharing
application/Data base

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
51
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Application Security
Application Level Security
Most of the application might restrict access based on user
information stored in a database. Often, we need to protect
resources (data bases)

Authorization provides controlled access to protected


resources. However, authorization is based on
authentication and access control.

Authentication is a process that verifies the identity of a


user

Access Control is a process that determines whether this


authenticated user is entitled to access a particular
requested resource

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
52
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Application Security
Role Level Security

Role - an abstract name for the permission to access a


particular set of resources. A role can be compared to a key
that can open a lock. Many people might have a copy of the
key, and the lock doesn't care who you are, just that you have
the right key.

User - an individual (or application program) identity that has


been authenticated. A user can have a set of roles associated
with that identity, which entitles them to access all resources
protected by those roles.

Example:
1. All suppliers can access supply related information, but not
customer related information
2. Same way, all customers can access customer related
information but not the supply related information.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
53
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Construction - Design

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Layering
Layering the application
Layering is a technique that supports the concept of
separation of concerns by organizing your software design
into layers/collections of classes or components that fulfill a
common purpose, such as implementing your user interface
or the business logic of your system.

Reasons for Layering


• Reducing complexity
• Avoiding duplicate code
• Limiting effects of changes
• Hiding sequences
• Improving performance
• Making central points of control
• Promoting code reuse
• Improving portability
• Isolating complex operations

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
55
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Layering
Qualities that make up good layers
• Should be able to make modifications to any given layer
without affecting any other layers. This will help to make our
system easy to extend and to maintain -- in other words more
flexible and robust
• Layers should be modularized. Should be able to either to
rewrite a layer or simply replace it and, as long as the interface
remains the same, the rest of the system should not be
affected. This will help to make increase the portability of your
software.
• Layers should be cohesive: they should encapsulate one high-
level concept. A cohesive layer is easier to understand, and
thus to work with.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
56
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Routines/ Modules
What is Routines?
A set of instructions that perform a specific task for
a program.

The major activities are


• Designing the routine
• Checking the designBegin
• Coding the routine
• Checking the codeDesign the Check the
routine design
Repeat if
necessary
Check the Code the
code routine

Done
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
57
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Routines/ Modules
Characteristics of Routine (Modules)
Strong Cohesion
Cohesion refers to how closely the operations in a routine are
related or how strongly the operations are related in a Layer

Example:
1. A function like getCustomerName() is perfectly cohesive because the
whole routine is dedicated to perform one function
2. A function like inputAll() has lower cohesion, because it tries to do more
than one thing.

Goal
The goal is to have each routine do one thing well and not do
anything else

Advantages
The payoff is higher reliability.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
58
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Characteristics of Routine (Modules)
Loose Coupling
The degree of coupling refers to the strength of a connection between two
routines. Coupling describes how strongly a routine is related to other
routines.

Try to create routine that depend little on other routines. Make then
detached, as business associates are, rather than attached, a Siamese
twins are

Example:
1. A function like sin() is loosely coupled because everything it needs to
know is passed in to it with one value representing an angle in degrees.
2. A function like inputAll(var1, var 2 , var3 … var N) is more tightly coupled
because the calling routine virtually knows what is happening inside it.

Goal
The goal is to create routines with internal integrity (strong cohesion) and
small, direct, visible, and flexible relations to other routines (loose
coupling)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
59
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A good developer knows that there
is more to development than programming.

A great developer knows that there


is more to development than development.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
60
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
RDBMS

COE – Current Technologies


Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Contents
DBMS Definition
Purpose of DBMS
Data Models
Instances, Schemas
Data Independence
DBMS Users
Single & Multi User Systems
Database System Components & Architecture

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
62
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Contents
E-R Model
Relational Model
Object Oriented Model
Normalization

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
63
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DBMS Definition

Database Management Systems or Database Systems consists of :


• A collection of interrelated persistent data
• A set of application programs to access, update and manage the data.
Handles:
• Data Redundancy
• Data Inconsistency
• Data Isolation
• Data Access
• Multiple Users
• Security
• Integrity

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
64
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Purpose of DBMS

The goal of a DBMS is :


 To provide an environment that is both convenient and
efficient to use in
 Retrieving information from the database.
 Storing information into the database.
Database is usually designed to manage large
bodies of information.
This involves Definition of structures for
information storage (data modeling).

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
65
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Purpose of DBMS
Mechanisms for manipulation of information
(file and systems structure, query
processing).
Providing the safety of information in the
database (crash recovery and security).
Concurrency control if the system is shared by
more than one user
Provide security of data against unauthorized
access.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
66
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Purpose of DBMS
Data Abstraction
• Provides an Abstract View of Data
• Hides how data is stored and maintained
• Hides the Complexity
Levels of Abstraction
• Physical Level
 How the data is stored
 Structures defined in detail
• Conceptual Level
 Describes what data is stored
 Describes the relationships among data
• View Level
 Describes part of Database for particular users

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
67
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Models

Collection of conceptual tools for describing data, data


relationships, data semantics and data constraints.
Object Based Logical Models
• E-R Model
• Object Oriented Model
Record Based Logical Models
• Relational Model
• Network Model
• Hierarchical Model

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
68
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Object Based Logical Models
Provides data at conceptual and view levels
Provides structuring capabilities
Can specify constraints

E-R Model
E-R model is based on a perception of the world as collection of basic
objects and relationships among those objects
• An entity is a distinguishable object that exists.
• Each entity has associated with it a set of attributes describing it.
• A relationship is an association among several entities.
• The set of all entities or relationships of the same type is called the entity
set or relationship set.
• E-R diagram maps cardinalities, which express the number of entities to
which another entity can be associated via a relationship set.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
69
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Object Based Logical Models

Object Oriented Model


The object-oriented model is based on a collection of objects
• An object contains values stored in instance variables within the object
• Each object has its own unique identity, independent of the values it
contains. Two objects containing the same values are distinct
• Distinction is created and maintained in physical level by assigning
distinct object identifiers.
• An object also contains bodies of code that operate on the the object.
• Objects that contain the same types of values and the same methods are
grouped into classes
• The only way in which one object can access the data of another object
is by invoking the method of that other object.
• Result is two levels of data abstraction.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
70
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Record Based Logical Models
Provide data at conceptual and view levels
Specifies overall logical structure of the database unlike the
previous model
• Provide a higher-level description of the implementation
• Named so because the database is structured in fixed-format records of
several types.
• Each record type defines a fixed number of fields, or attributes.
• Each field is usually of a fixed length.
• Record-based models do not include a mechanism for direct
representation of code in the database.
• Separate languages associated with the model are used to express
database queries and updates.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
71
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Record Based Logical Models
The Relational Model
Data and relationships are represented by a collection of
tables.
Each table has a number of columns with unique names, e.g.
customer, account.

Name Street City Number Number Balance


Harry Maples Queens 900 900 3000
Shiver North Bronx 646 646 500
Derek Sidehill Brooklyn 337 337 1500
Gail West Buffalo 801 801 300
Hodges Southwood Jersey 617 617 2500

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
72
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Record Based Logical Models

Network Models
Data are represented by collections of records.
Relationships among data are represented by links.
Organization is that of an arbitrary graph.
Some data were modeled with more than one parent per child.

The network model permitted the modeling of many-to-many


relationships in data

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
73
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Record Based Logical Models

Hierarchical Models
Organization of the records is as a collection of trees, rather
than arbitrary graphs.
In a hierarchical database the parent-child relationship is one
to many. This restricts a child segment to having only one parent
segment

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
74
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Instances , Schemas

Databases changes over time


Instance:
Information in a database at a particular point in time
Schema:
The overall design of the database
Analogy with programming languages:
Data type definition - Schema
Value of a variable - Instance

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
75
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Independence

Ability to modify a schema definition in one level without


affecting a schema definition in a higher level
Physical data independence:
Ability to modify the physical schema without causing
application programs to be rewritten
Modifications at this level are usually to improve
performance
Logical data independence:
Ability to modify the conceptual schema without causing
application programs to be rewritten
Usually done when logical structure of database is altered
Logical data independence is harder to achieve as the application
programs are usually heavily dependent on the logical structure of
the data
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
76
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DBMS Users

The Application Programmer


Who writes programs that operate on the data in the database. The
operations include retrieving,inserting or deleting data.
The End User
Who interacts with the system by invoking the application program.
The end user performs all the basic operations - retrieval, insertion,
updation, deletion.
The Database Administrator
Who is responsible for designing and maintaining the database and
its security.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
77
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Single & Multi User Systems
Single user and Multi-user Systems
• Systems on larger machines are mostly multi-user, while
those on smaller machines are single-user.
• A multi-user system allows access to the same data from
various nodes.
Data - Integrated and Shared
• Integration of data is the unification of several distinct files
with little or no redundancy among them.
• Sharing allows different users to have access to the same
piece of data , though they may use it for different
purposes.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
78
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Database System Components
& Architecture
The components of DBMS are:
• File Manager : Manages allocation of space on the disk and
the way data is represented in the storage.
• Database Manager: Interface between the users and data
stored in the system.
• Query Processor: Translates statements in a query
language to a form that the database manager can
understand.
• DML Pre-compiler: Converts the embedded statements
written in the data sub-language to its equivalent form in the
host language. Interacts with the query processor to
generate appropriate code.
• DDL Compiler: Converts statements to a set of files that
contain data about the data. This information is stored in the
data dictionary
• Data Dictionary: Stores information about the structure of
the database
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
79
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Database System Components &
Architecture
USERS DBA
Application Database
Query
Programs Schema

Query DDL
DML Pre-compiler Processor
compiler
Object Code
Database
Manager
File Manager Data
Dictionary
Data Files Disk
Storage
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
80
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Database System Components &
Architecture
User 1 User 2 User 3

External Schema
(User View)

Conceptual Schema
(Logical View)

Internal Schema
(Physical View)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
81
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
E-R Model

Entity Relationship Model :


• Based on a perception of the world as collection of basic
objects and relationships among these objects
• Identifies the objects with the concept of Entity / Attribute
and Relationships.
Entity / Entity Set:
• An entity is a distinguishable object,place or an event that
exists. E.g: Person
• Entity can be concrete (a person or book for e.g.,) or
abstract( a holiday or a concept ) or an event or a location
• An entity set is a set of entities of the same type (e.g., all
persons having an account at a bank).

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
82
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
E-R Model

Attributes:
• A data element that describes an entity
• Attribute can also describe the properties of Relations
• E.g. Entity Attributes
Student Student ID, Name
Book Title, Author Price

Relationship/ Relationship Sets


• A relationship is an association among several entities.
 e.g. A cust_acct relationship associates a customer with each
account he or she has.
• A relationship can also have properties or attributes
associated with it
• A relationship set is a set of relationships of the same type

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
83
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
E-R Model
Mapping Constraints:
• Also called as the Degree of Relationships
• Expresses the number of ways the entities can be
associated via a relationship
• One To One (1:1)
 An entity in A is associated with at most one entity in B, and an
entity in B is associated with at most one entity in A.
• One-to-many: (1:M)
 An entity in A is associated with any number in B. An entity in B
is associated with at most one entity in A.
• Many-to-many (M:M)
 Entities in A and B are associated with any number from each
other

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
84
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
E-R Model
Keys:
• Differences between entities must be expressed in terms
of attributes.This is done by the use of Keys

Super Key:
• A set of one or more attributes which, taken collectively,
allow us to identify uniquely an entity in the entity set.
 For example, in the entity set customer, customer-name
and S.I.N. is a superkey. Note that customer-name alone is
not, as two customers could have the same name.

Candidate Key:
• Smallest superkey
• A superkey for which no subset is a superkey, is called a
candidate key.
 In the example above, S.I.N. is a candidate key, as it is
minimal, and uniquely identifies a customer entity

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
85
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
E-R Model

Primary Key:
• An attribute or set of attributes that uniquely identifies
a row in a table.
Foreign key:
• A column in one table whose value matches the
primary key in some other table is called a foreign key.
Alternate key:
• Any attribute which is a candidate for primary key but
is not the primary key is an alternate key.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
86
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
E-R Model

Integrity Constraints:
• Refers to the accuracy and correctness of data in the
database
Entity Integrity:
• It means that every row or tuple in a table must be
unique.
Referential Integrity:
• It is called referential integrity because the values in
one column or set of columns must match the values in
some other column or set of columns in another table.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
87
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
E-R Model

E-R Model uses a graphical notation for


representing the data
• Rectangles: represent entity sets.
• Ellipses: represent attributes.
• Diamonds: represent relationships among entity sets.
• Lines: link attributes to entity sets and entity sets to
relationships.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
88
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Relational Model

Proposed by E.F.Codd on the mathematical


concept of relational sets.
Data is organized in logical sets using tabular
structure
Relational Model Components:
• Data Structure : Data is organized
• Data Integrity : Refers to accuracy and correctness of
data
• Data Manipulation :Manipulation of data using the
relational operators.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
89
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Relational Model
Features:
• Does not maintain physical connection between
relations
• Data is organized into two dimensional Relations called
Tables.
• A Table is a collection of relationships.
• A row in a table represents a relationship among a set
of values
• The Intersection of a row and column must contain an
atomic value
• All entries of a column must be of the same kind
• All names of columns must be distinct.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
90
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Relational Model

Query Languages
• A query language is a language in which a user requests
information from a database
• Procedural: where the user instructs the system to
perform a sequence of operations on the database. This
will compute the desired information.
• Nonprocedural: where the user specifies the
information desired without giving a instructions for
obtaining the information. Ex- SQL informs what
operations to perform, doesn’t specify how to perform
• A complete query language also contains facilities to
insert and delete tuples as well as to modify parts of
existing tuples

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
91
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Relational Model

Fundamental Operations:
• The relational algebra is a procedural query language
• Six fundamental operations:
 select
 project
 join
 cartesian product
 union
 set-difference
 Several other operations, defined in terms of the
fundamental operations:
 set-intersection
 natural join
 division
 assignment

 Operations produce a new relation as a result.


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
92
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Relational Model
Selection
• A selection operation extracts or retrieves information from
a table.
Projection
• A projection operation retrieves only a selected number of
attributes from a table.
Cartesian Product
• It is the concatenation of every tuple of one relation with
every tuple of a second relation.
Join
• A join operation extracts data from one or more relations
based on some specific conditions and constructs a resultant
relation

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
93
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Relational Model
Union
• It is formed by combining tuples from one relation with those from
a second relation to produce a third relation.
Intersection
• The intersection of two relations is the third relation containing the
common tuples.
Difference
• The difference of two relations is a third relation containing the
tuples that occur in the first relation but not in the second.
Restriction
• When used in a select statement the comparison operators restrict
the number of tuples retrieved depending on the comparison
operator used.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
94
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Codd's RDBMS Rules
1. Information Representation
The information rule simply requires all information in the
database to be represented in one and only one way, Namely
by values in column positions within rows of tables.
2. Guaranteed Access
It says that every individual scalar value in the database must
be logically addressable by specifying the name of the
containing table, the name of the containing column and the
primary key value of the containing row.
3. Systematic Treatment of Null Values
The DBMS is required to support a representation of "missing
information and inapplicable information" that is systematic,
distinct from all regular values and independent of data type. It
is also implied that such representations must be manipulated
by the DBMS in a systematic way.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
95
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Codd's RDBMS Rules
4. Dynamic On-Line Catalog Based Relational Model
The system is required to support an online, inline, relational
catalog that is accessible to authorized users by means of their
regular query language.
5. Comprehensive Data Sub-Language
The system must support at least one relational language that
(a) has a linear syntax, can be used both interactively and within
application programs, and supports data definition operations, data
manipulation operations, security and integrity constraints, and
transaction management operations.
6. View Updating
All views that are theoretically updatable must be updatable by the
system.
7. High Level Update, Insert, Delete
The system must support INSERT, UPDATE, and DELETE operators.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
96
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Codd's RDBMS Rules
8. Physical Data Independence
9. Logical Data Independence
10. Integrity Independence
Integrity constraints must be specified separately from application
programs and stored in the catalog. It must be possible to change
such constraints as and when appropriate without unnecessarily
affecting existing applications.
11. Distributed Independence
Existing applications should continue to operate successfully (a)
when a distributed version of the DBMS is first introduced; (b)
when existing distributed data is redistributed around the system.
12. Non-Subversion
If the system provides a low-level (record-at-a-time) interface,
then that interface cannot be used to subvert the system (e.g.)
bypassing a relational security or integrity constraint.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
97
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Object Oriented Data Model

Features:
• New applications such as Engineering databases,
Multimedia databases, Office Information Databases
etc., require additional complex features such as:
 Complex objects: A complex object is an item that is viewed as a
single object in the real world, but that contains other objects
 Behavioral data: Distinct objects may need to respond in
different ways to the same command
 Long duration transactions
• Hence a data model that is a logic organization of the
real world objects (entities), constraints on them, and
the relationships among objects was introduced.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
98
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Object Oriented Data Model
A core object-oriented data model consists of the
following basic object-oriented concepts:
• Object and object identifier:
 Any real world entity is uniformly modeled as an object
(associated with a unique id)
• Attributes and methods:
 Every object has a state (the set of values for the
attributes of the object) and a behavior (the set of
methods - program code - which operate on the state of
the object). The state and behavior encapsulated in an
object are accessed or invoked from outside the object
only through explicit message passing.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
99
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Object Oriented Data Model

• Class:
 A means of grouping all the objects which share the same
set of attributes and methods. An object must belong to
only one class as an instance of that class (instance-of
relationship). A class is similar to an abstract data type

• Class hierarchy and inheritance:


 Derive a new class (subclass) from an existing class
(superclass). The subclass inherits all the attributes and
methods of the existing class and may have additional
attributes and methods.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
100
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Object Oriented Data Model

Object Structure:
• The object-oriented paradigm is based on encapsulating
code and data into a single unit. Conceptually, all
interactions between an object and the rest of the system
are via messages
• In general, an object has associated with it:
 A set of variables that contain the data for the object.
The value of each variable is itself an object.
 A set of messages to which the object responds.
 A set of methods, each of which is a body of code to
implement each message; a method returns a value as
the response to the message
• The ability to modify the definition of an object without
affecting the rest of the system is considered to be one of
the major advantages of the OO programming paradigm.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
101
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Object Oriented Data Model

Object Classes:
• Usually, there are many similar objects in a DB.
• By “similar”, it means that they respond to the same
messages, use the same methods, and have variables of
the same name and type.
• We group similar objects to form a class.
• Each such object is called an instance of its class. E.g., in
a bank DB, customers, accounts and loans are classes.
• Class:
 captures the instance-of relationship,
 the basis on which a query may be formulated,
 enhance the integrity of OO systems by introducing type
checking,
 reducing replications of names and integrity-related
specifications among objects in the same class.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
102
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Object Oriented Data Model
Inheritance:
• An object-oriented database schema typically requires a large
number of classes. Often, however, several classes are similar.
 For example, bank employees are similar to customers
• In order to allow the direct representation of similarities among
classes, we need to place classes in a specialization hierarchy.
• This in turn routes to derivation of some attributes from the
existing attributes
• An important benefit of inheritance in OO systems is the notion
of substitutability.
• This characteristic leads to code-reuse
Multiple Inheritance:
• The ability of class to inherit variables and methods from
multiple super classes.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
103
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Object Oriented Data Model
Object Identity:
• An object retains its identity even if some or all of the
values of variables or definitions of methods change over
time
• Several forms of identity:
 value: A data value is used for identity (e.g., the primary
key of a tuple in a relational database).
 name: A user-supplied name is used for identity (e.g., file
name in a file system).
 built-in: A notion of identity is built-into the data model
or programming languages
• Object identity is typically implemented via a unique,
system-generated OID.
• The value of the OID is not visible to the external user,
but is used internally by the system to identify each object
uniquely and to create and manage inter-object references

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
104
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Object Oriented Data Model

Object Relational :
• The concepts of object-orientation can be used purely as
a design tool and are encoded into a relational database
to form a O - RDBMS.
• The concepts of object-orientation are incorporated into a
language that is used to operate the database. There are
several possible languages into which the concepts are
integrated. E.g: Oracle 8i
• Systems that provide object-oriented extensions to
relational systems are called object-relational systems.
• Features: complex data types, powerful query languages,
high protection.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
105
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization
Main objective in developing a logical data
model for relational database systems is to
create an accurate representation of the data,
its relationships, and constraints.
To achieve this objective, you should identify a
suitable set of relations.
A relation can be normalized to a specific form
to prevent possible occurrence of update
anomalies.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
106
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization

Normalization : Process of refining the E-R


Model
• Based on functional dependencies among the attributes of
a relation.
• Segregation of data over many entities or tables
• This technique logically groups the data over a number of
tables, not to contain unnecessary data.
• The normalized entities contain simple data items, with
the relationships being represented by replication of key
data items

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
107
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization

Data Redundancy:
• Major aim of relational database design is to group
attributes into relations to minimize data redundancy and
reduce file storage space required.
• Problems associated with data redundancy are illustrated
by comparing the following Staff and Branch relations
with Staff Branch Relation:
• Staff Branch relation has redundant data: details of a
branch are repeated for every member of staff.
• In contrast, branch information appears only once for each
branch in Branch relation and only branch No is repeated
in Staff relation, to represent where each member of staff
works.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
108
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
109
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization

Relations that contain redundant information


may potentially suffer from update anomalies.
Types of update anomalies include:
• Insertion
• Deletion
• Modification
Two important properties of decomposition:
• Lossless-join property enables us to find any instance
of original relation from corresponding instances in the
smaller relations.
• Dependency preservation property enables us to
enforce a constraint on original relation by enforcing some
constraint on each of the smaller relations.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
110
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization
Functional Dependency:
• Main concept associated with normalization.
• Describes relationship between attributes in a relation.
• If A and B are attributes of relation R, B is functionally
dependent on A ( denoted A B), if each value of A
in R is associated with exactly one value of B in R.
• Diagrammatic representation:

 Determinant of a functional dependency refers to attribute or group of


attributes on left-hand side of the arrow.
 Dependent of a functional dependency refers to attribute or group of
attributes on right-hand side of the arrow.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
111
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization

Process of Normalization:
Formal technique for analyzing a relation based on its primary
key and functional dependencies between its attributes.
Often executed as a series of steps.
Each step corresponds to a specific normal form, which has
known properties.
As normalization proceeds, relations become progressively
more restricted ( stronger) in format and also less vulnerable to
update anomalies.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
112
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization
Process of Normalization:
• First Step: Convert E-R Model into Tables or Relations
• Second Step: Examine for redundancy and convert them
to non-redundant forms
• Third Step: Convert the Non-redundant model to a
database definition
Need for Normalization:
• Improves database design
• Ensures need to reorganize data when design is
modified / enhanced
• Removes anomalies for database activities
Denormalization:
• Defines the process of making an unnormalized data
structure.
• Contains redundant and disorganized data

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
113
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization
First Normal Form (1 NF)
• A relation in which intersection of each row and column
contains one and only one value
• A table is said to be in First Normal Form when it
contains no repeating groups.
Process:
• Identify repeating groups of fields
• Remove the repeating groups to a separate table.Such a
table becomes dependent of the parent table from which
it is derived.
• Identify the keys for the tables.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
114
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization

Ist Normal Form

ecode dept projcode hours hod


E01 systems p10 60 E11
E01 systems p25 55 E11
E01 systems p35 100 E11
E02 sales p20 75 E22
E03 admin p30 90 E33
E03 admin p40 80 E33

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
115
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization
Second Normal Form (2 NF)
• Based on concept of full functional dependency:
 A and B are attributes of a relation, B is fully dependent on
A
 If B is functionally dependent on A but not on any proper
subset of A.
• A table is said to be in the Second Normal Form of all its
non-key fields are fully dependent on the whole key
 i.e : A relation that is in 1NF and every non primary- key
attribute is fully functionally dependent on the primary key.
• This means that each field in the table must depend
upon the entire key.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
116
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization
Second Normal Form (2 NF)
Process:
• Identify primary key for the 1NF relation.
• Check if the fields are dependent on the whole key.
Identify the functional dependencies in the relation
• Remove fields that depend on part of the key
• Group partially dependent fields as a separate table
• Name the tables
• Identify keys to the tables

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
117
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization
A table is said to be in 2NF when it is in 1NF and
every non-key attribute is functionally
dependent on the primary key.
Non-loss decomposition
ecode projcode hours Table in 2NF
E01 P10 60 dept
ecode hod
E01 p25 55 systems E11
E01
E01 p35 100 sales E22
E02
E02 p20 75 admin E33
E03
E03 p30 90
E03 p40 80

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
118
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization
Third Normal Form ( 3 NF)
• Based on concept of transitive dependency:
 A , B and C are attributes of a relation such that if A
B and B C,
 then C is transitively dependent on A through B.( Provided
that A is not functionally dependent on B or C)
• 3NF - A relation that is in 1NF and 2NF and in which no
non-primary-key attribute is transitively dependent on
the primary key.
• A table is said to be in the Third Normal Form if all the
non-key fields of the table are independent of all other
non-key fields of the same table

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
119
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization
Third Normal Form ( 3 NF)
Process:
• Identify the primary key in the 2NF relation.
• Identify functional dependencies in the relation.
• If transitive dependencies exist on the primary key,
Remove the fields that depend on other non-key fields
• Place them in a new relation along with copy of their
determinant.
• Group interdependent fields as a separate table, identify
the key and name the table

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
120
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Third Normal Form
A relation is in third normal form if it is in 2NF
and has no transitive dependencies (no mutual
dependencies)

dept hod ecode dept


systems E11 E01 systems
sales E22 E02 sales
admin E33 E03 admin

Table in 3NF

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
121
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization
The third normal form in most situations was
inadequate as:
• Systems had multiple candidate keys that were
composite.
• Candidate keys overlapped.
• To solve this the Boyce-Codd NF was introduced.
BCNF:
• A relation is in Boyce-Codd NF if every determinant is a
candidate key.
• Difference between 3NF and BCNF is that for a functional
dependency A . B, 3NF allows this dependency in a relation
if B is a primary key attribute and A is not a candidate key.
• Whereas, BCNF insists that for this dependency to remain
in a relation, A must be a candidate key.
• Every relation in BCNF is also in 3NF.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
122
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization
UNF To BCNF (Unnormalized FormTo BCNF)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
123
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization

UNF To BCNF

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
124
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization
UNF To BCNF

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
125
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization
ecode name projcode hours
E01 Miller p10 60
E01 Miller p25 55
E01 Miller p35 100
E02 Jones p20 75
E03 Smith p30 90
E03 Smith p40 80
• Normal Form
ecode projcode hours ecode name
E01 p10 60 E01 Miller
E01 p25 55 E02 Jones
E01 p35 100 E03 Smith
E02 p20 75
E03 p30 90
E03 p40 80

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
126
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization

Fourth Normal Form ( 4 NF)


• Although BCNF removes anomalies due to functional
dependencies, another type of dependency called a multi-
valued dependency (MVD) can also cause data redundancy.
• Possible existence of MVDs in a relation is due to 1NF and
can result in data redundancy.
• Dependency between attributes ( for example, A, B, and C)
in a relation, such that for each value of A there is a set of
values for B and a set of values for C. However, set of
values for B and C are independent of each other.
• MVD between attributes A, B, and C in a relation using the
following notation:
 A ->> B
 A ->> C

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
127
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization
Fourth Normal Form ( 4 NF)
• MVD can be further defined as being trivial or nontrivial.
 MVD A ->> B in relation R is defined as being trivial if ( a) B
is a subset of A or ( b) A B = R.
 MVD is defined as being nontrivial if neither ( a) nor (b) are
satisfied.
 Trivial MVD does not specify a constraint on a relation,
while a nontrivial MVD does specify a constraint.
Defined as a relation that is in BCNF and
contains no nontrivial MVDs.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
128
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization

Fourth Normal Form ( 4 NF)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
129
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization

Fifth Normal Form ( 5 NF)


• A relation decomposed into two relations must have
lossless-join property, which ensures that no spurious
tuples are generated when relations are reunited through
a natural join.
• However, there are requirements to decompose a relation
into more than two relations.
• Although rare, these cases are managed by join
dependency and fifth normal form ( 5NF).
A relation that has no join dependency.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
130
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization

Fifth Normal Form ( 5 NF)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
131
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Normalization

Fifth Normal Form ( 5 NF)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
132
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Programming in SQL
Server

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States
For Internal Use Only
www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics to be covered
 Introduction to Databases
 Elements of Transact - SQL
 Data Types
 Data Tables
 Data Integrity
 Indexes
 Querying Techniques
 Stored Procedures
 Views
 Triggers
 Cursors

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
134
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics to be covered
(Continued)
 Temporary Tables
 Error Handling
 DB Coding Standards
 Case Studies

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
135
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to Databases
 DBMS vs RDBMS
 Normalization
 Codd’s 12 Rules
 Introduction to SQL Server

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
136
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to Databases
(Continued)
CODD’s 12 Rules
 Rule 1: The Information Rule
All data should be presented to the user in table form.
 Rule 2: Guaranteed Access Rule
All data should be accessible without ambiguity. This can be accomplished through a
combination of the table name, primary key, and column name.
 Rule 3: Systematic Treatment of Null Values
A field should be allowed to remain empty. This involves the support of a null value, which
is distinct from an empty string or a number with a value of zero. Of course, this can't apply
to primary keys. In addition, most database implementations support the concept of a nun-
null field constraint that prevents null values in a specific table column.
 Rule 4: Dynamic On-Line Catalog Based on the Relational Model
A relational database must provide access to its structure through the same tools that are
used to access the data. This is usually accomplished by storing the structure definition
within special system tables.

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
137
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to Databases
(Continued)
 Rule 5: Comprehensive Data Sub language Rule
The database must support at least one clearly defined language that includes functionality
for data definition, data manipulation, data integrity, and database transaction control. All
commercial relational databases use forms of the standard SQL (Structured Query
Language) as their supported comprehensive language .
 Rule 6: View Updating Rule
Data can be presented to the user in different logical combinations, called views. Each view
should support the same full range of data manipulation that direct-access to a table has
available. In practice, providing update and delete access to logical views is difficult and is
not fully supported by any current database.
 Rule 7: High-level Insert, Update, and Delete
Data can be retrieved from a relational database in sets constructed of data from multiple
rows and/or multiple tables. This rule states that insert, update, and delete operations
should be supported for any retrievable set rather than just for a single row in a single table .
 Rule 8: Physical Data Independence
The user is isolated from the physical method of storing and retrieving information from the
database. Changes can be made to the underlying architecture ( hardware, disk storage
methods ) without affecting how the user accesses it.

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
138
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to Databases
(Continued)
 Rule 9: Logical Data Independence
How a user views data should not change when the logical structure (tables structure) of the
database changes. This rule is particularly difficult to satisfy. Most databases rely on strong
ties between the user view of the data and the actual structure of the underlying tables.
 Rule 10: Integrity Independence
The database language (like SQL) should support constraints on user input that maintain
database integrity. This rule is not fully implemented by most major vendors. At a minimum,
all databases do preserve two constraints through SQL.
 No component of a primary key can have a null value. (see rule 3)
 If a foreign key is defined in one table, any value in it must exist as a primary key in another table.
 Rule 11: Distribution Independence
A user should be totally unaware of whether or not the database is distributed (whether parts
of the database exist in multiple locations). A variety of reasons make this rule difficult to
implement;
 Rule 12: Non subversion Rule
There should be no way to modify the database structure other than through the multiple row
database language (like SQL). Most databases today support administrative tools that allow
some direct manipulation of the data structure .

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
139
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to Databases
(Continued)
Introduction to SQL Server

Results
Results

Transact-SQL
Transact-SQL
Application
Application
Client SQL Server
Relational Database
Management System

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
140
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Elements of Transact - SQL
 Data Manipulation Language(DML) Statements
 Data Control Language(DCL) Statements
 Data Definition Language(DDL) Statements
 Operators
 Functions
 Control of Flow Language Elements

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
141
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DML Statements
 SELECT
 Syntax :
select {[alias.]column name}[, {[alias.]column name}[, …]]
from {database name}.{object owner}.{table name} [[{alias 1}] [inner
join {database name}.{owner name}.{table name} [{alias 2}] on {alias
1}.{column name} = {alias 2}.{column name}[{next join}]]
[where {constraint condition}[and {constraint condition}[…]]]
[group by {column [list]}
[having {constraint condition}]]
[order by {column [list]}][{union}{next select statement}]
 Example:
Select empno, empname
from employee
group by dept
order by empno
For Internal Use Only
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
142
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DML Statements
(Continued)
 INSERT
 Syntax :
insert [into] {database name}.{owner}.{table name}
({column name}[,{column name}[,…}})
values
({value or variable}[,{value or variable}[,}…]]
 Example:
insert Parts.dbo.TB_TOASTER (TOASTER_ID,
MANUFACTURER_ID, NAME, NOTES)
values
(1,1, 'spring', 'cross sell handle latch')

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
143
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DML Statements
(Continued)
 UPDATE
 Syntax :
update {database name}.{owner}.{table name}
set {column} = {expression}[,{column} = {expression}[,…]]
{where clause}
 Example:
update Articles.dbo.TB_STATISTICS
set READ_HITS = READ_HITS + 1,LAST_READ_DT =
current_timestamp
where ARTICLE_ID = @pArticleId

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
144
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DML Statements
(Continued)
 DELETE
 Syntax :
delete [from] {database name}.{owner}.{table name}
{where clause}
 Example:
delete from WebLog.dbo.TB_ARTICLE_STATISTICS
where ARTICLE_ID = @pArticleId

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
145
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DCL Statements
 GRANT
Syntax:
GRANT { ALL | statement [ ,...n ] }
TO security_account [ ,...n ]
 DENY
Syntax:
DENY { ALL | statement [ ,...n ] }
TO security_account [ ,...n ]
 REVOKE
Syntax :
REVOKE { ALL | statement [ ,...n ] } FROM security_account
[ ,...n ]

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
146
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DDL Statements
 CREATE
Partial Syntax :
CREATE <Object Name>
 ALTER
Partial Syntax :
ALTER <Object Name>
 DROP
Partial Syntax :
DROP <Object Name>

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
147
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Operators
 Arithmetic
 Bit-wise
 Comparison
 Logical
 Concatenation
 Unary

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
148
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Operators
(Continued)
 Arithmetic
 = assignment operator
 + addition
 - subtraction
 * multiplication
 / divide
 % modulo or remainder from division

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
149
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Operators
(Continued)
 Bit-Wise
 & (AND)
 | (OR)
 ^ (Exclusive OR)
 ~ (NOT)

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
150
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Operators
(Continued)
 Comparison
 = equal to
 <> not equal to
 < less than
 > greater than
 <= less than or equal to
 >= greater than or equal to

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
151
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Operators
(Continued)
 Logical
 AND
 OR
 NOT
 BETWEEN
 LIKE
 IN
 Concatenation
 The (+) Plus sign is used to concatenate strings
 Unary
 + (Positive)
 - (Negative)

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
152
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Functions
 Aggregate Functions
 Date and Time Functions
 Mathematical Functions
 String Functions
 System Functions

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
153
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Functions
(Continued)
 Aggregate Functions
 AVG
 COUNT
 MAX
 MIN
 SUM

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
154
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Functions
(Continued)
 Date and Time Functions
 DATEADD
 DATEDIFF
 DATENAME
 DATEPART
 GETDATE

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
155
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Functions
(Continued)
 Mathematical
Functions  LOG
 ABS  LOG10
 ACOS  PI
 ASIN  POWER
 RADIANS
 ATAN
 RAND
 ATN2
 ROUND
 CEILING  SIGN
 COS  SIN
 COT  SQRT
 DEGREES  TAN
 EXP
 FLOOR

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
156
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Functions
(Continued)
 String Functions
 NCHAR  STR
 CHARINDEX  STUFF
 LEN  SUBSTRING
 LOWER  UNICODE
 LTRIM  UPPER
 PATINDEX
 REPLACE
 REPLICATE
 RTRIM
 SPACE

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
157
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Functions
(Continued)
 System Functions
 CASE
 COALESCE
 CONVERT
 DATALENGTH
 NEWID

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
158
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Control of Flow Language Elements
 Statement Level
 Row Level

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
159
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Control of Flow Language Elements
(Continued)
 Statement Level
 Begin … End Block
 IF … ELSE Block
 WHILE constructs

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
160
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Control of Flow Language Elements (Continued)
 Row Level
 CASE Expression

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
161
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Control of Flow Language Elements
(Continued)
 Begin … End Block
Syntax:
BEGIN
{
sql_statement
| statement_block
}
END

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
162
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Control of Flow Language Elements (Continued)
 IF … ELSE Block
Syntax
IF Boolean_expression
{ sql_statement | statement_block }
[ ELSE
{ sql_statement | statement_block } ]

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
163
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Control of Flow Language Elements (Continued)

 While Constructs
Syntax:
WHILE Boolean_expression
{ sql_statement | statement_block }
[ BREAK ]
{ sql_statement | statement_block }
[ CONTINUE ]

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
164
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Control of Flow Language Elements (Continued)
 CASE Expression
Syntax:
CASE input_expression
WHEN when_expression THEN result_expression
[ ...n ]
[
ELSE else_result_expression
]
END

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
165
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Types
 Limited character
 Unlimited character
 Binary
 Binary large object
 Integer
 Approximate numeric
 Exact numeric
 Date and time
 Currency
 Other

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
166
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Types
(Continued)
 Limited Character
 CHAR – Fixed-length character data up to 8,000 characters
 VARCHAR – Variable-length character data up to 8,000 characters
 NCHAR – Fixed-length Unicode character data up to 4,000
characters
 NVARCHAR – Variable-length Unicode character data up to 4,000
characters
 Unlimited Character
 TEXT – Variable-length character data up to 2,147,483,647 characters (2
MB)
 NTEXT – Variable-length Unicode character data 1,073,741,823
characters (1 MB)
 Binary
 BINARY – Fixed-length binary data up to 8,000 bytes
 VARBINARY – Variable-length binary data up to 8,000 bytes

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
167
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Types
(Continued)
 Binary Large Objects
 IMAGE – Variable-length binary data up to 2,147,483,647 bytes
 Integers
 BIGINT – Integer from –2^63 to 2^63-1
 INT – -2,147,483,648 to 2,147,483,647
 SMALLINT – -32,768 to 32,767
 TINYINT – 0 to 255
 BIT – Binary integer two possible values 0 or 1
 Approximate Numeric
 REAL – Approximate numbers with a precision between 1 and
7, 4 bytes of storage
 FLOAT – Approximate numbers with a precision between 8 and
15, 8 bytes of storage

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
168
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Types
(Continued)
 Exact Numeric
 DECIMAL – Exact numbers that use up to 17 bytes of storage
 NUMERIC – Synonym of DECIMAL
 Date and Time
 DATETIME – Date and time data from January 1, 1753 to December
31, 9999
 SMALLDATETIME – Date and time from January 1, 1900 to June 6, 2079
 Currency
 MONEY – Currency data from -922,337,203,685,477.5808 to
922,337,203,685,477.5807
 SMALLMONEY – Currency data from -214,748.3648 to 214,748.3647

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
169
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Types
(Continued)
 Other
 UNIQUEIDENTIFIER – 16-byte GUID
 TABLE – Similar to a table database object and used
just for temporary storage
 SQL_VARIANT – Can store any Transact-SQL data type
except TEXT, NTEXT, IMAGE, TIMESTAMP
and itself, similar to VARIANT data type in
Visual Basic
 TIMESTAMP/ ROWVERSION – 8-byte binary number that changes every
time a column is inserted or updated
 CURSOR – Used only for variables and stored
procedures
 User Defined Data Types(UDDTS)

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
170
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Tables
 Creating Table
 Dropping Table
 Adding and Dropping Columns

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
171
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Tables
(Continued)
 Creating Table
Partial Syntax :
CREATE TABLE
[ database_name.[ owner ] . | owner. ] table_name
( { < column_definition >
| column_name AS computed_column_expression
| < table_constraint > ::= [ CONSTRAINT constraint_name ] }
| [ { PRIMARY KEY | UNIQUE } [ ,...n ]
)

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
172
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Tables
(Continued)
 Dropping Table
Syntax :
DROP TABLE table_name

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
173
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Tables
(Continued)
Adding and Dropping Columns
Partial Syntax:
ALTER TABLE table
{
[ ALTER COLUMN column_name
{ new_data_type [ ( precision [ , scale ] ) ]
[ COLLATE < collation_name > ]
[ NULL | NOT NULL ]
| {ADD | DROP } ROWGUIDCOL }
]
| DROP
{ [ CONSTRAINT ] constraint_name
| COLUMN column } [ ,...n ]
}
}

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
174
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Integrity

Types of Integrity and Constraints


 Domain
 DEFAULT
 CHECK
 Entity
 PRIMARY KEY
 UNIQUE
 Referential
 FOREIGN KEY
 CHECK

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
175
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Indexes
 PROS and CONS of Index.
 Types of Indexes
 Creating and Dropping Indexes
 Indexing Guidelines

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
176
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Indexes
(Continued)
PROS and CONS of Indexes
 Why to create an Index
 Speeds up data access
 Enforces uniqueness of rows
 Why not to create an Index
 Consumes disk space
 Incurs overhead

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
177
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Indexes
(Continued)
Types of Indexes
 Clustered
 Each Table can have only one clustered Index
 The physical row order of the table and the order of rows in the index
are the same
 Key value uniqueness is maintained explicitly or implicitly
 Non clustered
 SQL Server Default

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
178
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Indexes
(Continued)
Creating Index
Partial Syntax:
CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX
index_name
ON { table | view } ( column [ ASC | DESC ] [ ,...n ] )
[ WITH < index_option > [ ,...n] ]
Dropping Index
Syntax:
DROP INDEX 'table.index | view.index' [ ,...n ]

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
179
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Indexes
(Continued)
Indexing Guidelines
 Columns to Index
 Primary and foreign keys
 Those frequently searched in ranges
 Those frequently accessed in sorted order
 Columns not to Index
 Those seldom referenced in queries
 Those that contain few unique values
 Those defined with bit, text, or image data types

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
180
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Querying Techniques
 Joins
 Unions
 Sub Queries

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
181
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Querying Techniques
(Continued)
Joins
 Types of Joins
 Inner Join
 Outer Join
 Cross Join
 Self Join
 Partial Syntax
SELECT column_name[,column_name...]
[ FROM { < table_source > } [ ,...n ] ]
< join_type > ::=
[ INNER | { { LEFT | RIGHT | FULL } [ OUTER] } ]
[ < join_hint > ]
JOIN
< joined_table > ::=
< table_source > < join_type > < table_source > ON < search_condition >
| < table_source > CROSS JOIN < table_source >
| [ ( ] < joined_table > [ ) ]

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
182
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Querying Techniques
(Continued)
Unions
 UNION
 UNION ALL

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
183
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Querying Techniques
(Continued)
Sub Queries
 Nested Sub queries
 Correlated Sub queries

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
184
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Stored Procedures
 Introduction to Stored Procedures
 Processing of Stored procedures
 Advantages of Stored procedures
 Creating , Executing, Altering and Dropping
Stored Procedures
 Using parameters in stored procedures
 Executing Extended Stored Procedures
 Handling Error Messages

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
185
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Stored Procedures
(Continued)
Introduction to Stored Procedures
 Named Collections of Transact-SQL Statements
 Encapsulate Repetitive Tasks
 Five Types (System, Local, Temporary, Remote, and Extended)
 Accept Input Parameters and Return Values
 Return Status Value to Indicate Success or Failure

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
186
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Stored Procedures
(Continued)
Initial Processing

Creation
Creation Parsing
Parsing
Entries
Entries into
into sysobjects
sysobjects
and
and syscomments
syscomments tables
tables

Execution
Execution
(first Optimization
Optimization
(firsttime
time
or
orrecompile)
recompile)

Compilation
Compilation Compiled
Compiled plan
plan placed
placed in
in
procedure
procedure cache
cache

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
187
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Stored Procedures
(Continued)
Subsequent Process

Execution
Execution
(subsequent
(subsequent times)
times)
 Environment Remains the
Same
 Objects Do Not Require
Name Resolution

LRU
Compiled
Compiled plan
plan retrieved
retrieved
from
from procedure
procedure cache
cache

Least
Least recently
recently used
used (LRU)
(LRU)
plan
plan is
is replaced
replaced

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
188
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Stored Procedures
(Continued)
Advantages of Stored procedures
 Share Application Logic
 Provide Security Mechanisms
 Execute Automatically
 Increase Performance
 Reduce Network Traffic

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
189
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Stored Procedures
(Continued)
Creating , Executing, Altering and Dropping
Stored Procedures
 Creating Procedure
Syntax:
CREATE PROC [ EDURE ] procedure_name [ ; number ]
[ { @parameter data_type }
[ VARYING ] [ = default ] [ OUTPUT ]
] [ ,...n ]
 Executing Stored Procedures
Executing a Stored Procedure by Itself
Syntax:
Execute <SP_Name>

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
190
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Stored Procedures
(Continued)
Creating , Executing, Altering and Dropping
Stored Procedures
 Altering Stored Procedures
Partial Syntax
ALTER PROC [ EDURE ] procedure_name [ ; number ]
[ { @parameter data_type }
[ VARYING ] [ = default ] [ OUTPUT ]
] [ ,...n ]
AS
sql_statement [ ...n ]
 Dropping Stored Procedures
Partial Syntax
DROP PROCEDURE { procedure } [ ,...n ]

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
191
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Stored Procedures
(Continued)
Using parameters in stored procedures
 Using Input Parameters
 Executing Stored Procedures with Input Parameters
 Returning Values with Output Parameters
 Explicitly Recompiling Stored Procedures

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
192
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Stored Procedures
(Continued)
Using Input Parameters
 Trap Missing or Invalid Parameter Values First
 Provide Appropriate Default Values

CREATE
CREATE PROC
PROC dbo.find_isbn
dbo.find_isbn
@title
@title longstring
longstring == null,
null,
@translation
@translation char(8)
char(8) == 'English'
'English'
AS
AS
IF
IF @title
@title isis null
null
BEGIN
BEGIN
PRINT
PRINT "Please
"Please provide
provide aa title
title
(or
(or partial
partial title)
title) and
and the
the translation"
translation"
PRINT
PRINT "find_isbn
"find_isbn 'Oliver%',
'Oliver%', 'Japanese'"
'Japanese'"
..
..
..

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
193
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Stored Procedures
(Continued)

Executing Stored Procedures with Input


 Parameters
Passing Values by Reference
EXEC
EXEC addadult
addadult
@firstname
@firstname == 'Linda',
'Linda',
@lastname
@lastname == 'LaBrie',
'LaBrie',
@street
@street == 'Dogwood
'Dogwood Drive',
Drive',
@city
@city == 'Sacramento',
'Sacramento',
@state
@state == 'CA',
'CA',
@zip
@zip == '94203'
'94203'

 Passing Values by Position


EXEC
EXEC addadult
addadult 'LaBrie',
'LaBrie', 'Linda',
'Linda', null,
null,
'Dogwood
'Dogwood Drive',
Drive', 'Sacramento',
'Sacramento', 'CA',
'CA',
'94203',
'94203', null
null

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
194
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Stored Procedures
(Continued)
Returning Values with Output Parameters

CREATE
CREATE PROCEDURE
PROCEDURE dbo.mathtutor
dbo.mathtutor
Creating
CreatingStored
Stored @m1
@m1 smallint,
smallint,
Procedure
Procedure @m2
@m2 smallint,
smallint,
@result
@result smallint
smallint OUTPUT
OUTPUT
AS
AS
SET
SET @result
@result == @m1
@m1 ** @m2
@m2
Executing
ExecutingStored
Stored
Procedure DECLARE
DECLARE @answer
@answer smallint
smallint
Procedure
EXECUTE
EXECUTE mathtutor
mathtutor 5,
5, 6,
6, @answer
@answer OUTPUT
OUTPUT
SELECT
SELECT 'The
'The result
result is:
is: '' ,, @answer
@answer

Results
ResultsofofStored
Stored
Procedure
Procedure The
The result
result is:
is: 30
30

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
195
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Stored Procedures
(Continued)
Explicitly Recompiling Stored Procedures

 Recompile When
 Stored procedure returns widely varying result sets
 A new index is added to an underlying table
 The parameter value is atypical
 Recompile by Using
 CREATE PROCEDURE [WITH RECOMPILE]
 EXECUTE [WITH RECOMPILE]
 sp_recompile

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
196
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Stored Procedures
(Continued)
Executing Extended Stored Procedures
 Increase SQL Server Functionality
 Are Programmed Using Open Data Services API
 Can Include C and C++ Features
 Can Contain Multiple Functions
 Can Be Called from a Client or SQL Server
 Can Be Added to the master Database Only

EXEC master..xp_cmdshell 'dir c:\mssql7'

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
197
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Stored Procedures
(Continued)
Handling Error Messages

 RETURN Statement Exits Query or


Procedure Unconditionally
 sp_addmessage Creates Custom Error
Messages
 @@error Contains Error Number for Last
Executed Statement
 RAISERROR Statement
 Returns user-defined or system error message
 Sets system flag to record error

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
198
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Views
 Introduction to Views
 Advantages of Views
 Defining Views
 Modifying Data Through Views
 Performance Considerations

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
199
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to Views

title
title
title_no
title_no title
title author
author synopsis
synopsis
11 Last
Lastofofthe theMohicans
Mohicans James
JamesFenimore
FenimoreCooper
Cooper ~~~
~~~
22 The
TheVillage
VillageWatch-Tower
Watch-Tower Kate
KateDouglas
DouglasWiggin
Wiggin ~~~
~~~
33 Poems
Poems Wilfred
WilfredOwen
Owen ~~~
~~~

CREATE
CREATE VIEW
VIEW dbo.TitleView
dbo.TitleView
AS
AS
SELECT
SELECT title,
title, author
author
FROM title
FROM title

TitleView
TitleView
title
title author
author
Last
Lastofofthe theMohicans
Mohicans James
JamesFenimore
FenimoreCooper
Cooper User’s
User’sView
View
The
TheVillage
VillageWatch-Tower
Watch-Tower Kate
KateDouglas
DouglasWiggin
Wiggin
Poems
Poems Wilfred
WilfredOwen
Owen

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
200
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Advantages of Views
 Focus the Data for Users
 Focus on important or appropriate data only
 Limit access to sensitive data
 Mask Database Complexity
 Hide complex database design
 Simplify complex queries, including distributed queries to
heterogeneous data
 Simplify Management of User Permissions
 Organize Data for Export to Other Applications

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
201
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Defining Views
 Creating Views
 Altering and Dropping Views

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
202
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Views
 Creating a View

USE
USElibrary
library
Go
Go
CREATE
CREATEVIEW VIEWdbo.UnpaidFinesView
dbo.UnpaidFinesView(Member,
(Member,TotalUnpaidFines)
TotalUnpaidFines)
AS
AS
SELECT
SELECTmember_no,
member_no,(sum(fine_assessed-fine_paid))
(sum(fine_assessed-fine_paid))
FROM
FROMloanhist
loanhist
GROUP
GROUPBY BYmember_no
member_no
HAVING
HAVING SUM(fine_assessed-fine_paid)>>00
SUM(fine_assessed-fine_paid)
GO
GO

 Restrictions on View Definitions


 ORDER BY, COMPUTE, or COMPUTE BY clauses
 INTO keyword

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
203
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Views (Continued)
Example : View of Joined Tables
member_no
member_no lastname
lastname firstname
firstname middleinitial
middleinitial photograph
photograph member_no
member_no adult_no
adult_no birth_date
birth_date
1111 Thomas
Thomas Gary
Gary ~~~
~~~ ~~~
~~~ 1212 1111 1992-01-16
1992-01-1600:00:00.000
00:00:00.000
1212 Thomas
Thomas Clair
Clair ~~~
~~~ ~~~
~~~ 1313 66 1984-01-18 00:00:00.000
1984-01-18 00:00:00.000
1313 Funk
Funk Frank
Frank ~~~
~~~ ~~~
~~~
1414 Rudd
Rudd Clair
Clair ~~~
~~~ ~~~
~~~

USE
USE library
library
GO
GO BirthdayView
CREATE
CREATE VIEW
VIEW dbo.BirthdayView Lastname
dbo.BirthdayView LastnameFirstname
FirstnameBirth
BirthDate
Date
(Lastname,
(Lastname, Firstname,
Firstname, Birthdate) Thomas
Birthdate) Thomas Clair
Clair 92.01.16
92.01.16
AS
AS Funk Frank 84.01.18
Funk Frank 84.01.18
SELECT
SELECT lastname,
lastname, firstname,
firstname,
CONVERT(char(8),
CONVERT(char(8), birth_date,
birth_date, 2)
2)
FROM member JOIN juvenile
FROM member JOIN juvenile
ON
ON member.member_no
member.member_no == juvenile.member_no
juvenile.member_no

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
204
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Altering and Dropping Views
 Altering Views

ALTER
ALTER VIEW
VIEW dbo.TitleView
dbo.TitleView
AS
AS
SELECT
SELECT title,
title, authors,
authors, synopsis
synopsis
FROM title
FROM title

 Dropping Views

DROP
DROP VIEW
VIEW UnpaidFinesView
UnpaidFinesView

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
205
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Modifying Data Through Views
 Cannot Affect More Than One Underlying Table
 Cannot Be Made to Certain Columns
 Can Cause Errors if They Affect Tables with
Columns That Do Not Have Default Values or
Accept NULLs
 Are Verified if the WITH CHECK Option Has
Been Specified

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
206
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Performance Considerations
title
title USE
USE library
library
11item ~~
item ~~ ~~ nn GO
GO
copy CREATE
CREATE VIEW
VIEW dbo.LoanableView
2211~~copy
~~ ~~~~ ~~~~nnnn dbo.LoanableView
1 ~ ~ ~ n AS
3322~~1~~ ~ ~~~~ ~ ~~~~yy~nn n
AS
2 ~ ~ ~ n SELECT
SELECT **
4433~~2~~ ~ ~~~~ ~ ~~~~yy~yy n FROM
FROM CopywideView
CopywideView
3 ~ ~ ~ y
5544~~3~~ ~ ~~~~ ~ ~~~~nn~yy y WHERE
WHERE loanable
loanable == 'y'
'y'
4 ~ ~ ~ y
6655~~4~~ ~ ~~~~ ~ ~~~~yy~nn y
66 55~~ ~~ ~~ ~~ ~~ ~~yy nn
66 ~~ ~~ ~~ yy
CopywideView
CopywideView LoanableView
LoanableView
11 ~~ ~~ ~~ nn 33 ~~ ~~ ~~ yy
22 ~~ ~~ ~~ nn 44 ~~ ~~ ~~ yy
33 ~~ ~~ ~~ yy 66 ~~ ~~ ~~ yy
44 ~~ ~~ ~~ yy
55 ~~ ~~ ~~ nn
66 ~~ ~~ ~~ yy
SELECT
SELECT DISTINCT
DISTINCT isbn,
isbn, title,
title, author
author
FROM LoanableView
FROM LoanableView
WHERE
WHERE language
language == 'french'
'french'

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
207
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Triggers
 Introduction to Triggers
 Defining Triggers
 How Triggers Work
 Examples of Triggers
 Performance Considerations

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
208
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to Triggers
 Overview of Trigger
 Uses of Triggers
 Considerations for Using Triggers

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
209
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to Triggers
(continued)
 Overview of Trigger
 Associated with a Table
 Invoked Automatically
 Cannot Be Called Directly
 Is Part of a Transaction
 Special Type Of Stored Procedure
 Executed When Insert, Update, or Delete Updates Table
 After Triggers—Base Tables
 Instead-Of Triggers—Can Also Be Used With View
 Truncate Doesn’t Invoke Trigger
 Always Invoked By SQL Server NOT With Execute
 No Parameters, No Return Value

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
210
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to Triggers
(continued)
 Uses of Triggers
 Cascade Changes Through Related Tables in a Database
 Enforce More Complex Data Integrity Than a CHECK Constraint
 Define Custom Error Messages
 Maintain Denormalized Data
 Compare Before and After States of Data Under Modification

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
211
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to Triggers
(continued)
 Considerations for Using Triggers
 Triggers Are Reactive; Constraints Are Proactive
 Constraints Are Checked First
 Tables Can Have Multiple Triggers for Any Action
 Table Owners Can Designate the First and Last Trigger to Fire
 You Must Have Permission to Perform All Statements That Define
Triggers
 Table Owners Cannot Create AFTER Triggers on Views or
Temporary Tables

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
212
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Defining Triggers
 Creating Triggers
 Altering and Dropping Triggers

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
213
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Defining Triggers
(Continued)
 Creating Triggers
 Requires Appropriate Permissions
 Cannot Contain Certain Statements

Use
Use Northwind
Northwind
GO
GO
CREATE
CREATE TRIGGER
TRIGGER Empl_Delete
Empl_Delete ONON Employees
Employees
FOR DELETE
FOR DELETE
AS
AS
IF
IF (SELECT
(SELECT COUNT(*)
COUNT(*) FROM
FROM Deleted)
Deleted) >> 11
BEGIN
BEGIN
RAISERROR(
RAISERROR(
'You
'You cannot
cannot delete
delete more
more than
than one
one employee
employee at
at aa time.',
time.', 16,
16, 1)
1)
ROLLBACK TRANSACTION
ROLLBACK TRANSACTION
END
END

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
214
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Defining Triggers
(Continued)
 Altering and Dropping Triggers
 Changes the definition without dropping the trigger
 Can disable or enable a trigger
USE
USE Northwind
Northwind
GO
GO
ALTER
ALTER TRIGGER
TRIGGER Empl_Delete
Empl_Delete ONON Employees
Employees
FOR DELETE
FOR DELETE
AS
AS
IF
IF (SELECT
(SELECT COUNT(*)
COUNT(*) FROM
FROM Deleted)
Deleted) >> 66
BEGIN
BEGIN
RAISERROR(
RAISERROR(
'You
'You cannot
cannot delete
delete more
more than
than six
six employees
employees at
at aa time.',
time.', 16,
16, 1)
1)
ROLLBACK TRANSACTION
ROLLBACK TRANSACTION
END
END

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
215
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
How Triggers Work
 How an INSERT Trigger Works
 How an UPDATE Trigger Works
 How a DELETE Trigger Works
 How an INSTEAD OF Trigger Works
 How Nested Triggers Work
 Recursive Triggers

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
216
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
How an INSERT Trigger Works

INSERT statement to a table with an INSERT Trigger Defined


TRIGGER Actions Execute
INSERT
INSERT [Order Details]
Trigger
[Order Code:
Details] VALUES
VALUES
Trigger Code:
(10525, 2,
2, 19.00, 5,
5, 0.2)
11 INSERT
(10525, Statement
USE
USE Northwind
19.00,
CREATE
Northwindto a Table with an INSERT
0.2)
CREATE TRIGGER OrdDet_Insert
TRIGGER OrdDet_Insert
Trigger Defined
ON [Order
Order
Details]
ON [Order Details]
Details
FOROrder
FOR INSERTDetails
INSERT
OrderID
ASOrderIDProductID
AS ProductIDUnitPrice
UnitPriceQuantity
QuantityDiscount
Discount
22
INSERT UnitsInStock
Statement
UPDATE P
UPDATE P SET
10522
10522 10
Logged
SET
10 =31.00 77 0.2
UnitsInStock =31.00
(P.UnitsInStock
(P.UnitsInStock 0.2 –– I.Quantity)
I.Quantity)
10523
FROM
10523
FROM 41
Products
41
Products 9.65
AS
9.65P 99
INNER
AS P INNER 0.15
JOIN
0.15
JOIN Inserted
Inserted AS
AS II
33 ON
ON P.ProductID
P.ProductID == I.ProductID
I.ProductID
Order
Trigger Actions
10524 Executed
10524 77 30.00
30.00 24 0.0 24 0.0
OrderDetails
Details 10523 2 19.00 5 0.2
OrderID Products
Products
OrderIDProductID
ProductIDUnitPrice
UnitPriceQuantity
QuantityDiscount
Discount
ProductID
ProductID UnitsInStock
UnitsInStock …… ……
10522
10522 10 10 31.00
31.00 77 0.2
0.2
10523 41 9.65 99 0.15 11 15
15
Insert
10523 statement
41 logged
9.65 0.15
10524 77 30.00 24 0.0 22 15
10
10
10524inserted
inserted 30.00 24 0.0
10523 2 19.00 5 0.2 33 65
65
10523
10523 22 19.00
19.00 55 0.2
0.2 44 20
20

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
217
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
How an Update Trigger works

TRIGGER Actions Execute


UPDATE Statement to a table with an UPDATE Trigger Defined
USE
USE Northwind
Northwind
GO UPDATE Employees
GO UPDATE Employees
CREATE
SET
CREATE
ON
ON
UPDATE
TRIGGER
EmployeeID
11 EmployeeID
SET TRIGGER
Employees
Employees
Statement
Employee_Update
== 17
Employee_Update
17 to a Table with an UPDATE
WHERE
WHERE EmployeeID
EmployeeID == 22
FOR
AS
FOR UPDATE Trigger DefinedEmployees
UPDATE
AS
AS Employees
IF
IF UPDATE
IF UPDATE (EmployeeID)
UPDATE (EmployeeID)
(EmployeeID) EmployeeID
BEGIN
BEGIN TRANSACTION
BEGIN TRANSACTION
TRANSACTION EmployeeID LastName
LastName FirstName
FirstName Title
Title HireDate
HireDate
22 UPDATE
RAISERROR
RAISERROR
RAISERROR Statement
('Transaction
('Transaction
('Transaction Logged
cannot
1
cannot
cannot bebe as
Davolio
be INSERT
processed.\
Nancy
processed.\
processed.\ andRep.
Sales ~~~
*****
***** Employee
***** Employee
Employee IDID number
ID number
1cannot
number cannot
Davolio
cannot bebe Nancy
modified.', Sales
modified.', 10,
be modified.',
Rep.1)
10, 1)
10, 1)
~~~
ROLLBACK
ROLLBACK
ROLLBACK DELETE Statements
TRANSACTION
TRANSACTION
TRANSACTION 22 Fuller
Barr
Barr Andrew
Andrew Vice
RR Pres. ~~~ ~~~
Leverling 33
Leverling Janet
Janet Sales
SalesRep.
Rep. ~~~
~~~
Transaction
3 cannot be processed. Peacock 44
Peacock Margaret
MargaretSales
SalesRep.
Rep. ~~~
~~~
3 Trigger
***** Member Actions
number cannot Executed
be modified
***** Member number cannot be modified
Employees
UPDATE Statement loggedEmployees
as INSERT and DELETE Statements
EmployeeID
EmployeeID LastName
LastName FirstName
FirstName Title
Title HireDate
HireDate
inserted
inserted 11 Davolio
Davolio NancyNancy Sales
SalesRep.
Rep. ~~~
~~~
17
17 Fuller Andrew
Fuller 2 Andrew Vice Pres.
Vice Pres.
Fuller ~~~
Andrew~~~R Pres.
2 Barr
Barr Andrew Vice
R ~~~
~~~
deleted
deleted 33 Leverling
Leverling Janet
Janet Sales
SalesRep.
Rep. ~~~
~~~
22 Fuller 44Andrew
Fuller Peacock
Andrew Vice
VicePres.
Peacock Margaret
~~~Sales
~~~
Margaret
Pres. SalesRep.
Rep. ~~~
~~~
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
218
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
How Delete Trigger Works

DELETE Statement to a table with a DELETE Trigger Defined


Trigger Actions Execute
Categories
Categories
DELETE Statement
11 CategoryIDtoCategoryName
CategoryID a Table with a DELETE
CategoryName Description
Description Picture
Picture
DELETE
DELETE Categories Products
Products
WHERE
Statement
Categories Defined
11 Beverages
Beverages Soft
Softdrinks,
drinks,coffees…
coffees… 0x15…
ProductID Discontinued … …
0x15…
Condiments ProductID Discontinued
…… 0x15…

WHERE Condiments 22Sweet
CategoryID
CategoryID == 44 Sweetand
and savory
savory… 0x15…
22 Confections
Confections 33 11
Desserts,
Desserts, 00
candies,
candies,…… 0x15…
0x15…
DELETE Logged Statement
4 22
Dairy Products Cheeses 1
0 0x15…
USE Northwind 2 0
USE Northwind 33 00
CREATE
33 TRIGGER
CREATE TRIGGER Category_Delete
Category_Delete
ON Trigger Actions Executed
ON Categories
Categories 44 00
FOR
FOR DELETE
DELETE
AS
AS
UPDATE
UPDATE PP SET
SET Discontinued
Discontinued == 11
FROM
FROM Products
Products ASAS PP INNER
INNER JOIN
JOIN deleted
deleted AS
AS dd
ON P.CategoryID
ON DELETE == d.CategoryID
statement
P.CategoryID logged
d.CategoryID
Deleted
Deleted
44 Dairy
DairyProducts
Products Cheeses
Cheeses 0x15…
0x15…

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
219
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
How Instead of Trigger Works

Create a View That Combines Two or More Tables


CREATE
CREATE VIEW
UPDATE is Made
VIEW
toCustomers
11 View
the
Customers AS
INSTEAD
AS OF Trigger Can Be on a Table or View
SELECT
SELECT **
FROM
FROM CustomersMex
CustomersMex Customers
INSTEAD
UNION OF
UNION Customers
SELECT ** CustomerID
CustomerIDCompanyName
CompanyName Country
Country Phone
Phone ……
trigger
SELECTdirects the
22 CustomersGer
FROM The Action ThatALFKI
InitiatesAlfreds
the Fu…
Trigger Does030-0074321
Germany NOT Occur ~~~
update to the base
FROM CustomersGer ALFKI ALFKI Alfreds Fu… Germany 030-0074321 ~~~
table ANATR
ANATR Ana
AnaTrujill…
Trujill… Mexico
Mexico (5)
(5)555-4729
555-4729 ~~~
~~~
ANTON
ANTON Antonio
AntonioM…
M… Mexico
Mexico (5)
(5)555-3932
555-3932 ~~~
~~~
Original Insert to
33 Allows Updates to Views Not Previously Updateable
the Customers
CustomersMex
CustomersMex
View Does
CustomerID
CustomerID Not
CompanyName
CompanyName Country
Country
CustomersGerPhone
Phone ……
CustomersGer
Occur
ANATR
ANATR Ana AnaTrujill…
Trujill… Mexico
Mexico (5)
(5)555-4729
CustomerID
CustomerIDCompanyName
555-4729 ~~~
CompanyName Country
~~~
Country Phone
Phone ……
ANTON
ANTON Antonio
AntonioM…
M… Mexico
Mexico (5) 555-3932 ~~~
Germany
ALFKI(5) 555-3932
ALFKI Alfreds Fu…~~~
AlfredsFu… Germany 030-0074321
030-0074321 ~~~
~~~
CENTC Centro Co… Mexico
CENTC Centro Co… Mexico (5) 555-3392 ~~~
BLAUS(5) 555-3392
BLAUS Blauer Se…~~~
BlauerSe… Germany
Germany 0621-08460
0621-08460 ~~~
~~~
DRACD
DRACD Drachenb…
Drachenb… Germany
Germany 0241-039123
0241-039123 ~~~
~~~

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
220
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
How Nested Triggers Work
Order_Details
Order_Details
OrDe_Update
OrDe_Update OrderID
OrderIDProductID
ProductIDUnitPrice
UnitPriceQuantity
QuantityDiscount
Discount
10522
10522 10
10 31.00
31.00 77 0.2
0.2
10523
10523 41
41 9.65
9.65 99 0.15
0.15
10524
10524 77 30.00
30.00 24
24 0.0
0.0
10525 2 19.00 5 0.2

Placing an order causes the


OrDe_Update trigger to
Products
Products execute
InStock_Update
InStock_Update ProductID
ProductID UnitsInStock
UnitsInStock …… ……
Executes an UPDATE
11 15
15 statement on the Products
2 15
10
10 table
33 65
65
44 20
20
InStock_Update trigger
executes
UnitsInStock + UnitsOnOrder Sends message
is < ReorderLevel for ProductID 2
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
221
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Recursive Triggers
 Activating a Trigger Recursively
 Types of Recursive Triggers
 Direct recursion occurs when a trigger fires and performs an action
that causes the same trigger to fire again
 Indirect recursion occurs when a trigger fires and performs an action
that causes a trigger on another table to fire
 Determining Whether to Use Recursive Triggers

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
222
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Examples of Triggers
 Enforcing Data Integrity
 Enforcing Business Rules

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
223
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Enforcing Data Integrity

CREATE
CREATE TRIGGER
TRIGGER BackOrderList_Delete
BackOrderList_Delete
ON
ON Products FOR
Products FOR UPDATE
UPDATE
AS
AS
IF
IF (SELECT
(SELECT BO.ProductID
BO.ProductID FROM
FROM BackOrders
BackOrders ASAS BO
BO JOIN
JOIN
Inserted AS I ON BO.ProductID = I.Product_ID
Inserted AS I ON BO.ProductID = I.Product_ID
)) >> 00
BEGIN
BEGIN
DELETE
DELETE BO BO FROM
FROM BackOrders
BackOrders AS
AS BO
BO
INNER JOIN Inserted
INNER JOIN Inserted AS IAS I
ON
ON BO.ProductID
BO.ProductID == I.ProductID
I.ProductID
END
END

Products
Products BackOrders
BackOrders
ProductID
ProductID UnitsInStock
UnitsInStock …… …… ProductID
ProductID UnitsOnOrder
UnitsOnOrder ……
11 15
15 11 15
15
2 15
10 Updated
Updated 12 10
10 12 10
33 65
65 33 65
65
44 20 Trigger
TriggerDeletes
Deletes Row
Row 2 15
20

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
224
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Enforcing Business Rules
Products with Outstanding Orders Cannot Be Deleted
IF
IF (Select
(Select Count
Count (*)
(*)
FROM
FROM [Order Details] INNER
[Order Details] INNER JOIN
JOIN deleted
deleted
ON [Order Details].ProductID = deleted.ProductID
ON [Order Details].ProductID = deleted.ProductID
)) >> 00
ROLLBACK
ROLLBACK TRANSACTION
TRANSACTION
DELETE statement executed on Trigger code Transaction
Product table checks the Order Details rolled back
table
Products
Products Order
OrderDetails
Details
ProductID
ProductID UnitsInStock
UnitsInStock …… …… OrderID
OrderIDProductID
ProductIDUnitPrice
UnitPriceQuantity
QuantityDiscount
Discount
11 1515 10522
10522 10
10 31.00
31.00 77 0.2
0.2
22 010
10 10523
10523 22 19.00
19.00 99 0.15
0.15
33 6565 10524
10524 41
41 9.65
9.65 24
24 0.0
0.0
44 2020 10525
10525 77 30.00
30.00

'Transaction
'Transaction cannot
cannot bebe processed'
processed'
'This
'This product
product has
has order
order history'
history'

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
225
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Performance Considerations
 Triggers Work Quickly Because the Inserted
and
Deleted Tables Are in Cache
 Execution Time Is Determined by:
 Number of tables that are referenced
 Number of rows that are affected
 Actions Contained in Triggers Implicitly Are
Part of
a Transaction

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
226
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Transact-SQL Cursors
 Overview of Cursor
 Uses of Cursors
 How Cursors work
 Types of Cursors
 Cursor Characteristics
 Cursor Syntax

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
227
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Overview of Cursor
 Points to a Specific Row
 Retrieves and Modifies Rows based on Current
Position
 Can be Sensitive to Changes in Underlying Data

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
228
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Uses of Cursors
 Building Command String for Execution
 Increasing Script Readability
 Performing Multiple Unrelated Manipulation
with Data
 Compensating for Database and Application
Limitations

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
229
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
How Cursors Work

DECLARE @tablename nvarchar(256)


DECLARE tnames_cursor CURSOR
FOR SELECT name FROM sysobjects
WHERE objectproprty(id, ‘IsUserTable’)=1
ORDER BY name
OPEN tnames_cursor
FETCH NEXT FROM tnames_cursor INTO @tablename
WHILE (@@FETCH_STATUS = 0)
BEGIN
EXEC sp_spaceused @tablename
FETCH NEXT FROM tnames_cursor INTO @tablename
END

CLOSE tnames_cursor
DEALLOCATE tnames_cursor

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
230
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Types of Cursors
 Forward-Only
 Static
 Dynamic
 Keyset-driven

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
231
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Cursor Characteristics
 Scrollability
 Sensitivity
 Locking

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
232
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Cursor Syntax
DECLARE CURSOR
OPEN
FETCH
CLOSE
DEALLOCATE

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
233
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Object
Orientation

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Prerequisites for the course
Object Oriented Programming Experience

Target Audience

Analysts
Designers
Reviewers

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
235
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Session Plan
Introduction
Elements Of Object Orientation
• Object
• Class
• Abstraction
• Encapsulation
• Identity
• Object Structuring
• Object Interactions

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
236
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
What is Object Orientation
• Viewing and modeling the world (or any system) as a set of
interacting and interrelated objects.
• Using objects as the basic building blocks of a system’s
construction
• A method of structuring data more natural to our way of
thinking
• An approach than just a tool
• Each external request is implemented as a sequence of
messages which flow among a set of reactive software
abstractions
• Involves
• Object Oriented Thinking in
 Object Oriented System Analysis
 Object Oriented Architecture
 Object Oriented Design
 Object Oriented Programming

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
238
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
What is Object Orientation (cont…)
JSPs Form Beans Presentation Layer

0..* Action Servlet Action Classes Controller Layer


0..*

R espondant
Eval uator
Service Locator
eval uates
responds to
0..*

V alu e O b je c ts
0..*

1 has 0..*
Facade Facade Facade Facade Facade
0..* Business Layer
Busine Busine Busine Busine Busine
0..*
Survey Response ss ss ss ss ss
Objects Objects Objects Objects Objects
1
0..*
1
Data Data Data Data Data
Access Access Access Access Access
Data Access Layer
creates
Sec ti on 0..* 0..* Objects Objects Objects Objects Objects
1 1 has 0..*

1 0..*
Access Master
CSD Template CSD Propagation
Management M aintenence
Component Component Component
Component Component
0..* 1 Question Answer

Buyer

Subsecti on

Object
Analyst
Oriented
Architect
Thinking

Buyer Respondant
Evaluator
createSurvey() respondToSurvey()
evaluateResponse()
1 0..* answerQuestion()

creates responds to
0..* creates evaluates
0..*
Survey
has Response
1 0..* objBuyer : Buyer objSurvey : objSection : objSubsection : objQuestion :
addSection() Survey Section Subsection Question

1 load( )
load( )
load( )
Section load( )

addSubsection() 0..1
0..* 0..*
addQuestion()

1 1 has 0..* load( )


Ques tion Answer

0..*
0..*
Subsection
0..1
addQuestion()

Developer Designer

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
239
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
What is Object Orientation –
Analyst’s View
• How the business domain is structured
• Objects in the business domain, their characteristics
• Object relationships evident in the business domain
• Object relationship attributes to define business rules
• How the business domain operates
• Interactions among the business objects to carry out the
business processes

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
240
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
What is Object Orientation –
Analyst’s View
Manager Object
Employe
Behavior s
e
Softwar Problem Hardware
Relationships
e Interactions
Infra Server
team Dependencies

Manager
Review Employee
Creates

Complete

InfraTeamMember ServiceRequest

JobRequest SoftwareRequest HardwareRequest

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
241
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
What is Object Orientation –
Architect’s View
• What forms the foundation of this solution
• Decomposition into components
• Objects that form the basis of the chosen architecture
• How the responsibilities are handled
• Generic distribution of responsibilities across objects
• What common services are required
• Objects for common utility services

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
242
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
What is Object Orientation – Designer’s View

• How can the requirements be met using the


chosen architecture
• Enrich the architecture framework identifying new objects
required to meet the functional, non-functional requirements
• Build object hierarchies
• Determine object states
• Assign object behavior
• How to eliminate redundancy and save effort
• Address reuse opportunities
• Can the solution work
• Illustrate object collaboration to meet each of the
requirements

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
243
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Why Object Orientation
• Problem domain analysis and solution are more
closer to reality
• Problem domains are inherently complex
• Other traditional methodologies fall apart as the
problem domain becomes complex
• Easy communication of analysis and design
decisions
• Benefits that it provides over other paradigms

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
244
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Paradigm Shift – Procedural Vs Object Oriented

Main program/subroutine Object-oriented

Components modules objects

Connectors Procedure calls messages

Properties Hierarchical control main program Main program instantiates objects

Single thread of control Parallel threads of control possible


 
Execution from start to end Execution never ends

Global data on files/databases Objects responsible for own data

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
245
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Paradigm Shift – Procedural Vs Object Oriented
(cont…)

• Drawbacks in procedural paradigm


• Takes no account of evolutionary change
• system characterized by a single function - a questionable
concept
• does not encourage reusability
 
• based on functional mindset, data structure aspect often
neglected
Procedural Mindset Object-oriented Mindset
• Shift of mindset
What does the system do? Of what objects is the system composed?

What is its purpose?How do I design and code to How can I model the system dynamically using
achieve this functional behaviour? objects, their behaviour, and other objects they
use?

Focus on algorithms Algorithmic functions deferred

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
246
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Benefits of Object Orientation
• Support for modeling complex systems
• Designed for change
• Allows re-use
• Improves productivity
• Speeds up development time
• Improves maintainability, reliability
• Provides controlled and scalable evolution path

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
247
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Pitfalls of Object Orientation
• There is no ‘best’ object decomposition for a
system of any size
• Chances of over-designing

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
248
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Elements of Object
Orientation

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Object

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Object-Orientation - A Conceptual Look

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Objectives

• Functional approach
• Changing requirements
• An alternative

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
252
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
The Way We Think
Traditional software development focuses on functions
and
how they manipulate data
• A natural way to deal with complexity
 Big functions that decompose into smaller functions
The problem is Requirements Change
• Functional decomposition might not handle change well
 A change to one function or piece of data
 Can cause unwanted side effects
 High level level functions depend upon
the details of low level functions
 The ripple effect
 More likely to have problems in your software
As people we think about things and what they do
• A more abstract way of thinking
• Handles change well

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
253
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Attending Class - An Example
I have a problem to solve
• I am teaching you this class
• After you are finished with my class, you have another
to attend
• You do not know where that class is located
• I must make sure you know how to get to your next
class
 It’s another Keane class and we want you there!

How well will the


How would I solve
solution adapt to
this problem?
change?

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
254
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
The Functional Approach
A functional solution to the problem
• Get list of people in class
• For each person on the list
 Determine next class they need to attend
 Determine location of the class
 Formulate directions from my class to the next class
 Tell the person the instructions

Implementing this approach would require


• A procedure to get the list of people
• A procedure to get each person's schedule
• A program to give directions
• A controlling program to execute these functions
for each person

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
255
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
An Alternative
An alternative solution
• Post directions to classroom locations on the wall
• Tell people in class where directions are and to
go to their next class
Implementing this approach would require
• People that
 Know how to read directions Which solution
feels more natural?
 With directions, can get to next class
• A control program to
 Post the instructions and tell people that class is over

A shift of responsibility
• With the functional approach,
The control program is responsible for everything
• With this alternative, students are responsible for
themselves
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
256
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Change in Requirements
A new requirement for the problem
• Keane employees can also audit classes
 Among other duties, they will collect evaluations
for the instructor before going to the next class

Impact on functional solution?


• Change control program
 Must now determine if the person is a
Keane employee or student
 If the type is employee, tell it to collect evaluations
 Could take considerable work!

Impact on alternative solution?


• Write additional routine for people who are employees
• Control program is unchanged
 People, go to your next class!

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
257
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
How Does It Work?

People are responsible for themselves


• They do their own work
• They know what type of person they are
Control program
• Communicates with all people as if they are the same
• Does not care how people get from one class to
another
• Does not care if people need to take special steps

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
258
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Object-Orientation

In the alternative solution


• Communication occurred at a conceptual level
 Tell people what to do, but not how to do it
 Know what is happening, but not how it is done
• People performed at a lower level
 Implementation level
 They have specific steps and logic to get from one
class to another

This is the structure provided by Object-


Orientation
• Objects are responsible for themselves
• Objects tell each other to do things at a conceptual
level
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
259
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Object-Orientation - Basic
Principles

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Objectives

• Objects
 State, behavior, identity
 Instantiation
• Classes
 Visibility
• The three pillars
 Encapsulation
 Inheritance
 Polymorphism

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
261
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Objects
Objects are abstractions we use to model things
in the real world
• Student, location, account, product, customer, accident
A definition for objects depends upon your
perspective
• Conceptual
 Objects are things with responsibilities
• Specification
 Objects are sets of behavior and attributes
 May be called by other objects or itself
• Implementation
 Packets of code and data

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
262
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Attributes
Attributes
• Are variables belonging to an object
 Student has a name, address and GPA
 “John Park”, “2309 Riverside Dr”, 3.5
• Have a type
 Name is a string, address is a string, GPA is a float
• Define the state of an object
 An object might behave differently depending upon its state

One object may have another object as an


attribute
• A student is registered for and keeps track of multiple
classes

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
263
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Behavior
Operations specify what an object can do
• Call operations to activate object responsibilities
• “Student object, goToNextClass( )”
Parameters may be passed into operations
Operations are
• Defined by the operation signature identified with ( ) at the
end of the operation
Operations may return information name

Calling an operation could change the state of the object


• Cause a change to its attributes
The list of operations an object supports is its interface
Objects collaborate with other objects by sending
messages
• Called object receives the message
 Invokes the appropriate operation

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
264
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Identity
Each object has a unique existence in space and
time
• Makes it different from every other object
• Known as the object's identity
In implementation terms
• When an object is created, it resides at a specific place in
memory
 This memory location is not shared with other objects
 Specific objects are tracked with references
Identity is independent of state
• Changing the value of one object's attributes will not
affect another object's attributes
 Even if two objects have identical values for their attributes
 Unless we specify behavior to do so

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
265
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Classes

A class is a template for a set of objects


• It defines
 The object's type
 The attribute types an object will have
 The values can be different for each object
 The operations the object will support
Think of classes to objects as
• A blueprint to a house
• A cookie cutter to the actual cookies
• A database table to rows in the table
Classification is a powerful concept
• Allows us to talk about features and behavior
that every object will have
 Without having to specify each object

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
266
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Instantiation
Objects are created from class specifications
• This process is know as instantiation
 The object is an instance of the class
Classes have special operations called constructors
• Called to create a new instance
• Allocates memory for the object (gives it identity)
• Initializes the attributes
 May be set to default values or passed as attributes
• Returns a reference to the new object
• Eliminates errors associated with uninitialized variables

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
267
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Objects in Action

A sneak peak Here’s some


at UML notation! Java. Notice how concept
maps to code.

class Student {
Class Student String name;
String address;
name : String
Attributes float gpa;
address : String
gpa : float
public void goToClass( ) {
goToClass( ) Operations // code here
Constructor Student(name: String) }
public Student(String argName) {
name = argName;
}
<<instanceof>> <<instanceof>> <<instanceof>> }

s1:Student s2:Student s3:Student


Student s1 = new Student(“Chris”);
name = “Chris” name = “Mike” name = “Chris” Student s2 = new Student(“Mike”);
Student s3 = new Student(“Chris”);
st
jec
Ob

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
268
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Objects in Action

A sneak peak Same thing in


at UML notation! C#. Notice how concept
maps to code.

class Student {
Class Student string name;
string address;
name : String
Attributes float gpa;
address : String
gpa : float
public void goToClass( ) {
goToClass( ) Operations // code here
Constructor Student(name: String) }
public Student(string argName) {
name = argName;
}
<<instanceof>> <<instanceof>> <<instanceof>> }

s1:Student s2:Student s3:Student


Student s1 = new Student(“Chris”);
name = “Chris” name = “Mike” name = “Chris” Student s2 = new Student(“Mike”);
Student s3 = new Student(“Chris”);
st
jec
Ob

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
269
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Inheritance Inheritance is
also known as

Inheritance is a relationship between classes Generalization

• Subclass may inherit from a superclass


 Inherits all of its operations and attributes
 Allows us to create categories
 Based upon behavior and characteristics
 Allows for code reuse
 Most importantly, provides structure for polymorphism

A subclass can override superclass operations


• The same operation (conceptually) is implemented differently
• Operation signature must match exactly
An “is-a” relationship
• Because a subclass inherits all operation and attributes
 It can be used any place the superclass is expected

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
270
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Inheritance in Action

Student Student s1 = new Student(“Chris”);


PayingStudent s2 = new PayingStudent(“Mike”);
goToClass() KeaneStudent s3 = new KeaneStudent(“Chris”);

StudentList slist = new StudentList();


“is-a” slist.addStudent(s1);
slist.addStudent(s2); A subclass instance may be used
slist.addStudent(s3); wherever superclass is expected!
PayingStudent KeaneStudent

Subclasses
inherit goToClass( ) s1.goToClass();
behavior s2.goToClass(); This will also work
s3.goToClass();

StudentList
Superclasses are also called: Subclasses are also called:
• Parent • Children
addStudent(Student) • Ancestor • Descendant
getNextStudent() : Student • Base class • Specializations

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
271
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Setting the Stage

Subclasses will usually override operations


• Implement their own specialized behavior
• PayingStudents get to the next class differently than
KeaneStudents
 PayingStudents get directions and go directly to next class
 KeaneStudents help collect evals and then go to the next class
Inheritance provides the structure to treat all kinds
of students the same
• What we think is a generic Student might actually be a
subclass
Student s = slist.getNextStudent();
s.goToClass();

What happens?
Do we need to know what type
of student we are referring to?
Where’s the if logic?

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
272
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Dynamic Behavior

Sign the
students into class
Student
PayingStudent s1 = new PayingStudent(“Mike”);
goToClass() KeaneStudent s2 = new KeaneStudent(“Chris”);

StudentList slist = new StudentList();


slist.addStudent(s1);
slist.addStudent(s2);

PayingStudent KeaneStudent
Class is over!
goToClass() goToClass() while(still students in the list)
Student s = slist.getNextStudent();
s.goToClass();
Override goToClass(). Override goToClass(). }
Goes directly to Collects evals first
next class

Goes directly
goToClass() :Student s1:PayingStudent to next class

:StudentList

:Student s2:KeaneStudent Collects evals


goToClass() first

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
273
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Polymorphism
Formal Definition
"Many Forms"
• Polymorphism allows you to send objects of different
classes the same message and the objects will respond
appropriately
 The sender of the message does not need to know the
specific type of the object
Informal Definition
• Anything the superclass does, the subclasses can do also
 They just might do it differently
Polymorphism allows communication at a conceptual
level
• New subclasses with new implementations will not
impact
the code
 As long as communication is at the superclass level
 Type checking is done “behind the scenes”

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
274
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Requirements Change
Changing requirements have little impact

A new type of student


Student
is added with its own
implementation of
goToClass() goToClass().
AuditStudent

goToClass()
New class
instantiated and
PayingStudent KeaneStudent added to the list
PayingStudent s1 = new PayingStudent(“Mike”);
goToClass() goToClass()
KeaneStudent s2 = new KeaneStudent(“Chris”);
AuditStudent s3 = new AuditStudent(“Jeff”);

StudentList slist = new StudentList();


Inheritance at work. slist.addStudent(s1);
slist.addStudent(s2);
slist.addStudent(s3):

No Changes needed! while(still students on the list)


Polymorphism at work! Student s = slist.getNextStudent();
s.goToClass();
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
275
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Abstract Classes

In many cases, the base class can not


implement a sensible, default behavior
An abstract class declares an operation but
does not implement it
• Operations without behavior are abstract
• One or more operations may be abstract
• Abstract classes can not be instantiated
Subclasses of an abstract class must override
and implement inherited abstract operations
• If you wish to instantiate the subclass
 a.k.a. make it concrete

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
276
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Abstract Continued
Abstract classes define behavior for a set of
classes
• Act as a placeholder for other classes
 Allowing conceptual communications and polymorphic behavior

Most base classes will have at least one abstract


method

Student
No behavior
implemented.
goToClass()
AuditStudent

goToClass()

PayingStudent KeaneStudent

goToClass() goToClass()

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
277
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Quiz - Old MacDonald’s Farm
We are starting a new children’s entertainment software
company
• Our first application will be Old MacDonald’s Farm
 Initially, children can put three types of animals in the barn - pigs,
ducks and cows
 The GUI will provide a button for each animal.
 When the button is pressed, it adds the animal to the barn
 The GUI also has a “Go” button.
 When pressed, it starts the Old MacDonald song
 As the song is played, each animal will come out of the barn
 And make its appropriate animal sound
• Identify the classes needed and their behaviors
• Keep flexibility in mind. We want to be able to easily integrate
expansion packs with additional animals
• After we have the song working, would it be possible to have the
ducks fly when they come out of the barn?

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
278
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Visibility

Classes define different levels of visibility for their


attributes and operations
• If an attribute or method is visible it may be accessed or
called
Public
• Anything can see it
Protected
• Only objects instantiated from this class and its subclasses
can see it
Private
• Only objects instantiated from this class can see it
• Not even subclasses can see it
Package
• Any object in in the same package can see it
• A class's interface is its public operations

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
279
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Encapsulation
Objects should be self contained
• When you tell a dog to fetch, you do not worry about the details of
how he or she does it
• Objects should encapsulate their implementation details away
from clients
 Keep data hidden
 Attributes are not made public
 Prevents data corruption
 Access is controlled by getter and setter methods
 Business rules are kept in once place!
 Hide away implementation details
 Operations are public, but their implementation is hidden
 Other objects that interact with them (use their operations) should not be aware of
how the operations are implemented

• Well encapsulated objects minimize the impact of change


 Clients should be ignorant and unaffected

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
280
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Quiz - Encapsulation
If you know a subclass will need to access your
classes attributes, is it OK to declare them as
protected?

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
281
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Class

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Class
• Is a unit of abstraction in an object oriented
(OO) program
• Represents similar objects
 Its instances
• Translates to a software module in
programming world
 Describes its instances’ structure (properties)
 Contains methods to implement their behavior
Manager
Class Properties Behavior
Employee ID join()
Employee Name
leave()
Department
retire()
Executive Address
Graduation changeDetails()
….

Engineer
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
283
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Abstraction

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Abstraction
• Is representing essential features without including the
background details or explanations.
• Emphasizing the relevant (..relevant to problem area)
features, properties, or functions and ignoring irrelevant
ones with an eye to future reuse

Abstraction Instantiation
Service Request

Software Request Hardware Request Job Request email Request

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
285
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Benefits of Abstraction
• Supports modeling
• Reduces code redundancy
• Encourages reusability
• Encourages extensibility
• It allows us to take a high level view

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
286
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Encapsulation

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Encapsulation
• Is capturing attributes and operations together
in an object for effective re-use
• Provides sense of ownership to the object and
distributes responsibility

Service Request Employee


Request No Employee Id
Location Name
Cubical …..
….. join()
approve() assignGroup()
reject() retire()
…. ….

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
288
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Benefits of Encapsulation
• Modularity
• Information Hiding
• Program independence

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
289
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Identity

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Identity
• The property that distinguishes an object from
all other objects
• In programming perspective it is the reference
Identity: Employee Id Identity: Employee Name Name:Deepa
Employee Id: 123
Name:Raj
Employee Id: 2345

Employee Id: 6748 Employee Id: 2343 Employee Id: 5436 Name: Deepak Name:Raj


Name:Riya


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
291
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Object

Object Identity Behaviour State

Employee Employee Id: 2543 Join, AssigntoGroup Project delivery


Group
Software Request Request No: Approve, Reject, Assign For Approval
BLR/Jan04/1232

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
292
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Object Relationships

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Composition
• A property that allows a class to be composed
of other classes
• Whole - part structure : ‘is a part of /
component of’ relation Computer
Example :

Base Unit Keyboard


Monitor

Data Cables
Hard Disk Motherboard Power Supply

©2007 Keane. All rights reserved. Confidentiality:


RAM CPUThe concepts and methodologies BIOS
contained herein are proprietary to Keane.
294
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Inheritance
• A property that allows subordinate class objects
to use (inherit) the data and methods of a
parent class
• Building up new data types from existing ones
• A reuse mechanism Service Request
Request No
Location
Cubical
…..
approve()
reject()
….

Hardware Service Request Software Service Request


CPU Speed Project Specific
RAM Non-Project Specific
HDD …..
…..
. .
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
295
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thank You !!

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to .Net
Framework

COE – Current Technologies


Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
.NET Enterprise Vision
Users
Any device,
Any place,
Any time

XML Web
Services
Integrate business
Authentication applications and
Scheduling processes
Notification

Back Office
Heterogeneous
application and
server
infrastructure

Customer Sales
ERP & Billing Service
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
298
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
.NET Framework

.NET is a platform that provides a standardized set of services.


It’s just like Windows, except distributed over the Internet.
It exports a common interface so that it’s programs can be run
on any system that supports .NET.

A specific software framework


Includes a common runtime

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
299
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
.NET Framework

Programming model for .NET


Platform for running .NET managed code in a virtual
machine
Provides a very good environment to develop networked
applications and Web Services
Provides programming API and unified language-
independent development framework

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
300
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
The Core of .NET Framework: FCL &
CLR

Common Language Runtime


• Garbage collection
• Language integration
• Multiple versioning support (no more
DLL hell!)
• Integrated security
Framework Class Library
• Provides the core functionality:
ASP.NET, Web Services, ADO.NET, Windows
Forms, IO, XML, etc.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
301
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
.NET Framework
Common Language Runtime

• CLR manages code execution at runtime


• Memory management, thread management, etc.

Common Language Runtime

Operating System
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
302
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
.NET Framework
Base Class Library

• Object-oriented collection of reusable types


• Collections, I/O, Strings, …

.NET Framework (Base Class Library)

Common Language Runtime

Operating System
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
303
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
.NET Framework
Data Access Layer

• Access relational databases


• Disconnected data model
• Work with XML

ADO .NET and XML

.NET Framework (Base Class Library)

Common Language Runtime

Operating System
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
304
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
.NET Framework
ASP.NET & Windows Forms
• Create application’s front-end – Web-based user
interface, Windows GUI, Web services, …

ASP .NET Windows


Web Forms Web Services
Forms
Mobile Internet Toolkit

ADO .NET and XML

.NET Framework (Base Class Library)

Common Language Runtime

Operating System
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
305
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
.NET Framework
Programming Languages
• Use your favorite language

C++ C# VB.NET Perl J# …


ASP .NET Windows
Web Forms Web Services
Forms
Mobile Internet Toolkit

ADO .NET and XML

.NET Framework (Base Class Library)

Common Language Runtime

Operating System
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
306
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
.NET Framework
Common Language Specification

C++ Common
C# VBLanguage
Perl Specification
J# …
ASP .NET Windows
Web Forms Web Services
Forms
Mobile Internet Toolkit

ADO .NET and XML

.NET Framework (Base Class Library)

Common Language Runtime

Operating System
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
307
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
.NET Framework
Visual Studio .NET

C++ C# VB Perl J# …

Common Language Specification

Visual Studio .NET


ASP .NET Windows
Web Forms Web Services
Mobile Internet Toolkit
Forms

ADO .NET and XML

.NET Framework (Base Class Library)

Common Language Runtime

Operating System

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
308
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
.NET Framework
Standards Compliance

C# Language –
Submitted to ECMA
C++ C# VB Perl J# …
Open Language
Common Language Specification
Specification

Visual Studio .NET


ASP .NET Windows Web services –
Web Services Web Forms
Forms XML, SOAP-based
Mobile Internet Toolkit

ADO .NET and XML

.NET Framework (Base Class Library) XML-based


data access
Common Language Runtime

Operating System

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
309
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
.NET Framework

Manages running code – like a virtual machine


Threading
Memory management
No interpreter: JIT-compiler produces native code – during
the program installation or at run time

Fine-grained evidence-based security


Code access security
Code can be verified to guarantee type safety
No unsafe casts, no un-initialized variables and no out-
of-bounds array indexing
Role-based security

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
310
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
.NET Framework – Managed Code

Code that targets the CLR is referred to as


managed code
All managed code has the features of the CLR
• Object-oriented
• Type-safe
• Cross-language integration
• Cross language exception handling
• Multiple version support
Managed code is represented in special
Intermediate Language (IL)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
311
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
.NET Framework -Automatic
Memory Management
The CLR manages memory for managed code
• All allocations of objects and buffers made from a Managed
Heap
• Unused objects and buffers are cleaned up automatically
through Garbage Collection
Some of the worst bugs in software development are not
possible with managed code
• Leaked memory or objects
• References to freed or non-existent objects
• Reading of uninitialised variables
Pointerless environment

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
312
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
.NET Framework - Multiple Language
Support

 IL (MSIL or CIL) – Intermediate Language


 It is low-level (machine) language, like Assembler, but is Object-
oriented
 CTS is a rich type system built into the CLR
 Implements various types (int, float, string, …)
 And operations on those types
 CLS is a set of specifications that all languages and libraries need to
follow
 This will ensure interoperability between languages

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
313
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
.NET Framework - Multiple Language
Support

.NET languages are compiled to an


Intermediate Language (IL)
IL is also known as MSIL or CIL
CLR compiles IL in just-in-time (JIT)
manner – each function is compiled just
before execution
The JIT code stays in memory for
subsequent calls
Recompilations of assemblies are also
possible

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
314
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
.NET Framework - Common Type System (CTS)

All .NET languages have the same primitive data types.


An int in C# is the same as an int in VB.NET
When communicating between modules written in
any .NET language, the types are guaranteed to be
compatible on the binary level
Types can be:
• Value types – passed by value, stored in the stack
• Reference types – passed by reference, stored in the heap
Strings are a primitive data type now

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
315
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
.NET Languages

Languages provided by Microsoft


• C++, C#, J#, VB.NET, JScript
Third-parties languages
• Perl, Python, Pascal, APL, COBOL, Eiffel, Haskell, ML,
Oberon, Scheme, Smalltalk…
Advanced multi-language features
• Cross-language inheritance and exceptions handling
Object system is built in, not bolted on
• No additional rules or API to learn

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
316
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thank You !

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
C# 2.0 on Visual Studio
2005

COE – Current Technologies


Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics
1) Introduction to C#
2) Visual Studio 2005 – IDE
3) C# Programming language
4) Data Types
5) Variables
6) Enumeration Types
7) Operators
8) Statements
9) Arrays
10)Class
11)Structures
12)Debugging In Visual Studio 2005

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
319
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics
13) Visual Studio Class Designer
14) Classes & Object
15) Properties
16) Property visibility
17) Partial Classes
18) Static Class
19) Structures
20) Inheritance
21) Abstract methods and Classes.
22) Operator Overloading & Type Conversion
23) Interface
24) Indexers

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
320
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics
25) Nested Classes
26) Generics
27) Callbacks & Delegate
28) Anonymous methods
29) Events
30) Exception Handling
31) Inline Warning
32) Refactoring - Visual Studio 2005

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
321
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to C#

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
C# – Features

The first component oriented language in


the C/C++ family
Everything really is an object
Next generation robust and durable
software
Preservation of investment

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
323
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A component oriented language

C# is the first “component oriented” language


in the C/C++ family
Component concepts are first class:
• Properties, methods, events
• Design-time and run-time attributes
• Integrated documentation using XML
Enables one-stop programming
• No header files, IDL, etc.
• Can be embedded in web pages

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
324
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Everything really is an object

Traditional views
• C++, Java: Primitive types are “magic” and do not
interoperate with objects
• Smalltalk, Lisp: Primitive types are objects, but at great
performance cost
C# unifies with no performance cost
• Deep simplicity throughout system
Improved extensibility and reusability
• New primitive types: Decimal, SQL…
• Collections, etc., work for all types

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
325
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Robust and durable software

Garbage collection
• No memory leaks and stray pointers
Exceptions
• Error handling is not an afterthought
Type-safety
• No uninitialized variables, unsafe casts
Versioning
• Pervasive versioning considerations in all aspects of
language design

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
326
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Hello World

using System;

class Hello
{
static void Main() {
Console.WriteLine("Hello world");
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
327
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
C# 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

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
328
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
C# Program Structure

using System;

namespace System.Collections
{
public class Stack
{
Entry top;

public void Push(object data) {


top = new Entry(top, data);
}

public object Pop() {


if (top == null) throw new InvalidOperationException();
object result = top.data;
top = top.next;
return result;
}
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
329
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Type System

Value types
• Directly contain data
• Cannot be null
Reference types
• Contain references to objects
• May be null

int i = 123;
string s = "Hello world";

i 123

s "Hello world"

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
330
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Type System

Value types
• Primitives int i;
• Enums enum State { Off, On }
• Structs struct Point { int x, y; }
Reference types
• Classes class Foo: Bar, IFoo {...}
• Interfaces interface IFoo: IBar {...}
• Arrays string[] a = new string[10];
• Delegates delegate void Empty();

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
331
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Predefined Types

C# predefined types
• Reference object, string
• Signed sbyte, short, int, long
• Unsigned byte, ushort, uint, ulong
• Character char
• Floating-point float, double, decimal
• Logical bool
Predefined types are simply aliases for system-
provided types
• For example, int == System.Int32

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
332
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Classes

Single inheritance
Multiple interface implementation
Class members
• Constants, fields, methods, properties, indexers, events,
operators, constructors, destructors
• Static and instance members
• Nested types
Member access
• public, protected, internal, private

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
333
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Structs

Like classes, except


• Stored in-line, not heap allocated
• Assignment copies data, not reference
• No inheritance
Ideal for light weight objects
• Complex, point, rectangle, color
• int, float, double, etc., are all structs
Benefits
• No heap allocation, less GC pressure
• More efficient use of memory

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
334
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Interfaces
Multiple inheritance
Can contain methods, properties, indexers, and
events
Private interface implementations

interface IDataBound
{
void Bind(IDataBinder binder);
}

class EditBox: Control, IDataBound


{
void IDataBound.Bind(IDataBinder binder) {...}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
335
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Enums

Strongly typed
• No implicit conversions to/from int
• Operators: +, -, ++, --, &, |, ^, ~
Can specify underlying type
• Byte, short, int, long

enum Color: byte


{
Red = 1,
Green = 2,
Blue = 4,
Black = 0,
White = Red | Green | Blue,
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
336
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Delegates

Object oriented function pointers


Multiple receivers
• Each delegate has an invocation list
• Thread-safe + and - operations
Foundation for events

delegate void MouseEvent(int x, int y);

delegate double Func(double x);

Func func = new Func(Math.Sin);


double x = func(1.0);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
337
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Unified Type System
Everything is an object
• All types ultimately inherit from object
• Any piece of data can be stored, transported, and
manipulated with no extra work

object

Stream Hashtable int double

MemoryStream FileStream

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
338
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Component Development

What defines a component?


• Properties, methods, events
• Integrated help and documentation
• Design-time information
C# has first class support
• Not naming patterns, adapters, etc.
• Not external files
Components are easy to build
and consume

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
339
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Properties
Properties are “smart fields”

public class Button: Control


{
private string caption;

public string Caption {


get {
return caption;
}
set {
caption = value;
Repaint();
}
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
340
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Attributes

How do you associate information with types


and members?
• Documentation URL for a class
• Transaction context for a method
• XML persistence mapping
Traditional solutions
• Add keywords or pragmas to language
• Use external files, e.g., .IDL, .DEF
C# solution: Attributes

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
341
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML Comments

class XmlElement
{
/// <summary>
/// Returns the attribute with the given name and
/// namespace</summary>
/// <param name="name">
/// The name of the attribute</param>
/// <param name="ns">
/// The namespace of the attribute, or null if
/// the attribute has no namespace</param>
/// <return>
/// The attribute value, or null if the attribute
/// does not exist</return>
/// <seealso cref="GetAttr(string)"/>
///
public string GetAttr(string name, string ns) {
...
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
342
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Operator Overloading

First class user-defined data types


Used in base class library
• Decimal, DateTime, TimeSpan
Used in UI library
• Unit, Point, Rectangle
Used in SQL integration
• SQLString, SQLInt16, SQLInt32, SQLInt64, SQLBool,
SQLMoney, SQLNumeric, SQLFloat…

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
343
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Versioning

Problem in most languages


• C++ and Java produce fragile base classes
• Users unable to express versioning intent
C# allows intent to be expressed
• Methods are not virtual by default
• C# keywords “virtual”, “override” and “new” provide context
C# can't guarantee versioning
• Can enable (e.g., explicit override)
• Can encourage (e.g., smart defaults)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
344
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Versioning

class Base // version 2


1
{
} public virtual void Foo() {
Console.WriteLine("Base.Foo");
}
}

class Derived: Base // version 2b


1
2a
{
new public
public virtual
override
virtual
void
void
void
Foo()
Foo()
Foo()
{{ {
Console.WriteLine("Derived.Foo");
base.Foo();
} Console.WriteLine("Derived.Foo");
} }
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
345
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Conditional Compilation

#define, #undef
#if, #elif, #else, #endif
• Simple boolean logic
Conditional methods
public class Debug
{
[Conditional("Debug")]
public static void Assert(bool cond, String s) {
if (!cond) {
throw new AssertionException(s);
}
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
346
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Visual Studio 2005 - IDE

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Visual Studio 2005 - IDE

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
348
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Visual Studio 2005 - IDE

ToolBox

Soluition
Explorer

Form Designer

Properties

Code Defnision Window

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
349
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Visual Studio 2005 - IDE

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
350
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Visual Studio 2005 - IDE

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
351
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
C# Programming
language

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Contents
• HelloWorld
• Data Types
• Variables
• Enumeration Types
• Operators
• Statements
• Selection
• Iterations
• Arrays
• Multidimensional
• Jagged
• Class
• Struct
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
353
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Hello World Program
using System;
namespace HelloWorld
{
public class Hello
{
public static void Main()
{
System.Console.WriteLine("Hello, World!");
}
}
}

• Every Main method must be contained inside a class (Hello in


this case)
• The System.Console class contains a WriteLine method that
can be used to display a string to the console
• The Console class is contained in the namespace System
• Hello Class will be part of namespace HelloWorld
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
354
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Passing Command Line Arguments
using System;
namespace CmdLine
{
class CLine
{
static void Main(string[] args)
{
Console.WriteLine(
"You Entered {0} command Line Arguments", args.Length);
Console.WriteLine("They are :");
for(int i =0; i<args.Length; i++)
{
Console.WriteLine("arg#{0} is {1}", i,args[i]);
}
}
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
355
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Passing Command Line Arguments
Parameters that are passed from OS prompt are
presented to main in an array of Strings
• args.Length gives number of elements / command
parameters
• Parameters are accessed using args[i]

WriteLine method is used to print values of


variables inside a string
• { n } is a place holder of a variable or value
• n is the position of the parameter after the output string

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
356
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Setting Command line arguments

Thru Project -> <Proj Name> Properties menu


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
357
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Output of Command line program

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
358
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Comments
The C# language supports 2 kinds of comments:

/* text */
The compiler ignores everything from /* to */

// text
The compiler ignores everything from // to the end of the line

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
359
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Types
• Every variable must have a data type
• A variable's data type determines
• the values that the variable can contain
• the operations that can be performed on it
• The C# programming language has two categories of
data types
 Value Type
 Reference Type

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
360
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Value Types
• A variable of a value type always contains a
value of that type
• The assignment to a variable of a value type
creates a copy of the assigned value
• All value types are derived implicitly from the
Object class

Categories
• Struct Type
 Built-In Simple types
 User defined (Discussed Later)
• Enumeration Type (Discussed later)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
361
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Reference Types
Reference type variables are
• Referred to as objects
• Store references to the actual data

Categories (discussed later)


• User defined
 class
 interface
 delegates
• Built In
 object
 String

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
362
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Built In Data types
All of the simple types are aliases of the .NET
Framework System types
• For example, int is an alias of System.Int32

• Numeric types
• Integral types
• Floating-point types
• decimal
• bool

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
363
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Built In Data types
byte 1 byte System.Byte Unsigned (0 to 255)

sbyte 1 byte System.Sbyte Signed (-127 to 127)

bool 1 byte System.Bool true or false

char 2 byte System.Char Unicode 16 bit character

short 2 byte System.Int16 Signed

ushort 2 byte System.Uint16 Unsigned

int 4 byte System.Int32 Signed

uint 4 byte System.Uint32 Unsigned

float 4 byte System.Single Signed, 7 digit precision

double 8 byte System.Double Signed, 15 –16 digit precision

decimal 8 byte System.Decimal Signed, 28 digit precision


Used in Financial calculations
long 8 byte System.Int64 Signed

ulong 8 byte System.Uint64 Unsigned

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
364
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Variables
• An object stores its state in variables
• A function accepts parameters in variables
• A function uses variables to store intermediate values
from calculations
• A variable is an item of data named by an identifier

Variable Names
• It must be a legal identifier
 An identifier is an unlimited series of Unicode characters that begins
with a letter
• It must not be a keyword, a boolean literal (true or false), or the
reserved word null
• It must be unique within its scope

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
365
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Variables definition
Format
Datatype var1, var2, var3….. ;
e.g. int x, y;
float interest;

Variables can take an initial value


e.g. int x = 10, y = 5;
float interest = 7.25F; //F denotes a float value
decimal amount = 765.27M; //M denotes a decimal value
bool match = true; //true and false are bool values
double sum = 0.0D //D denotes a double value
long elapsedTime = 69532L //L denotes a long value
char quit = ‘x’ //char values enclosed in ‘’

A value must be assigned to a variable


before using it
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
366
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Variables definition - Quiz
1. These thing mean the same. Why there are 2
types?
int x = 10;
System.Int32 x = 10;

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
367
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Variables definition - Exercise
1. Use the intellisense feature and find out the
way to obtain the maximum and minimum
values of the various data types in the System
namespace and built in types

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
368
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Type Conversions
Implicit Conversion
• Happens automatically when a small value is assigned to a big
enough variable
(e.g.)
short x = 10;
int y = x //OK

Explicit Conversion
• Conversion is forced by developer
e.g.
int x = 100;
short y = x //wont compile
Short y = (short) x //Compile

Each type has its own conversion rule, may result


in data loss if used improperly
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
369
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
String Data type
• The string type represents a string of Unicode characters
enclosed in double quotes : “”
• string is an alias for System.String in the .NET Framework
• The + operator concatenates strings:
string a = "good " + "morning";
• The [] operator accesses individual characters of a string:
char x = "test"[2]; // x = 's'
• The char ‘\’ is used to place special chars in string:
string a = "good\tmorning"; //tab character between words
• \\ is used to place a ‘\’ char in string:
string a = “c:\\myfile.txt"; //means c:\myfile.txt
• Literal strings:
string a = @“c:\myfile.txt"; //rather than c:\\myfile.txt

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
370
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Formatting numeric types
Currency
Console.Write("{0:C}", 2.5); // $2.50
Console.Write("{0:C}", -2.5); // ($2.50)
Decimal
Console.Write("{0:D5}", 25); // 00025
Scientific
Console.Write("{0:E}", 250000); // 2.500000E+005
Fixed Point
Console.Write("{0:F2}", 25); // 25.00
Console.Write("{0:F0}", 25); // 25
General
Console.Write("{0:G}", 2.5); // 2.5
Number
Console.Write("{0:N}", 2500000); //2,500,000.00
HexaDecimal
Console.Write("{0:X}", 250); // FA
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
371
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
String to numbers
static void Main(string[] args)
{
int i;
//read from keyboard
Console.WriteLine(“Enter a value for I : ”);
string s = Console.ReadLine();
//Convert to integer
i = System.Int32.Parse(s);
Console.WriteLine("i = {0}", i);

Console.ReadLine(); //Close terminal


}

ReadLine reads the string from Keyboard , Type 100 and


press Enter key
Parse method of System datatype is used to construct a
value from string. Improper input may result in error
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
372
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Constants
A Constant is a variable whose value cannot be
changed
const float PI = 3.14F;

General form
const datatype Constant-name = value;

(e.g)
const int Sunday = 1;
const int Monday = 2; //etc.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
373
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Enumerations
• A new data type of named integer constants
• Variable defined of this type can take a value
from a predefined set
enum LayerType
{
opaque, //takes value 0
transparent //takes value 1
}

LayerType layer1 = LayerType.opaque;


Console.WriteLine(“Layer Type {0}”, layer1); //prints opaque

int layer = (int) layer1; //Explicit conversion necessary


Console.WriteLine(“Layer Type {0}”, layer); //prints 0

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
374
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Enumerations – Why?
• The previous sample is equivalent to
const int opaque = 0;
const int transparent = 1;

BUT
• Though enumerations are integral type they are
not int or short or long (Explicit casting necessary)
• Enumeration type variables cannot be assigned
with integral constants
LayerType layer = 0; //not allowed

Enumeration type variables can be assigned only


values defined with in the enum leading to Strong
type checking

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
375
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Enumerations – values
• Enumerations need not take zero based values
always
enum TemperatureLimits {
FreezingPoint = 32,
BoilingPoint = 212
}

enum CrazySet {
FirstVal, //value 0
SecondVal = 3, //value 3
ThirdVal, //value 4
FourthVal = 10, //value 10
FifthVal //value 11
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
376
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Operators & Assignment
Arithmetic Operators (Other operators will be discussed as
required)
• Addition (+)
• Subtraction (-)
• Multiplication (*)
• Division (/)
• Modulus (%)Returns Reminder
• 13 % 5 gives 3
Assignment
• Operator is =
• E.g. x = 5;
• Expression x = 5 gives 5
Y = x = 5;
Sets variable x with value 5 and then y with value 5

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
377
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Operators & Assignment
• Assignment with expression
int x = 5;
x = x + 2; //x gets the value of 7
• The second expression can be written as
x += 2;
• This form holds good for any of the other arithmetic
operators
var = var + value;
• Can be written as
var += value;
Increment decrement
x += 1; //increment x i.e. x gets 6
• Can be written as
x++; or ++x;
• Similarly decrement is by
x--; or --x

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
378
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Operators & Assignment
• Post Increment
int x = 5;
int y = x++; //y gets 5 and x becomes 6

• Pre Increment
int x = 5;
int y = ++x; //x becomes 6 and y gets 6

• The above is applicable to decrement operator (--) also

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
379
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Statements
Statement is a complete program instruction
Apart from Simple assignment statements we
have
• Selection or Conditional statements
• Iteration Statements
• Jump Statements
• Exception statements (Covered separately)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
380
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Conditional Statements
• Causes the program control to follow specific
flow based on a condition
• The condition yields a bool value and are
represented as boolean expressions with
relational and logical operators
• Categories of conditional statements are
• if / else
• switch / case

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
381
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Relational Operators
Assume x = 5 and y = 10
Expression Result

Equals x == 5 true
y == 6 false
Not Equals x != y true
y != 10 false
Greater than y > x true
Greater than x >= 5 true
or Equals
y >= 11 false
Less than x < y true
Less than or x <= y true
Equals
y <= 6 false
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
382
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Conditional Operators
Work on Relational expressions
Assume x = 5 and y = 10
Expression Result

and x == 5 && y == 6 false. Because Both


relational
expressions must be
true

or x == 5 || y == 6 true. Any one


expression may be
true

not !(x == 3) true. Unary


operator. Works with
one logical /
relational expression

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
383
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
If else statement
• Syntax
if (condition)
{
//Statements to execute if condition is true
}
else
{
//Statements to execute if condition is false
}
Condition is any relational / logical expressions

The following sample accepts a char from the user


and prints the type of the character

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
384
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
If else statement - Sample
public static void Main()
{
Console.Write("Enter a character: ");
char c = (char) Console.Read();
if (Char.IsLetter(c))
{
if (Char.IsLower(c))
Console.WriteLine("The character is lowercase.");
else
Console.WriteLine("The character is uppercase.");
}
else
{
Console.WriteLine(
"The character is not an alphabetic character.");
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
385
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
If else sample
• IsLetter, IsLower methods return true or false
• Any method returning a bool can be used in
conditional expressions

• If we need to change the program to check for


lowercase, upper case and digit (Alpha
numeric)
• The options are mutually exclusive
• If else if ladder can be used for this type of
problems

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
386
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
If else if
public static void Main()
{
Console.Write("Enter a character: ");
char c = (char) Console.Read();

if (Char.IsUpper(c))
Console.WriteLine("The character is uppercase.");
else if (Char.IsLower(c))
Console.WriteLine("The character is lowercase.");
else if (Char.IsDigit(c))
Console.WriteLine("The character is a number.");
else
Console.WriteLine("The character is not
alphanumeric.");
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
387
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
switch / case
switch (expression)
{
case constant-expression:
statement
jump-statement
[default:
statement
jump-statement ]
}
• Check expression against mutually exclusive constant-expressions
• Normally there will be multiple case statements
• default is optional
• Jump statement used is break

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
388
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
switch case Sample
class SwitchTest
{
static void Main(string[] args)
{
Console.WriteLine(
"Coffee sizes: 1=Small 2=Medium 3=Large");
Console.Write("Please enter your selection: ");
string s = Console.ReadLine();
int n = int.Parse(s);
int cost = 0;

//Small cup costs 25 cents


//Medium costs 50 cents
// and Large costs 75 cents

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
389
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
switch case Sample …
switch(n)
{
case 1:
cost += 25; // Add 25 Cents
break;
case 2:
cost += 25; // Add 25 cents
goto case 1; // Add another 25 thru case 1
case 3:
cost += 50; // Add 50 cents
goto case 1; // Add 25 cents thru case 1
default:
Console.WriteLine(
"Invalid selection. Please select 1, 2, or 3.");
break;
}
if (cost != 0)
Console.WriteLine(
"Please insert {0} cents.", cost);
Console.WriteLine("Thank you for your business.");
Console.ReadLine();
}
}

goto causes the control jump to a label (e.g. ‘case 1:’ )

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
390
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
switch case – Bad Practices
Use of goto & absence of break may lead to poor readability
of the code
The same switch need to be written as :
switch(n)
{
case 1:
cost = 25;
break;
case 2:
cost = 50;
break;
case 3:
cost = 75;
break;
default:
Console.WriteLine(
"Invalid selection. Please select 1, 2, or 3.");
break;
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
391
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Ternary Operator
A conditional operator Involves 3 operands
Syntax
Conditional Expression ? expr1 : expr2

Returns expr1 if condition is true expr2 otherwise

string result = ((n%2)==0 ? “even” : “odd”);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
392
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Bitwise operators

& Binary, Bitwise For (u)int and (u)long operands


AND bitwise AND is done. For bool
operands it is conditional operation
| Binary, Bitwise Same as above
OR
^ Binary, Bitwise Same as above
XOR
~ Unary, Bitwise Only for (u)int, (u)long
NOT
<< Left Shift Empty bits on the low order are
Operand << filled with zeros
count
>> Right Shift Empty bits on the high order filled
For all above>>
Operand binary operators except
with sign bit for uint“~”
and ulong,
count zeros for int and long
Short hand notation is applicable as
x &= 2; //same as x = x & 2
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
393
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Bitwise operators sample
Bitwise operators can be used for setting and
checking flags
class TextFormat
{
public const int normal = 0;
public const int bold = 1;
public const int italic = 2;
public const int underline = 4;
private int format = normal;

public void addFormat(int formatConst)


{
format = format | formatConst;
}

public bool checkFormat(int formatConst)


{
if ( (format & formatConst) == 0)
return false;
return true;
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
394
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Bitwise operators sample
public static void Main()
{
TextFormat tf = new TextFormat();
tf.addFormat(TextFormat.bold);
tf.addFormat(TextFormat.underline);

if (tf.checkFormat(TextFormat.bold))
Console.WriteLine("Bold");
if (tf.checkFormat(TextFormat.italic))
Console.WriteLine("Italic");
if (tf.checkFormat(TextFormat.underline))
Console.WriteLine("Underline");
}
} //end class

A TextFormat object could be defined with a combination of


Bold, italic and underline

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
395
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Iteration Statements
Used to execute statement(s) repeatedly (a.k.a. loops)
The statements executed in order unless a jump statement or
selection statement is encountered
Every loop must have a termination condition upon which loop
stops
• Termination condition could be under the control of the program
(deterministic loop)
• Or some external input or condition during program execution (non
deterministic loop)
• All variables taking part in the termination condition must be
initialized / set appropriately before evaluating termination
conditions
An index based loop is one which condition is controlled by a
variable
• The variable value is increased or decreased inside the loop to
achieve termination condition
Jump statements could be used to exit out of a loop

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
396
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
while loop
Syntax
while ( Condition )
{
//statements to be executed repeatedly
}

Condition is evaluated before the loop starts


If condition evaluates to true then the statements
executed once
This is repeated each time
Loop stops once the condition becomes false, flow
jumps to statements after the loop end

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
397
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
while sample
public static void Main()
{
int n = 1; //initialize n so that condition evaluates
while (n < 6)
{
Console.WriteLine("Current value of n is {0}", n);
n++; //index based loop n is incremented
}
}

This loop prints numbers from 1 to 5 when n


becomes 6 loop is exited and program ends

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
398
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
do loop
Syntax
Do
{
//statements to be executed repeatedly
} while ( Condition );

Loop executes atleast once


If condition evaluates to true then the statements
executed once again
This is repeated each time
Loop stops once the condition becomes false, flow
jumps to statements after the loop end

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
399
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
do sample
public static void Main()
{
int n = 1; //initialize n so that condition evaluates
do
{
Console.WriteLine("Current value of n is {0}", n);
n++; //index based loop n is incremented
} while (n < 6);
}

Same as while loop sample


Executes once even if n is initialized to 6

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
400
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Quiz
static void Main(string[] args)
{
string s = "Copy till you get g";
StringBuilder sb = new StringBuilder();
int i = 0;
while (s[i] != 'g')
{
sb.Append(s[i++]);
}
Console.WriteLine(sb);
}
What does this program do?
How many termination conditions are possible ( What
is missing?)?
Rewrite this with the additional check. And Rewrite
with do loop.
What is this StringBuilder class?

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
401
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
for loop
• While and do loops are mostly used for non index
based loops
• for loop is mostly index based though conversion of
one type of loop (while, do, for) into another type
is possible

Syntax
for ([initializers]; [expression]; [iterators])
{
//statements to be executed repeatedly
}
Order of execution
1. intializers
2. Conditional expressions (need to evaluate to true)
3. Statements
4. Iterators
5. Steps 2 , 3, 4

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
402
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
for loop sample
public static void Main()
{
for (int i = 1; i <= 5; i++)
Console.WriteLine(i);
}

This sample is the same as while and do samples


Prints numbers from 1 to 5

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
403
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Jump Statements
In a loop jump statements are used to
• Exit out of the loop or
• Skip part of loop
Otherwise they can be used for immediate transfer of
program control to another location of the code

break Used inside loops to exit out. Seen the


use of break with switch statement
continue Skip part of loop and go to top of loop
again
goto Jump to any label. Including case
expression
return Exit out of a function.
(will be covered in return 0; inside Main function ends
function topic) the program.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
404
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
break sample
static void Main(string[] args)
{
string s = "Copy till the end and look for ?";
StringBuilder sb = new StringBuilder();
int i = 0;
while (s[i] != 'g')
{
sb.Append(s[i++]);
if (i == s.Length )
break; //exit loop if you have copied last char
}
Console.WriteLine(sb);
}

break terminates the closest enclosing loop in


case of nested loops
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
405
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
continue sample
public static void Main()
{
for (int i = 1; i <= 10; i++)
{
if (i < 9)
continue; //skip the statements below
Console.WriteLine(i);
}
}

This prints only 9 and 10. Printing skipped for 1 to 8

When using a continue statement with while or do


loops care must be taken to ensure that the
increment / decrement statement of an indexed
loop are not skipped resulting in infinite loop
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
406
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Arrays (reference type)
• An array is a data structure that contains a number of
variables called the elements of the array
• The array elements are accessed through computed
indexes
• C# arrays are zero indexed; that is, the array indexes
start at zero
• All of the array elements must be of the same type, which
is called the element type of the array
• Array elements can be of any type, including an array
type
• An array can be a single-dimensional array, or a
multidimensional array
• Array types are reference types derived from the abstract
base type System.Array
• An array must be created with an initial size
• Once created the array length can not be altered
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
407
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Single Dimensional Arrays
Declaring an Array
type[] ArrayName;
• type can be any datatype (value or reference type)
• ArrayName is the variable name to refer the array
int[] Numbers; //Numbers is an array that can hold integers
Setting a size
ArrayName = new type[size];
• Size is a number
Numbers = new int[5]; //Numbers array can hold 5 integers
ShortCut
type[] ArrayName = new type[size];
int[] Numbers = new int[5]; //Both the steps above together

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
408
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Single Dimension array sample
static void Main(string[] args)
{
int[] evenArray = new int[5];

for(int i = 0; i < evenArray.Length ; i++)


{
evenArray[i] = i * 2; //set an array element
}

for(int i = 0; i < evenArray.Length; i++)


{
//obtain an array element to print
Console.WriteLine("Array[{0}] = {1}", i, evenArray[i]);
}
}
Accessing an element of an array
ArrayName[n] where n is between 0 and array length -1
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
409
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Array Initialization
Arrays can be initialized with constant values
The following 3 are equal
int[] myArray = new int[5] {1, 3, 5, 7, 9};

int[] myArray = new int[] {1, 3, 5, 7, 9};

int[] myArray = {1, 3, 5, 7, 9};

However For an unallocated array


int[] myArray;

intializations
myArray = new int[] {1, 3, 5, 7, 9}; // OK

myArray = {1, 3, 5, 7, 9}; // Error

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
410
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Multi Dimensional Arrays
Arrays can have more than one dimension
For example, the following declaration creates a
two-dimensional array of four rows and two
columns:
int[,] myArray = new int[4,2];
Also, the following declaration creates an array of
three dimensions, 4, 2, and 3:
int[,,] myArray = new int [4,2,3];

Initializing
• All rules like single dimensional array initialization
int[,] myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}};
• Or
int[,] myArray = {{1,2}, {3,4}, {5,6}, {7,8}};

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
411
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Multi Dimensional Arrays
Size of single dimension array can be found by
Length property
For a multidimensional array the max index on each
dimension is found using the function
GetUpperBound(dimension)

For the previous sample


myArray.GetUpperBound(0)
gives 3 (i.e.) 4 Elements on the first dimension
indexed from 0 to 3

Similarly
myArray.GetUpperBound(1)
gives 1
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
412
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Quiz
static void Main(string[] args)
{
int[,] MultTable = new int[5,3];

for( int i = 0; i <= MultTable.GetUpperBound(0); i++)


{
for (int j = 0; j <= MultTable.GetUpperBound(1); j++)
{
MultTable[i,j] = i *j;
}
}
}

What does this program do?


Add code to print the contents like a matrix.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
413
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Jagged Arrays
• A Jagged Array is an array whose elements are
arrays
• Not rectangular (2 dim) or cuboid (3 dim) …..

• Declare a jagged array with 3 arrays


int[][] myJaggedArray = new int[3][];
• Create child arrays and set values later
myJaggedArray[0] = new int[5];
myJaggedArray[1] = new int[4];
myJaggedArray[2] = new int[2];
• Or Initialize child arrays
myJaggedArray[0] = new int[] {1,3,5,7,9};
myJaggedArray[1] = new int[] {0,2,4,6};
myJaggedArray[2] = new int[] {11,22};

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
414
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Jagged Arrays
• Doing all at once (if initialization is required)
int[][] myJaggedArray = new int [][]
{
new int[] {1,3,5,7,9},
new int[] {0,2,4,6},
new int[] {11,22}
};
OR
int[][] myJaggedArray = {
new int[] {1,3,5,7,9},
new int[] {0,2,4,6},
new int[] {11,22}
};
• Access an element
myJaggedArray[1][3] = 10; //Overwrite the value 6 with 10

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
415
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Quiz
Print the jagged array on the console

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
416
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Arrays – Special loop construct
Syntax
foreach (type variable in Array) statement(s)

For each iteration of statements the variable


assumes a value from the array from first to last
Statement(s) are executed for each element in the
array
Statements can process the value contained in the
variable

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
417
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
foreach sample
public static void Main()
{
int odd = 0, even = 0;
int[] arr = new int [] {0,1,2,5,7,8,11};
foreach (int i in arr) //Go thru each element
{
if (i%2 == 0) //Check each element
even++; //Count evens
else
odd++; //Count odds
}
Console.WriteLine(
"Found {0} Odd Numbers and {1} Even Numbers.",
odd, even) ;
}
Variable ‘i’ takes the values 0,1,2,5,7,8,11 on each
iteration
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
418
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Debugging In Visual Studio
2005

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Debugging Features In Visual Studio
2005
In Visual Studio 2005 you can debug C# and
C++, Visual Basic and VBScript. Step over
managed code, native code, mobile code, and
T-SQL code.

The two options of debugging are


1. Debug locally
2. Debug remotely

You can debug assemblies hosted by SQL Server, and JavaScript


hosted by Internet Explorer

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
420
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Debugging Features In Visual Studio
2005
There is just-in-time debugging and just my code debugging.

You can step into XML web services and into XSL transformations.

The debugger has data tips, and data visualizers, breakpoints and
tracepoints.

You can inspect threads, modules, memory, and call stacks.

you can view both local and global variables.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
421
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Debugging Features In Visual Studio 2005

There are three ways to start a debugging session in Visual


Studio.NET
The “Start” and “Step Into”
commands will both launch
your application and begin
a debugging session.

If you are inside of Visual Studio with an open project, you can use the
Debug menu to get started.

• A final method for beginning a debugging session is to wait for Just-In-


Time debugging to step in during an application crash.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
422
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Debugging Features In Visual Studio 2005
A second option is to use the “Attach to Process…” command on the
Debug menu.

The Attach command


will let you break into a
running application and
begin a debug session.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
423
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Debugging Features In Visual Studio 2005
A final method for beginning a debugging session is to wait for Just-In-
Time debugging to step in during an application crash.

ASP.NET developers won’t be


able to take advantage of JIT
debugging. The ASP.NET
runtime will not let an
unhandled exception terminate
the application.

On a computer with debugging tools installed, the JIT debugger will step in and
allow you to start a Visual Studio debugging session. If the application has
source code and debug symbols present, Visual Studio can take you directly to
the line of code responsible for the unhandled exception.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
424
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Breakpoints
Breakpoint can be used to collect information while pausing, or breaking
into the execution of your application at just the right spot. When the
debugger is in break mode, you can examine objects and local variables to
see the flow of your code.
A common method to set a breakpoint is to press F9 while the cursor is on
the line of code you want to break on.
When a breakpoint is set, a round, red glyph will appear in the left margin
of the editor.
You can also click in this area of the editor to add a breakpoint. Right click
on an existing breakpoint glyph to set properties, disable, or delete the
breakpoint.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
425
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Breakpoints
When execution reaches a
breakpoint, the debugger
pauses all of the
application’s threads and
allows you to inspect the
state of your application

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
426
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Breakpoints

The other way to set a


breakpoint is add break
point to function

Right click on an existing breakpoint glyph to set properties, disable, or delete the
breakpoint.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
427
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Breakpoints
Specify a condition for a
breakpoint to occur.

Breakpoint Condition is used to set a condition so that the breakpoint will hit
only if the expression returns true or the value has changed.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
428
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Breakpoints

You can also


combine logical
clauses to set a
condition

By using Breakpoint filter you can restrict the breakpoint to be set only for a
particular process or thread.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
429
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Breakpoints

There are hundreds


of macros by
default available for
specific task

By using when breakpoint window you can program a specific task when the
breakpoint occurs.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
430
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Immediate Window

Best suted for


handling bugs in code

By using Immediate window you can check a value of a variable or a output of a


function dynamically at runtime.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
431
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Stepping Through Code

Once you pause execution you have the ability to step through code, in other
words, execute code one line at a time.
From the debug menu there is a Step Into command (F11) . If you are
currently in break mode on a line of code that contains a method call.

Use Step Into if you want Step Over if you only want
to see what happens to execute the entire
inside a method call method and continue in the
current code block

Step Out command, is used


when you want to execute the
rest of the current method and
return to the calling method

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
432
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Watch Window

You can add a variable to


the watch window by right
clicking a variable and
selecting “Add Watch”.

A Watch Window will display an object’s state until you explicitly remove the
object from the window.The watch window supports the ability to “drill down” into
a complex object.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
433
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
SQL Server Stored Procedure
Debugging
One cool feature with VisualStudio 2005 is the ability to debug SQL Server™ stored
procedures.

To enable this feature, you'll need to make sure that the SQL Server debugging
components have been installed on your machine and that you have the appropriate
permissions to debug stored procedures.

Use the Server Explorer to select any SQL


Server database on your network, bring up
your stored procedure, set a breakpoint,
and then execute the code that calls that
stored procedure.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
434
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Wrap Up
When your program is buggy, Visual Studio will give you all the tools
you need to track down the error. Control the execution of your
application with breakpoints, and use variable windows, data tips, and
visualizes to inspect state along the way

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
435
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Visual Studio Class
Designer

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Visual Studio Class Designer
The Visual Studio Class Designer lets you visualize the structure of classes
and their relationships, create new classes using a visual design
environment, and easily refactor classes.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
437
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Features of Visual Studio Class Designer

1. The Visual Studio Class Designer lets you visualize the structure of classes and
other types, and through these visual representations edit their source code.
2. Changes made to the class diagram are immediately reflected in code, and changes
made to the code immediately affect the appearance of the designer.
3. Complex CLR types can be configured visually .
4. Visual Studio Class Designer lets you to easily refactor the code.
5. You can easily rename identifiers and override methods
6. You can automatically generate classes and structures, and implement interfaces by
automatically generating stubs.
7. Class Designer also serves as a communication tool by letting you easily
communicate areas of your code base to colleagues
8. Display reports in HTML pages or PowerPoint presentations.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
438
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Components of Visual Studio 2005 Class Designer

The Class View


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
439
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Components of Visual Studio 2005 Class Designer

ToolBox

Class Details Window

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
440
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Classes with the Class Designer

Class Designer makes it easy to create and configure classes in your project.
The class diagram is actually a live view of your code. Changes to the
diagram are automatically synchronized with the code, and vice versa. You
can create a simple class by dragging it from the Toolbox to the Class Design
surface.
To add a method, for example, you click <add method> in the Class
Details window and type the name of the method. You can then indicate the
return type, the access level, and add any comments about the method.

Once a method is created, you can add parameters—to the method name in
much the same way as you add methods-first by indicating the name of the
parameter, then indicating the type, the modifier, and any comments.

Properties, fields, and events are added the same way that methods are
added.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
441
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Implementing an Interface

The Class Designer makes it easy to implement interfaces in your classes. In


fact, if your interface is displayed on the class designer surface, you can
implement it using the same procedure you would use to inherit a class; by
drawing an inheritance line from the class to the interface.

If the interface is not displayed in Class Designer, however, it is


still easy to implement. You simply drag the interface from the
Class view onto the class that you want to implement. Method
stubs are automatically generated for the methods defined in the
interface.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
442
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Visualizing an Inheritance Hierarchy
You can use Class Designer to visualize inheritance hierarchies in a
project. To show the base class of an inherited class, right-click the
header area of the class and click Show Base Class. The base class
appears on the diagram.

To show classes that inherit from an existing class, right-click the header
area of the class and select Show Derived Types. The derived classes
appear on the diagram, connected to the class by an inheritance line

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
443
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Summary
Understanding existing code: Existing code bases can be complicated
and confusing. With a visual class designer, you can graphically explore
existing class hierarchies and get a feel for how classes relate to each
other.

Class Design: A visual class designer allows you to graphically create the
high level design and implementation of your software.

Reviewing and refactoring Code: A visual class designer is a powerful


tool for code reviews and refactoring. Existing code diagrams can be
annotated for review, and code can be refactored using a designer, saving
time.

Class diagrams for documentation: Class diagrams can be used to


document the existing class hierarchies, graphically displaying inheritance
trees. Class diagrams are also useful for communicating ideas with
colleagues, through email or visual presentations.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
444
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Class & Object

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Class
• Class is an abstraction of related objects properties
and behaviors
• Class is a blue print to define and create objects
• For each user defined object type a class definition
must be provided
• An instance of a class is called an object
• An object is a composition of state data and
behavior
• The state data (a.k.a. Properties) are declared as
variables inside a class
• And behavior are defined as functions
• Objects are reference types
• An object variable contains reference to the object created in
memory

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
446
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Defining classes
[attributes] [modifiers] class identifier [:base-list]
{
class-body
}[;]
Items in square brackets are optional
Class Identifier is the type name you wish to create
Modifiers could be either public or internal (default)
public – Globally visible, anybody could create an
object of this class
internal or no modifier – visible only with in
current dll or exe , more on this later

attributes & base-list are deferred to a later time

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
447
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Defining class members - state
State or properties of the class are defined by
variables
The variables take the form of
[public or private] [static]
type varaiable-name [=intial-value];
public variables can be accessed outside class using
object reference
• private variables are accessible only with in the
class definition

• static variables can be accessed without creating


an object of this type
• static variables are referred to as class variables
The Syntax is not complete. New modifiers will be
introduced as necessary

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
448
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Defining class members - behavior
Behavior of the class are defined by functions
Functions are the very first encapsulation in the
field of programming
The functions take the form of
[public or private] [static]
type function-name (params) { statements }

• public , private and static mean the same as


that of variables
Again this syntax is also not complete

Let us explore creating functions in the following


sections …

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
449
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Anatomy of Functions
A function is analogous to a system or a f(x)
computation from maths
A function has got
• Input(s)
• Process
• Output(s)

From the previous slide


• type is the datatype of the main output value or
void if it does not return anything
• statements are process
• params are the input

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
450
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Function types
The Main method is of type void since it does not return
anything
The Main method signature can be changed to return an
int

public static int Main(string[] args)


{
Console.WriteLine(“Hello, World!”);
return 0;
}
Here a return value 0 means a successful execution of
the application and used by OS
But the functions that are used internally by the
application return data which are used by the code
which called the function.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
451
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Function types…
Class SimpleInterest {
public static float CalculateInterest(
float amount,
int year,
float rate)
{
float interest = (amount * year * rate)/100;
return interest;
}
static void Main(string[] args)
{
float intamount = CalculateInterest(1000F, 1, 7.25F);
Console.WriteLine("Interest = {0:F2}", intamount);
}
}
Static function – No object of type SimpleInterest need to be
created in Main
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
452
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Parameter mechanism
• amount, year and rate are called formal
parameters
• Formal parameters are declared with appropriate type
• The values 1000F, 1 and 7.25F or are the actual parameters
• The values of actual parameters are copied into the formal
parameters and the statements of the function body are
executed
• Actual parameters could be passed as constant values or
variables containing input values
• Only the result is returned, the values are not copied back
to formal parameter (Pass By value)
• DIY :
Declare 3 variables inside Main and intialize them to 1000F, 1
and 7.25F respectively. Pass them as parameters to the
function.Try to change the value of amount or year or rate
inside the function and print the values in main after
calculating interest. Check whether they are changed

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
453
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Changing Parameter value – out – One way

What if we need more than one output from a function?


A function that takes 2 numbers as input and calculates the
sum and difference
See the function below :
public static void CalculateSumnDiff(int n1, int n2,
out int sum, out int diff)
{
sum = n1 + n2;
diff = (n1 > n2)? n1 - n2 : n2 - n1;
}

• The function does not return a value – void


• There are 2 additional parameters declared int sum and int
diff and marked as out
• Sum and difference are calculated in this function and placed
in the formal parameters
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
454
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Changing Parameter value – out – One way

static void Main(string[] args)


{
int x = 10, y = 12;
int s, d;
CalculateSumnDiff(x,y,out s, out d);
Console.WriteLine("Sum = {0}, Diff = {1}", s,d);
}
• The code above shows how the function can be invoked
• Note that the two out variables are not initialized
• While passing out parameter we need to add out in front of
the actual parameters

This mechanism is one way; the values are passed


from a formal parameter to the actual
parameters, opposite to pass by value
mechanism.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
455
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Changing Parameter value – ref – Two way

Ref parameters are used as two way parameters


A value is passed into the function and another
value got out thru the same parameter
Consider a function which swaps the values of 2
int variables
public static void swap (ref int n1, ref int n2)
{
int temp = n1; //put the value of n1 into a temp variable
n1 = n2; //put the value of n2 into n1
n2 = temp; //put the value of n1 from temp into n2
}
• The function does not return a value – void
• The parameters are marked as ref
• Values of formal parameters are swapped

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
456
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Changing Parameter value – ref – Two way

static void Main(string[] args)


{
int x = 10, y = 12; //initialize values
Console.WriteLine("Before Swap : x = {0}, y = {1}", x, y);
swap(ref x,ref y);
Console.WriteLine("After Swap : x = {0}, y = {1}", x, y);
}
• The code above shows how the function can be invoked
• Note that the ref variables must be initialized or must contain a
value while calling the function
• While passing ref parameter we need to add ref in front of
the actual parameters

This mechanism is two way; the values are passed


from a formal parameter to the actual parameters
and back after the function execution.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
457
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Variable number of Parameters
• Methods that take variable number of
parameters
• Main
• Console.WriteLine
• The keyword to specify a variable number of
parameters (all of same type) is params
public static int sum(params int[] numbers)
{
int sum = 0;
foreach (int n in numbers)
{
sum += n;
}
return sum;
}
static void Main(string[] args)
{
int s = sum(1,2,3,4,5);
Console.WriteLine("Sum is : {0}", s);
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
458
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Variable number of Parameters
• Parameters are presented to the method in an
array
• If you want to mix the parameters type like
Console.WriteLine method then the function
must accept an object array
• Check this in the API help or using intellisense
• Some methods ( like Console.WriteLine) will
take one or more fixed parameters (format
String ) and a variable list (items to printed)

Write a method that accepts a list of numbers and


computes sum and average

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
459
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating classes
class Kid
{
public int age;
public string name;
// Printing method:
public void PrintKid()
{
Console.WriteLine("{0}, {1} years old.", name, age);
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
460
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating classes
class MainClass
{
static void Main(string[] args)
{
Kid kid1 = new Kid(); //Create a Kid object
kid1.PrintKid();
//Set Data
kid1.name = "Craig";
kid1.age = 10;
kid1.PrintKid();
}
}
At First an object is created which got its individual state members
initialized to their default values – A Default behavior!
Then the data are set to give the object a meaning.
There is a good chance that some data are initialized and some are
not -> Inconsistent State
The Class creator must ensure that the objects are initialized with
some data.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
461
Constructors
• Constructors are methods in the class with function name
equivalent to class name
• Constructors will not have a return type including void
• Constructors take initializing data as parameters
• Constructor that does not take any parameters are called
default constructor
• C# compile provides a default constructor if no constructor is
defined for the class as in previous sample
• If a non default constructor is provided for a class then an
object cannot be created by passing no parameters (i.e.
default constructor)
A class can provide multiple constructors based on the
combination of parameters (Overloading)
But consistent state must be ensured

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
462
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Constructors
• Adding a constructor to Kid class
public Kid(string name, int age)
{
this.name = name;
this.age = age;
}
• A kid object will be initialized with a proper value of
name and age
• this keyword refers to the current object and used to
resolve the ambiguity of the variable names (name &
age)
• Now a Kid type object cannot be constructed with out
passing parameters
• Try adding this constructor and check the above point

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
463
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Constructors - Initializers
• If we need to create a object using no
parameters then a set of default values need to
be initialized
public Kid() : this("No name", 1) //use initializer
{
//Empty body
}
• This default constructor makes use of the other
constructor to initialize values

• Try creating 2 kid objects one by invoking the


constructors with parameters and other without
parameters. Print the objects and check the
values
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
464
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Private Constructor
• A private constructor is a special instance constructor
• It is commonly used in classes that contain static
members only
• If a class has one or more private constructors and no
public constructors, then other classes are not allowed to
create instances of this class
public class MyClass
{
private MyClass() {}
public static int counter;
public static int IncrementCounter()
{
return ++counter;
}
}
An Instance of this cannot be created. But an initial value
for the counter can be set and incremented and accessed
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
465
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Static constructor
• Does not take access modifiers or have parameters
• Called automatically to initialize the class before the first
instance is created or any static members are referenced
• Cannot be called directly
• The user has no control on when the static constructor is
executed in the program
• A typical use of static constructors is when the class is
using a log file and the constructor is used to write
entries to this file
class MyClass
{
// Static constructor:
static MyClass()
{
Console.WriteLine("The static constructor invoked.");
}
public static void MyMethod()
{
Console.WriteLine("MyMethod invoked.");
}
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
466
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Quiz
• Use the sample of private constructor and write a main
method to set counter, increment and print values
• For the static constructor sample write a main method to
invoke MyMethod and check the output
• Private constructors are used to prevent others from
creating objects. How will you control a class in such a
way that only one instance of that class exists and
anybody wants to invoke a method on that class obtain
the reference of the pre-created object using a method?
Hint :
• Use a static instance variable to hold the reference of self
• Set it using private constructor

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
467
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Properties

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Properties
Kid Class revisited :
• We have provided Constructors to initialize an
object with meaningful data
• But the name and age are still public (These are
called fields of a class)
• Having public data members
• makes the class vulnerable and anybody can change the
state data
• You cannot put code with which you can validate the data
that is being set to a state variable
• Properties come to the rescue
• You can encapsulate data, keep state private
• Interfere when a state variable is getting accessed or
changed

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
469
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Adding Properties
• Make age and name , private
Add the following code to Kid Class
public int Age //Age is the name of the property
{
get { return age; } //Accessor
set { //Mutator
//Validate the value being set
if ((value < 12) && (value >= 0))
age = value;
else
age = 0;
}
}

Now age for a Kid object could be set using


aKid.Age = 9;
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
470
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Properties explained
• A property is composed of
• a get block – Accessor
• A set block – Mutator
• In get block return the private instance variable
• In set block the keyword value represents the
value that is being set
• Properties can be static then they are
associated with the class not with a specific
instance

Demo With Visual Studio


• Provide a property called “Name” to the Kid
class, In set block validate the value for empty
or null string
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
471
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Read-Only property
• set block is omitted only get is provided
• Or
• Member variable declared as
public readonly string Name;
This variable could be assigned a value only in the constructor
or intialised
• A readonly property with get can be used to
return a computed value
• Where there is no equivalent private variable to hold the
value
Create a rectangle class with properties Length
and width, Provide a computed read-only
property “Area”
• While it is absolutely permitted to omit a get
and provide a set leading to write-only property
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
472
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Property visibility

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Property visibility

  C# 2.0 allows you to specify different visibility


for the get and set accessors of a property or an
indexer.

Ex: It is quite common to want to expose the get


as public, but the set as protected.
To do so, add the protected visibility qualifier to the set keyword.
Similarly, you can define the set method of an indexer as protected

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
474
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Example

public class MyClass


{
public string getName
{
get
{
return name;
}
protected set
{
name = value;
}
}
string names; //Rest of the class
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
475
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Property visibility Considerations

1. First, the visibility qualifier you apply on the set or the get can only be a
stringent subset of the visibility of the property itself.
2. If the property is public, then you can specify internal, protected, protected
internal, or private.
3. If the property visibility is protected, you cannot make the get or the set
public.
4. you can only specify visibility for the get or the set, but not both.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
476
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Kid – Complete Source
class Kid
{
private int age;
private string name;

// Default constructor:
public Kid() : this("No name", 1)
{
}
// Constructor:
public Kid(string name, int age)
{
this.name = name;
this.age = age;
}
// Printing method:
public void PrintKid()
{
Console.WriteLine("{0}, {1} years old.", name, age);
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
477
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Kid – Complete Source …
public int Age {
get { return age; }
set {
if ((value < 12) && (value >= 0))
age = value;
else
age = 0;
}
}
public string Name
{
get { return name; }
set
{
name = (value.Length != 0)? value : name;
}
}
} //End Class
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
478
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Destructors
• Invoked when an object (reference type) gets removed
from the memory
• Objects that are not used anymore are removed from the
memory by an automatic process called Garbage
Collection
• This is a non-deterministic destruction and developers
have NO control over it
• Destructors with a method name “ ~ClassName “have no
return type and does not take any parameter (invoked by
Garbage collector)
• Used to cleanup any resources
• Close Database connection
• Close files
~ Kid()
{
// Cleanup statements.
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
479
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Partial Class

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Partial Classes
C# 1.1 requires you to put all the code for a class in
a single file.
C# 2.0 allows you to split the definition and
implementation of a class or a struct across multiple
files. You can put one part of a class in one file and
another part of the class in a different file, noting the
split by using the new partial keyword.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
481
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Partial Classes
public partial class MyClass{
public void Method1()
{...}
}

In the file MyClass2.cs, you can insert this code:

public partial class MyClass{


public void Method2() {...}
public int Number;
}

Partial type support is available for classes, structures, and interfaces, but you
cannot have a partial enum definition.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
482
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Aspects of a partial Class
Partial class have two kinds of aspects or qualities: accumulative and
non-accumulative.
The accumulative aspects are things that each part of the class can
choose to add, such as interface derivation, properties, indexers,
methods, and member variables.
public partial class MyClass{}
public partial class MyClass : IMyInterface
{
public void Method1() {...}
public void Method2() {...}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
483
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Aspects of a partial Class
The non-accumulative aspects are things that all the parts of a type
must agree upon. Whether the type is a class or a struct,
public class MyBase{}
public class SomeOtherClass{}
public partial class MyClass : MyBase{}
public partial class MyClass : MyBase{
}
//Does not compile
public partial class MyClass : SomeOtherClass{}

The partial modifier is not available on delegate or enumeration


declarations.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
484
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Partial Class Support

C# 2.0 supports partial types as follows: when the compiler builds the
assembly, it combines from the various files the parts of a type and compiles
them into a single type in Microsoft intermediate language (MSIL). The
generated MSIL has no recollection which part came from which file. Just like in
C# 1.1 the MSIL has no record of which file was used to define which type.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
485
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Advantages of Using Partial Class

In ASP.NET 2.0 we can use partial classes for the code-beside class (the
evolution of codebehind), storing the machine-generated part of the page
separately.
In Windows® Forms partial classes are used to store the visual designer
output of the InitializeComponent method as well as the member controls in
a separate file thus giving code clarity.
Partial types also enable two or more developers to work on the same
type while both have their files checked out from source control without
interfering with each other.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
486
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Partial Class
Nested types can be partial, even if the type they are nested
within is not partial itself. For example:

class Container
{
partial class NestedKid
{
void Printkid() { }
}
partial class NestedKid
{
void NestKid() { }
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
487
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Partial Types

At compile time, attributes of partial-type definitions are


merged. For example, the following declarations:

[System.SerializableAttribute]
partial class Kid { }

[System.ObsoleteAttribute]
partial class Kid { }

are equivalent to:

[System.SerializableAttribute]
[System.ObsoleteAttribute]
Partial class Kid{}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
488
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Partial Types

The following are merged together from all the partial-type definitions:
XML comments

interfaces
generic-type parameter attributes
class attributes
members

For example, the following declarations:

partial class Kid : Icomparable, Icomparer { }


partial class Kid : IEnumerator { }
are equivalent to:

class Kid : Icomparable, Icomparer , IEnumerator { }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
489
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Constraints for a partial Class
All partial-type definitions meant to be parts of the same type must be modified
with partial.

The partial modifier can only appear immediately before the keywords class,
struct, or interface.

All partial-type definitions meant to be parts of the same type must be defined in
the same assembly and the same module (.exe or .dll file). Partial definitions
cannot span multiple modules.

The class name and generic-type parameters must match on all partial-type
definitions.

Generic types can be partial.

Each partial declaration must use the same parameter names in the same
order.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
490
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Partial Types
The following keywords on a partial-type definition are optional,
but if present on one partial-type definition, cannot conflict with
the keywords specified on another partial definition for the same
type:
public
private
protected
internal
abstract
sealed
base class
new modifier (nested parts)
generic constraints

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
491
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Partial Class Example

public partial class Kid


{
private string name;
private int age;
public Kid(string x, int y)
{
this.name = x;
this.age = y;
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
492
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Partial Class Example
public partial class Kid
{
public void PrintKid()
{
System.Console.WriteLine(“The Kid is {0},
{1}", name, age);
} }
class TestCoOrds
{
static void Main()
{
CoOrds kidObj = new CoOrds(Mickey, 15);

kidObj.PrintKid();
}}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
493
Static Class

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Static Class

Under C# 1.1, if you want to prevent people from instantiating objects of your class then
you can provide a private default constructor.
Without any public constructors, no one can instantiate objects of your class:

public class Kid


{
private Kid()
{
}
static public object CreateObject()
{...}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
495
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Static Class

It is still up to you to enforce the fact that only static members are defined on the class.

public class Kid


Have You Noticed ,C# compiler will
{ still allow you to add instance
private Kid() members, although they could never
be used.
{
}
static public object CreateObject()
{...}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
496
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Static Class

C# 2.0 adds support for static classes by allowing you to qualify your
class as static
The C# 2.0 compiler will not allow
public static class Kid you to add a non-static member to
{ a static class

private Kid()
{
}

static public T CreateObject<T>()


{...}
What else…
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
497
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Static Class
To Note…

1. C# compiler will not allow you to create instances of the static


class as if it were an abstract class.
2. You cannot derive from a static class. It's as if the compiler
adds both abstract and sealed to the static class definition.
3. You can define static classes but not static structures, and you
can add a static constructor.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
498
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Structures

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Structures – struct
• Are value types
• All C# datatypes have a struct equivalent (already seen)
• Are similar to classes and have
• Constructors
• Properties
• Methods
• Cannot initialize member data
• Do not support inheritance (Discussed later)
• No default constructor provided
• Cannot have destructors (not a reference type)
• Are implicitly derived from object (like any other value
type)
• Used to represent light weight objects that have a value
semantics
• Complex numbers, point, rectangle…

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
500
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Struct - sample
public struct Location
{
private int xCoord;
private int yCoord;

public Location(int x, int y)


{
this.xCoord = x;
this.yCoord = y;
}
public int x
{
get { return this.xCoord; }
set { this.xCoord = value; }
}
public int y
{
get { return this.yCoord; }
set { this.yCoord = value;}
}
}

This shows a struct which is similar to a class which has


Constructors, encapsulated members and properties
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
501
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Structs …
Creating a Location variable
Location Loc1 = new Location(10,10);
We can also create a struct variable without new (
a characteristic of value type)

But with this sample


Location Loc2;
Loc2.x = 10; //error
The error is because Loc2 is not initialized. Not
only properties, methods also wont work.

If we don’t want to use new to create struct


variables then the struct data members must
have to be initialized directly

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
502
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Structs… exercise & Learn
Fix the Location struct so that the following code works
static void Main(string[] args)
{
Location loc2;
loc2.xCoord = 50; //Please see note below
loc2.yCoord = 100; //Please see note below
loc2.printLocation(); //A method to be added to Location
}
Note :
All data members of struct need to be initialized in the calling
code before using it
Compact the code by removing the properties. Data members
have been made public. So we don’t need encapsulation
and constructors also not needed.
Remember the implications of coding while deciding on struct
Vs class. For Object oriented behavioral semantic objects
use classes
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
503
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Structs sample code
public struct Location
{
public int xCoord;
public int yCoord;
public Location(int x, int y)
{
this.xCoord = x;
this.yCoord = y;
}
public int x
{
get { return this.xCoord; }
set { this.xCoord = value; }
}
public int y
{
get { return this.yCoord; }
set { this.yCoord = value;}
}
public void printLocation()
{
Console.WriteLine("x = {0}, y = {1}", this.xCoord,
this.yCoord);
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
504
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Boxing & Un-Boxing
Value type variables are short lived and created in stack
Reference type variables are created in heap (Global
memory)
Boxing : Converting a value type into a reference type
Unboxing : Converting reference type to a value type
static void Main(string[] args)
{
int i =123;
object o = i; //boxing
int j = 0;
if (o is Int32) //Checking the type using is operator
{
j = (int)o; //Unboxing
}
Console.WriteLine(" j = {0}", j); //prints 123
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
505
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Boxing & Un-Boxing pitfalls
When we pass value type variable into a method which
expects an Object type as parameter
Boxing takes place automatically and a temporary object is
created

The formal parameters and local variables of a method are


created in stack only if they are value types
For reference type parameters the variable containing the
reference of the temp object is created in stack as per
above rule
But the temporary object itself is created in heap

This temporary object need to be Garbage collected and a


lot of such empty boxes created with the careless coding
can stress the memory and affect performance

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
506
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
C# Programming
language
Part 2

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
1. Inheritance
2. Abstract methods and Classes.
3. Multiple Inheritance.
4. Operator Overloading and Type Conversion.
5. Interfaces.
6. Collection Interfaces.
7. Nested Classes.
8. Indexers.
9. CallBacks
1. Delegates
2. Events
10.Exception Handling.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
508
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Inheritance

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Inheritance
Objectives :
• To build a family of related classes
• Code reuse amongst related objects
How ?
• Find Is-a relation ship
• Generalization
• Find Common things in related entities
• Create a base class with common attributes and behaviors
• Mammal is general class for Dog, Whale and Human
• Specialization
• Used mostly for adding entities later into the system
• Find the base class to inherit from and add special attributes &
behavior
• For a scalable design both Generalization and
Specialization must be used
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
510
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Simple Inheritance - Sample
Assume a typical Payroll application with an
Employee class
class Employee
{
protected int EmployeeID;
protected string FullName;
protected decimal BaseSalary;
public Employee() { }
public Employee(int id, string fullName, decimal baseSalary)
{
this.EmployeeID = id;
this.FullName = fullName;
this.BaseSalary = baseSalary;
}
public decimal computePay()
{
return this.BaseSalary;
}
public string Name //Only one property shown for simplicity
{
get { return this.FullName; }
}
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
511
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Base Class Explained
• Protected members could be accessed only in
the derived classes, unrelated classes cannot
access them
• Only Name property is shown, it is always
better to have other read-only properties as
well
• A default constructor is provided here, Though
it is not a good practice
• We will learn how to get rid of that when we
get more knowledge in inheritance

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
512
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Access Modifiers

Client

Child Class Unrelated Class

Component

Public

Protected

internal

Private
Child Class Unrelated Class

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
513
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Simple Inheritance - Sample
Now a Contractor class inherited from Employee
The pay for the contractor is based on overtime
(Specialization)
class Contractor : Employee
{
public int OverTime; //Additional Attribute
public decimal Rate; //Additional Attribute
public Contractor(int id, string fullName,
decimal baseSalary, int overTime, decimal rate)
{
EmployeeID = id; //Access base class Members
FullName = fullName; //Access base class Members
BaseSalary = baseSalary; //Access base class Members
OverTime = overTime;
Rate = rate;
}
public decimal computePay()
{
return (BaseSalary + OverTime * Rate);
}
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
514
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Simple Inheritance - Sample
Now the PayRoll Class :
class PayRoll
{
public static void Main(string[] args)
{
ArrayList Employees = new ArrayList();
Employees.Add(new Contractor(100, "Andrew Troelson",
1500.00M, 20, 25.00M));
Employees.Add(new Contractor(101, "Jesse Liberty",
1400.00M, 30, 20.00M));
Employees.Add(new Contractor(102, "Juval Lowy",
1700.00M, 10, 30.00M));

foreach (Contractor w in Employees)


{
decimal pay = w.computePay();
Console.WriteLine("{0} -> {1:C}", w.Name, pay);
}
}
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
515
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
PayRoll Explained
• The ArrayList “Employees” is the collection to
hold the 3 contractors
• Contractors are created and added to the virtual
organization
• For each contractor the pay is computed and
printed

This program just runs fine and prints the correct


output except for 1 warning ……………

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
516
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Revelation #1 : Bad Construction
• We saw during our class construction that default
constructors put the object in an inconsistent state
• Why do we have it here then?
• Try adding a
Console.WriteLine(“Hello, I am an Employee”); Statement
to the Employee’s default constructor
• You see this message getting printed while you create 3
of those Contractors
• So the derived class constructor calls the base class
constructor
• If you remove the default constructor you get an error
message from the compiler
• The best way is to invoke the non default base class
constructor from the non default derived class
constructor yourself and get rid of the default constructor
from the Employee class
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
517
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Revelation #1 : Bad Construction…
• How to do?
• Similar to invoking a non default constructor from a
default constructor by passing default state values
• But with a different keyword, change the code as below
public Contractor(int id, string fullName,
decimal baseSalary, int overTime,
decimal rate) : base ( id, fullName, baseSalary)
{
this.OverTime = overTime;
this.Rate = rate;
}
• Now when you run the Hello message is not printed
anymore
• Delete the default constructor from the Employee
• RIP

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
518
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Revelation #2 : Inheritance taught by C# compiler

• C# Compiler tells you that you need to add


keyword new to the computePay method because
it hides the Employee.computePay method
• Before learning what this new keyword is, let us
see some design aspects
• You will not have only one employee type in the organization,
if you have then inheritance may not be required
• Even if you have only one type for now you don’t know about
tomorrow
• To worsen the IS departments life a Manager class is added to
the Organization whose pay depend upon their performance
bonus
• Now you will be creating few Manager objects and adding
them to the ArrayList
• And change the foreach statement to
foreach (Employee w in Employees)
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
519
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Revelation #2 : Inheritance taught by C# compiler
• If we try to run even without creating a Manager class and
adding Manager objects, but changing the foreach statement
alone
• Compiler warning is still there (What is this new?)
• But to our horror the payroll prints BaseSalary 
• The lesson is that
• When you inherit the computePay method but changing the way
it calculates the pay
• The method in the base class must be marked virtual and the
derived class method must be marked override
• Change the signatures to
• Employee class
public virtual decimal computePay()
• Contractor class
public override decimal computePay()
• Now this in Main will print the correct pay for the contractors
foreach (Employee w in Employees)
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
520
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Revelation #2 : Inheritance taught by C# compiler

• Now happy compile and happy run


• Exercise
Make changes as per the revelations Add a manager
class and add managers to your organization and
compute pay
After adding Manager type you have 2
implementations of computePay method that is
invoked using a base class reference
• Still it invokes the appropriate types
calculations
• This is achieved using Virtual/override pair
• In OO terms this is called POLYMORPHISM
• Many forms of one function

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
521
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Versioning, Shadowing – new keyword

• In Continuation to the Compiler warning of the


previous section …
• Scenario #1
• A method available in base class (Employee) as
public void display()
{
Console.WriteLine("{0}, {1}, {2}",
EmployeeID, FullName, BaseSalary );
}
• This is supposed to be available thru the objects of type
Contractor or Manager
• So, if you have a function in Contractor with similar signature
which prints ID, Name, Basesalary, extra pay, total pay
public void display()
• You are not overriding since this is not virtual in base class
• Hence C# Compiler asks you to add new which is
public new void display()
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
522
Versioning, Shadowing – new keyword

• Scenario #2
• A virtual method available in base class (Employee) as
public virtual void display()
{
//Statements
}
• And you have a function in Contractor with a signature
public void display()
• Compiler warns you to either override or hide display
function
• So, to override
public override void display()
• Or to Hide
public new void display()

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
523
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Versioning, Shadowing – new keyword

• Scenario #2 (Contd)
• Overriding (Polymorphic)
 You can use the base class object reference and invoke display
method
 A proper derived class’s display method is executed as with the
computePay method
 Try this with the following code in the Main after adding the Display
method in derived classes
foreach(Employee e in Employees)
{
e.display();
}
• Hiding (Not Polymorphic)
 You can invoke the display method of derived class only using a
derived class’s object reference
 The code above will invoke only Employee class’s display method
 If we have a collection of Contractor and managers in ArrayList how do
we invoke the display method of the appropriate derived class ???
 See next slide
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
524
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Versioning, Shadowing – new keyword

Change the foreach loop to :


foreach(Employee e in Employees)
{
if (e is Contractor) //Check if object is Contractor
((Contractor)e).display();
else if (e is Manager) //Check if object is Manager
((Manager)e).display();
}

Hiding base implementation using new keyword is


called SHADOWING

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
525
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Versioning, Shadowing – new keyword

What is versioning ?
And another VERSION of a method is provided
which is different from the base class method

• Assume a method by name ExtraMethod is


introduced in a derived class
• And a method with the same name is added to
the base class at a later point of time
• Adding new keyword proactively to the derived
class method will prevent the code from
breaking
• While it is tempting to add new to all the new
methods of the derived class it must be done
judiciously
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
526
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Abstract Methods & Class
• An abstract method does not have a body
Public abstract type method-name(p1, p2…);
• Defining a base class method as abstract forces the
derived classes to override this method
• A new method of the same signature cannot be defined in
the derived class
• So, the derived class must override the method unlike
virtual methods
When a class defines one or more methods as abstract
then the class must be declared abstract
abstract classes cannot be instantiated thus preventing
invocation of a abstract method directly

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
527
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Abstract - Sample
Now the Employee class includes an abstract
method
public abstract decimal computeExtraPay();
And a modified display method
public virtual void display()
{
decimal extra = this.computeExtraPay();
decimal total = BaseSalary + extra;
Console.WriteLine(“Emp:{0}, {1}, {2:C}, {3:C}, {4:C}",
EmployeeID, FullName, BaseSalary, extra, total );
}

There is a change in Contractor Class ( Must


Override the abstract method)
public override decimal computeExtraPay()
{
return this.OverTime * this.Rate;
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
528
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Employee – Complete Source (Minus
Properties)
abstract class Employee
{
protected int EmployeeID;
protected string FullName;
protected decimal BaseSalary;

public Employee(int id, string fullName, decimal baseSalary)


{
this.EmployeeID = id;
this.FullName = fullName;
this.BaseSalary = baseSalary;
}
public virtual decimal computePay()
{
return this.BaseSalary ;
}
public abstract decimal computeExtraPay();
public virtual void display()
{
decimal extra = this.computeExtraPay();
decimal total = BaseSalary + extra;
Console.WriteLine("Emp:{0}, {1}, {2:C}, {3:C}, {4:C}",
EmployeeID, FullName, BaseSalary, extra, total );
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
529
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Contractor – Complete Source
class Contractor : Employee
{
public int OverTime;
public decimal Rate;
public Contractor(int id, string fullName, decimal baseSalary,
int overTime, decimal rate) :
base ( id, fullName, baseSalary)
{
this.OverTime = overTime;
this.Rate = rate;
}
public override decimal computePay()
{
return (this.BaseSalary + this.OverTime * this.Rate);
}
public new void display()
{
Console.WriteLine("{0}, {1}, {2:C}, {3:C}, {4:C}",
EmployeeID, FullName, BaseSalary, OverTime*Rate, computePay() );
}
public override decimal computeExtraPay()
{
return this.OverTime * this.Rate;
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
530
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Main Function and more revelations
foreach(Employee e in Employees)
{
//invoke display of base class
e.display();
//invoke display of derived class (new methods)
if (e is Contractor)
((Contractor)e).display();
}
Both print the same values, How ?
• The base class’s display method hooks the derived class’s
computeExtraPay method
• An abstract function is used for this and is like a contract
• Base class invokes the derived class method to know about
something which only derived class knows
• Display method of base class is called a Template Function and this
pattern of designing is called Template Design Pattern

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
531
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sealed Method
A method marked as sealed cannot be further
overridden in a derived class
sealed modifier must always come along with the
override modifier of a method
Cannot be combined with abstract modifier

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
532
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sealed Classes
This is quite opposite to abstract
That is if you don’t want people inheriting from
your class mark them as sealed
sealed class MyClass
{
//fields, properties and methods
}
Class YourClass : MyClass //Not Allowed
{
}

Sealed classes logically can not contain any


abstract method

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
533
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Multiple inheritance
C# permits inheritance from only one class
Multiple inheritance is not allowed
But could be achieved indirectly with interface
(a.k.a Mixins)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
534
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Structs & Inheritance
Structs cannot be base classes
Structs cannot inherit from other classes

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
535
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Object Behavior
All types are implicitly inherited from Object
The following methods are provided by Object

Equals Evaluates whether 2 objects are equal

GetHashCode Objects can provide their own hash


values and used in Collections
GetType Provide access to the Type object

ToString Provide a String representation of the


object
Finalize Similar to destructor, called by Garbage
Collector
MemberwiseClone Creates copis of the object, Must not be
overridden

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
536
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Overriding Object Methods
Most often the following methods are overridden
in any class
• Equals
• ToString

Kid class revisited :

How to compare 2 kids for equality?


How to print Kid objects like any normal built in
type?

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
537
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Equals
Revisit Kid class created earlier
Kid kid1 = new Kid("Craig", 11);
Kid kid2 = new Kid("Craig", 11);

if (kid1 == kid2)
Console.WriteLine(“Equal”);
else
Console.WriteLine(“Not Equal”);
The above code will print “Not Equal”, though the objects
contain equivalent values
Since Object variable stores only reference to the Object
and these 2 are two distinct object on the heap with
distinct references == operator returns false
Hence to compare objects (reference types ) we need to use
if (kid1.Equals(kid2))

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
538
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Equals …
Add the following method to the Kid class
public override bool Equals(object obj)
{
if (obj is Kid) //Check for type
{
Kid k = (Kid)obj; //Cast type
//Check individual fields
return(this.name.Equals(k.name) && this.age == k.age);
}
return false;
}
Note here that for comparing the name field
which is a string we have used Equals method

Check the method invoking Equals to compare Kid


objects.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
539
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ToString
• PrintKid is the method which is used for
printing the kid object’s value
• It is better to de-couple the print functionality
from the Kid class
• The users of kid class could print it on various
devices
• But formatting information must be provided by
Kid class
• If we try to print any Kid object using

Console.WriteLine("{0}", kid1);
The output is not as you expected, we need to implement
ToString method to make it happen

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
540
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ToString
public override String ToString ()
{
StringBuilder sb = new StringBuilder("Kid ");
sb.Append(this.name);
sb.Append(" is ");
sb.Append(this.age);
sb.Append(" years old.\n");
return sb.ToString(); //Check the use of ToString of sb
}

Now
Console.WriteLine("{0}", kid1); //No need for invoking ToString
In Main will print
Kid Craig is 11 years old.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
541
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Operator Overloading &
Type Conversion

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Operator Overloading
User defined classes can have all the functionality of
built-in types
Operators are static methods whose return value
represents the result of the operation
You can add a functionality to add two complex
numbers by overloading + operator
Mathematical operators are overloaded mostly for
entities modeled after mathematical concepts like
measurements, number systems etc.
For application specific entities the logical operators
come in handy to compare the objects
To compare 2 Kid objects it will be natural to use the
== operator than
Equals method

Let us add the functionality to the Kid class…


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
543
== , != Operator
Let us add this code to Kid class
public static bool operator ==(Kid lhs,Kid rhs)
{
return (lhs.Equals(rhs));
}

public static bool operator !=(Kid lhs, Kid rhs)


{
return(!(lhs == rhs));
}
You cannot overload just == operator, conditional
operators need to be overloaded in logical pairs
This is insisted by C# Compiler, if we leave “!=“
compiler generates an error

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
544
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Cleaning the code
• In our code Operator == method uses the Equals method
internally
• Equals method checks for the object type, this happens
unnecessarily though Operator == method can take only Kid
objects
• So it is better that Equals uses == operator

public override bool Equals(object obj)


{
if (obj is Kid)
{
Kid k = (Kid)obj;
return (this == k);
}
return false;
}
public static bool operator ==(Kid lhs,Kid rhs)
{
return(lhs.name.Equals(rhs.name) && lhs.age == rhs.age);
} ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
545
Exercise
• Create a complex number class with
• ToString
• + Operator
• - Operator

• Check with Operator overloading tutorial in


the .Net SDK Documentation

• For Contractor and Manager classes add


• >, <, >=, <= based on total Salary
• ToString
• Equals

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
546
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Type Conversion
Type conversion (Casting) is also done thru operators
We can implement rules for converting between user
defined types
Assume a struct like this exists
public struct Human
{
public string Name;
public int Age;

public Human(string name, int age)


{
this.Name = name;
this.Age = age;
}
}
We can obviously convert a kid object to Human
variable implicitly

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
547
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Implicit Conversion
Add this method to Kid class
public static implicit operator Human(Kid k)
{
return new Human(k.name, k.age);
}

So we can use this by


Kid kid1 = new Kid("Craig", 11);
Human h = kid1;

Provide an implicit conversion method only when


you are sure of no data loss

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
548
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Explicit conversion
Conversion between types which are not exactly
similar
Converting a Kid object to a String Object must be
forced explicitly
Add this method to Kid class
public static explicit operator string(Kid k)
{
return k.name;
}

If you need to use this :


Kid kid1 = new Kid("Craig", 11);
String s = (string)kid1;

Thus loosing the age value in the target


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
549
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Interface

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to interface
• An interface defines a contract
• A collection of semantically related abstract members
• Classes and structs implementing the interface must
adhere to this contract by implementing ALL the methods
and properties
• Implementing interface is like inheritance
• When a class inherits from another class it shares the
capability
• Since interfaces do not have any capability the
implementing classes share a common responsibility
defined in the contract
• Set of components working together can often be glued
by interfaces
• Another strong point of interface is maintainability
• Using too much of inheritance lead to explosion of
hierarchy and poor maintainability of design and code
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
551
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Interfaces
The .Net SDK is full of contracts which need to be fulfilled
by user defined class types to achieve additional
functionality
• The additional functionalities include but not limited to
• Creating copies of objects (Cloning)
• Comparing types
• Iterating thru lists (Enumeration)

• Let us see some sample interfaces available in .Net SDK


and implement them in our own classes
• Interface take the following form
• (public | internal) interface interface-name :
base-interface-list
{
members;
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
552
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Cloning
Consider this code :
Kid kid1 = new Kid("Craig", 11);
Kid kid2 = kid1; //Shallow Copy
There is only one kid object after this code
executes
Both Kid2 and Kid1 contain the same reference of the
only Kid object
This is called a shallow copy

Cloning is creating another instance of the object.


Done by
interface ICloneable {
Object Clone();
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
553
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Cloning implemented
class Product : ICloneable //Implement interface
{
public readonly int SKU;
public readonly string Name;
public readonly decimal Price;

public Product(int sku, string name, decimal price)


{
this.SKU = sku;
this.Name = name;
this.Price = price;
}
//Implement Clone function
public object Clone()
{
return new Product(this.SKU, this.Name, this.Price);
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
554
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Cloning used
static void Main(string[] args)
{
Product p1 = new Product(100, "Tooth Brush", 12.5M);

Product p2 = (Product)p1.Clone(); //Make a copy

Console.WriteLine("{0}, {1}, {2:C}",


p2.SKU, p2.Name, p2.Price);
if (p1 == p2)
Console.WriteLine("reference equal");
else
Console.WriteLine("reference unequal");
}

Output shows that : Values are equal References are


unequal
Here Clone is invoked using a Product Object P1.
This is called implicit implementation
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
555
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Comparison - Sorting
Sorting built-in types
int[] myIntArray = new int[5] { 5,4,3,2,1 };

Array.Sort(myIntArray);
Sort is a static method of System.Array class

Consider an array of Product objects


Product[] products = new Product[10];
products[0] = new Product(100, "Tooth Brush", 12.5M);
products[1] = …

Can we sort the products array using


Array.Sort(products); ????
Answer is NO! NOT YET!!!
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
556
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Comparison - Sorting
Sorting to work on an array of user defined types
• A contract need to be adhered to in our type
• A Comparator function

The Contract is :
interface IComparable
{
int ComparteTo(object o);
}

• Our type must implement this contract


• Sort method will invoke this CompareTo method by passing an
object to compare to the current object
• We need to provide the logic and return
 -1 if this is less than the object passed
 0 if they are equal
 +1 if this is greater
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
557
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Comparison - Sorting
While implementing IComparable interface you need
to decide which field to sort by
For this example let us sort by SKU which is an
integer
class Product : ICloneable, IComparable
{
//Fields here…
//Constructor
//Clone Method
int IComparable.CompareTo(object obj)
{
Product p = (Product) obj; //Cast obj to Product
if (this.SKU < p.SKU)
return -1;
if (this.SKU > p.SKU)
return 1;
return 0;
}
} ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
558
Bit of Interface theory
We have implemented 2 interfaces and 1 method in each of
them
But there is a subtle difference in the way the functions are
written
When you add the interface name to class definition
class Product : ICloneable, Icomparable
Visual Studio asked you to press <tab> key and added the
empty methods
When you added ICloneable the signature was
public object Clone()
And when you added the IComparable the signature was
public int CompareTo(object obj)
But it was changed in the code to
int IComparable.CompareTo(object obj)
What does it mean?
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
559
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Bit of Interface theory
You can implement a function as public with methodname or
interfacename.methodname without access specifier
In the former the method could be accessed using just the
object reference
• Since you need to invoke clone method on the object
In the later it is not possible since the method is not public
• Sort Method invoke the CompareTo method not using the
Product Object
• Because it does not know what Product object is
• Here the method must be accessed using a reference to the
interface IComparable
This is called Explicit implementation
But note that the comparable could be implemented
implicitly also
Why we have not done that is anybody who is holding a
reference to Product object should not access the method
just like that!
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
560
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
CompareTo - rewritten
You might have noticed the logic of the CompareTo function
according to the rules (return –1, +1, 0 on conditions)
But there is a real smart way of doing this

Consider for a moment how the sorting of an integer array


works?
Because int type has already implemented the IComparable!
Yes ! Structs can implement interfaces
So, why don’t we make use of the CompareTo method of int ?
Here is how the smart code looks :
int IComparable.CompareTo(object obj)
{
Product p = (Product) obj;
return(this.SKU.CompareTo(p.SKU));
}
This was possible for us because int has implemented the

IComparable interface implicitly ! 


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
561
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
IComparable - Used
Enough of theory!
static void Main(string[] args)
{
Product[] prods = new Product[5];
//Initialize product array, create products
prods[0] = new Product(104, "Washing Soap", 62.0M);
prods[1] = new Product(101, "Shower Gel", 90.0M);
prods[2] = new Product(102, "Tooth Paste", 20.0M);
prods[3] = new Product(103, "Toilet Soap", 15.6M);
prods[4] = new Product(100, "Tooth Brush", 12.5M);

Array.Sort(prods);

for(int i =0; i < prods.Length; i++)


{
Product p = prods[i];
Console.WriteLine("{0}, {1}, {2:C}",
p.SKU, p.Name, p.Price);
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
562
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Interface theory - Casting
How do we invoke the explicitly implemented method of an
interface if we only have an object?
Assume you want to compare prods[0] and prods[1]
yourself :
Product p0 = prods[0];
IComparable ic = (IComparable) p0;
int val = ic.CompareTo(prods[1]);
Console.WriteLine("Val is : {0}", val);
Here you are having the p0 object yourself,
But if somebody else passes an object to you and you need
to invoke a interface member on it
Then type casting to the interface may result in runtime
error!
So, you can check before casting using is operator
if (p0 is IComparable)
{
//Cast and use
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
563
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Interface theory – Casting…
But a much more efficient method is to cast using
as Operator :
Product p0 = prods[0];
IComparable ic = p0 as IComparable;
if (ic != null)
{
int val = ic.CompareTo(prods[1]);
Console.WriteLine("Val is : {0}", val);
}

as operator casts to the interface


and
if the object does not implement the interface it
returns null

as operator is efficient than is operator


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
564
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Implementing multiple interfaces
It is better to implement explicitly if two or more
interfaces contain exactly similar method(s)

interface Walkable {
void move(int pos);
}
interface Swimmable {
void move(int pos);
}
Class Human : walkable, Swimmable
{
Walkable.move(int pos) //Explicit implementation makes it possible
{
}
Swimmable.move(int pos) //Explicit implementation makes it possible
{
}


}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
565
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Enumeration
To iterate over custom collection classes
There are 2 interfaces involved
• IEnumerable
• IEnumerator GetEnumerator()

• IEnumerator
• void Reset()
• object Current {get;} //Property
• bool MoveNext()

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
566
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Product Collection class – Step 1
public class ProductCollection : IEnumerable, IEnumerator
{
private Product[] products;

public ProductCollection()
{
products = new Product[5];
products[0] = new Product(104, "Washing Soap", 62.0M);
products[1] = new Product(101, "Shower Gel", 90.0M);
products[2] = new Product(102, "Tooth Paste", 20.0M);
products[3] = new Product(103, "Toilet Soap", 15.6M);
products[4] = new Product(100, "Tooth Brush", 12.5M);
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
567
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
IEnumerable, IEnumerator – Step 2
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerator)this);
}

private int pos = -1; //State variable counter for Looping

void IEnumerator.Reset()
{
pos = -1;
}
object IEnumerator.Current
{
get { return products[pos]; }
}
bool IEnumerator.MoveNext()
{
pos++;
if (pos == products.Length) return false;
return true;
}
} //End Product Collection Class

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
568
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Using – Step 3
ProductCollection pc = new ProductCollection();

foreach (Product p in pc)


{
Console.WriteLine("Collections - > {0}, {1}, {2:C}",
p.SKU, p.Name, p.Price);
}
This implementation works fine but has a few drawbacks
Try adding another For Each loop below the first one , The
products wont get printed for the second time.
For each does not invoke Reset. We need to call reset in the
GetEnumerator method.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
569
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Collection in a better way
Instead of containing an Array contain an ArrayList
Advantages
• Can provide add, remove functions with strong typing
• Pre built Enumerators

class ProductList : IEnumerable


{
private ArrayList products;
public ProductList()
{
products = new ArrayList();
}
public int Add(Product p) //Manage Collection operations
{
return products.Add(p);
}
public IEnumerator GetEnumerator()
{
return products.GetEnumerator();
}
} ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
570
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Using List based Collection
ProductList pl = new ProductList();
pl.Add(new Product(104, "Washing Soap", 62.0M));
pl.Add(new Product(101, "Shower Gel", 90.0M));
pl.Add(new Product(102, "Tooth Paste", 20.0M));
pl.Add(new Product(103, "Toilet Soap", 15.6M));
pl.Add(new Product(100, "Tooth Brush", 12.5M));

foreach (Product p in pl)


{
Console.WriteLine("List - > {0}, {1}, {2:C}",
p.SKU, p.Name, p.Price);
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
571
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Indexers

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Indexers
Allow us to make classes look like virtual arrays
Appropriate to add this capability to collection classes

ArrayList is a collection class not a fixed size Array


While adding to the ArrayList is done by add() method
• Accessing elements sequentially are done by Enumerators
• Accessing at random facilitated by Indexers
Consider the ProductList class of previous sample the 3rd
product in the list could be accessed using
Pl[3]
How do we add this capability to the ProductList ?

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
573
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Indexer - Sample
Indexer is like a property the signature is
public type this[int index-var]
{
get { }
set { }
}
For the ProductList class we should not provide a
set method. Why?
And we need to provide a Length property also.
Why?

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
574
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Indexer - Sample
Indexer is like a property the signature is
public Product this[int index]
{
get
{
return (Product)products[index];
}
}
//Provide a Length property to prevent index going out of bounds
public int Length
{
get
{
return products.Count;
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
575
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Indexer - Exercise
Create a class which accepts an English sentence
where words are separated by space or comma
or full stop
Provide an indexer to access and set the
individual words.
Constructor of the class looks like this :
public Words( string sentence)
{
char[] delim = {' ', '.', ','};
words = sentence.Split(delim);
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
576
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Nested Classes

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sorting using different fields
An overload of Array.Sort is available for this purpose
Array.Sort(arr, Comparer)
The second parameter Comparer is an Object which
implements IComparer Interface
int IComparer.Compare(object x, object y)
Each Implementation of this method must compare using a
specific field
• The problem is we cannot implement any interface more
than once in a class
• The trivial solution suggests that This interface could be
implemented in 3 different classes(Anyway both the
objects for Comparison are passed as parameters)
• But we are increasing the number of Public classes
available which is also a potential problem. For Product
class we need need 3 more classes for implementing
Compare on each field
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
578
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Problems with IEnumerator
What if 2 concurrently executing foreach loops want access
to the same ProductCollection class?
The output will jump and items will be skipped by the two
loops, since they share the index variable pos and the
object
This situation is more common in a web application
environment
The solution is to provide a new Enumerator object each
time GetEnumerator is called
The IEnumerator must be implemented on a different class
and an object of this class must be created and returned
by the GetEnumerator, pos variable must be in this new
class
But how do we make the Products array available to this
class?

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
579
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Nested Classes
• A Class defined with in another class
• An Inner class can
• Access the outer class’s static members with or without specifying
the outer class name as qualifier
• Cannot access instance members of outer class unless a reference
is passed to the inner class
• When a reference is known then it can access all instance
members including Private members
• An outer class can
• Access the inner class’s static member by qualifying the member
with the inner class name
• Cannot access the instance members unless a reference is created
• An Inner class could be created with any member access
modifier
• Thos who have access to inner class can access the static
members of inner class
• Instance members of inner class can be accessed only when an
instance of inner is available with outer and is accessible
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
580
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Comparers
We are going to create 3 inner classes inside the
Product class Implementing IComparer
private class SKUComparer : IComparer
{
public int Compare(object x, object y)
{
return ((Product)x).SKU.CompareTo(((Product)y).SKU);
}
}

The inner class is private because nobody in the


outside world needs to know about this class
The instance of SKUComparare is independent of
the outer product class (Not accessing any of
the outer’s instance members)
Then how do people get an instance of this?
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
581
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Comparers
People of the outside world can get an object of
SKUComparer (the only one) thru a Static member of the
Product class
Add this line to the product below the inner
class(SKUComparer )
public static IComparer SKUCOMPARER = new SKUComparer();
Public : Client should be able to access this instance
Static : One instance is enough (Nothing to do with
outer class instance variables)
Type IComparer : Need not expose this as type
SKUComparer since it is Private. Or this is why we made
it as private?
• Can we expose this as a SKUComparer Type? Why?

Add Other 2 inner classes and static members. Sort by any


of the 3 fields and check the output.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
582
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Comparer - Solution
private class NAMEComparer : IComparer
{
public int Compare(object x, object y)
{
return ((Product)x).Name.CompareTo(((Product)y).Name);
}
}
private class PRICEComparer : IComparer
{
public int Compare(object x, object y)
{
return ((Product)x).Price.CompareTo(((Product)y).Price);
}
}
public static IComparer SKUCOMPARER = new SKUComparer();
public static IComparer NAMECOMPARER = new NAMEComparer();
public static IComparer PRICECOMPARER = new PRICEComparer();

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
583
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Comparer - Solution
Product[] prods = new Product[5];
prods[0] = new Product(104, "Washing Soap", 62.0M);
prods[1] = new Product(101, "Shower Gel", 90.0M);
prods[2] = new Product(102, "Tooth Paste", 20.0M);
prods[3] = new Product(103, "Toilet Soap", 15.6M);
prods[4] = new Product(100, "Tooth Brush", 12.5M);

Array.Sort(prods, Product.PRICECOMPARER);
//Print the sorted Array
for(int i =0; i < prods.Length; i++) //Print the sorted Array
{
Product p = prods[i];
Console.WriteLine("{0}, {1}, {2:C}", p.SKU, p.Name, p.Price);
}
Array.Sort(prods, Product.NAMECOMPARER );
//Print the sorted Array
Array.Sort(prods, Product.SKUCOMPARER );
//Print the sorted Array

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
584
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Enumerator
You got it!
IEnumerator must be implemented as an inner
class
Let us create an inner class by name
ProductEnumerator inside ProductCollection
class
Now the Enumerator class needs access to the
outer class’s instance member products Array
To enable this a reference of the outer class
instance is passed to the constructor of inner
class
And thru this reference the Enumerator inner
class accesses the private member of the outer
class
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
585
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Enumerator- Solution
private class ProductEnumerator : IEnumerator
{
private ProductCollection items;
private int pos;
public ProductEnumerator(ProductCollection items)
{
pos = -1;
this.items = items; //get outerclass ref thru constructor param
}
void IEnumerator.Reset() { pos = -1; }
object Ienumerator.Current //Access the outerclass private member
{
get { return items.products[pos]; }
}
bool Ienumerator.MoveNext()
{
pos++;
if (pos == items.products.Length) return false;
return true;
}
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
586
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Enumerator- Solution
Now the outer class ProductCollection implements only
IEnumerable
public class ProductCollection : IEnumerable
{
private Product[] products;
//Constructor
//Inner Class
IEnumerator IEnumerable.GetEnumerator()
{
//Pass a reference of self
//so that the inner class can access the array
ProductEnumerator pe = new ProductEnumerator(this);
return((IEnumerator) pe);
}
}
The Main Method
ProductCollection pc = new ProductCollection();
foreach (Product p in pc)
{
Console.WriteLine("Collections1 - > {0}, {1}, {2:C}",
p.SKU, p.Name, p.Price);
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
587
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
UML For Beginners

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Course Objectives
Ensure that trainees can
• Understand basic UML concepts
• Interpret requirements given in UML notation
• Prepare design artifacts using UML notation

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
589
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Target Audience
• Software Engineer Trainees
• SEs/SSEs looking for a basic understanding of
UML

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
590
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Prerequisites for the Course
• Understanding of OOPs and basic coding skills

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
591
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Session Plan
• What is UML?
• Where can UML be used?
• Types of UML diagrams/artifacts
• Use Cases & Use Case Diagrams
• Class Diagrams
• Sequence Diagrams
• Package Diagrams
• Deployment Diagrams
• Q/A Session

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
592
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
What is not covered
• Not a full fledged UML course
• Advanced concepts in most diagrams are not
covered

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
593
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
What is UML?
• Born out of the unification of the many object-
oriented graphical modeling languages
• Open standard, controlled by the Object
Management Group (OMG)
• Family of graphical notations
• Single meta-model
• Helps in describing and designing software
systems
• Common language for communicating design
concepts among software
developers/designers

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
594
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Where is UML Used?

How people
interact with
Conceptual the
perspective -A
•Use Case Diagram system.
Canway
good show the
•Use Case Diagram
•Class diagram of context
building
Can be for
up use cases
a rigorous
useful and alsohas
if a concept
Requirements •Class diagram Used to explain complex
•Activity Diagram theandetails
vocabulary ofofthe
interestinghow a cycle, use
domain.
life
Analysis •Activity Diagram cases
•State Diagram complicated
with various usestates
case works.
and events
•State Diagram
•Sequence Diagram that change that state.
•Sequence Diagram

Show the classes in the


software
To andwhat
figure out how happens
they in
•Class Diagram interrelate
Show the large-scale
the software for the use case
•Class Diagram For classesof
with
•Sequence diagram organization
scenarios thecomplex
softwarelife
•Sequence diagram Show the
histories. physical layout of
Design •Package Diagram
•Package Diagram the software
•State Diagram
•State Diagram
•Deployment Diagram
•Deployment Diagram

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
595
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Types of UML Diagrams and Artifacts

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
596
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Purpose of the Diagrams

Diagram Purpose
Activity Procedural & Parallel Behavioral
Class Class, Features & Relationships
Communication Interactions between objects; emphasis on Links
Component Structure and Connections of Components
Composite Structure Runtime Composition of a new class
Deployment Deployment of artifacts to nodes
Interaction Overview Mix of sequence and Activity Diagram
Object Example configurations of instances
Package Compile Time Hierarchy of Structure
Sequence Interactions between objects; emphasis on Sequences
State Machine How events change an object over its life
Timing Interactions between objects; Emphasis on timing
Use Case How users interact with a system

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
597
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Use Cases
• Describe the typical interactions between the users of
a system [actors] and the system itself
• Provide a narrative of how a system is used
• Capture the functional requirements of a system
using scenarios
• Use case - set of scenarios tied together by a
common user goal
• Scenario - sequence of steps describing an
interaction between a user and a system. Eg: Buy a
Product in a Web-based on-line store
• An actor is a role that a user plays with respect to
the system

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
598
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Use Cases – Contents of a Use Case

• Pick the main


success scenario
• Break main success
scenario as a
sequence of
numbered steps
• Note down
extensions
• Extensions can be
successes— as in
3a—or failures, as
in 6a

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
599
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Use Cases – Contents of a Use Case ...

• Primary actor
• Secondary actors
• Each step in a use case is an element of the interaction
between an actor and the system
• A complicated step in a use case can be another use case
i.e. the first use case includes the second
Thus in the previous figure, the first step includes the use case
"browse catalog and select items to buy"
• Additional information
- A pre-condition
- A guarantee [Success guarantees and minimal
guarantees]
- A trigger

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
600
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Use Cases – Use Case Diagrams

• The use case diagram


shows the actors, the
use cases, and the
relationships between
them:
1) Which actors carry out
which use cases
2) Which use cases include
other use cases

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
601
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Use Cases – Tips
• Use cases represent an external view of the system
• Do not expect any correlations between use cases
and the classes inside the system
• Each step in the use case should be a simple
statement
• The step should show the intent of the actor, not the
mechanics
• Do not describe the user interface in the use case
• Brainstorm all the extension conditions first, before
working out the consequences

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
602
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Class Diagrams
• Describes the types of objects in the system and the
various kinds of static relationships that exist among
them
• Shows the properties and operations of a class
• Mentions constraints that apply to the way objects
are connected
• Associations and generalizations

The slide below has a simple example of a class


diagram for order processing

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
603
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Class Diagrams

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
604
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Class Diagrams ...
• Classes are represented by rectangles
• A class icon can be subdivided into compartments
• The top compartment is for the name of the class
• The second is for the variables of the class
[properties]
• The third is for the methods [operations] of the class

• Properties – An attribute of the class


• Operations – Actions a class performs on its data

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
605
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Constituents of Class Diagram -
Operations
Operations are the actions that a class knows to carry out.

The full UML syntax for operations is:


visibility name (parameter-list) : return-type {property-string}

• This visibility marker is public (+) or private (-);


• The parameter-list is the list of parameters for the operation
• The return-type is the type of the returned value, if there is one
• The property-string indicates property values that apply to the given
operation

The parameters in the parameter list are notated in a similar way to


attributes.
The form is:
direction name: type = default value
• The name, type, and default value are the same as for attributes
• The direction indicates whether input (in), output (out) or both (inout).
Default is (in)

An example operation on account might be:


+ balanceOn (date: Date) : Money

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
606
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Constituents of Class Diagram - Properties

appear in two quite distinct notations: attributes


Properties
and associations

Attributes
A line of text within the class box

The full form of an attribute is:


visibility name: type multiplicity = default {property-string}

• This visibility marker is public (+) or private (-);


• The property-string indicates property values that apply to the given
operation

An example of this is:


- name: String [1] = "Untitled" {readOnly}

Only the name is mandatory.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
607
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Constituents of Class Diagram - Association
• Association –
 Is a solid line between two classes

 Directed from the source class to the target class.

 The name of the property goes at the target end of the association,
together with its multiplicity.

Association can be Uni directional/Bi Directional.

• Uni Directional Association -> Ex:

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
608
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Constituents of Class Diagram – Association …

• Bi Directional Association ->


A pair of properties that are linked together as inverses.

Ex: The Car class has property owner:Person[1], and the


Person class has a property cars:Car[*].

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
609
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Constituents of Class Diagram - Multiplicity
More on Multiplicity
 Optional implies a lower bound of 0.
 Mandatory implies a lower bound of 1 or possibly more.
 Single-valued implies an upper bound of 1.
 Multivalued implies an upper bound of more than 1: usually *. If
an attribute is multi valued, this implies that
the data concerned is a collection.

Examples:
Mandatory/Multi valued Association
• Digit -The exact number of elements.
• 1..* - One to many.
• 3..5 - Three to five.
Optional/Multi Valued Association
• * or 0..* - Zero to many.
Mandatory/Single Valued
• 1 – One
Optional/Single Valued
• 0..1 – Zero or One

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
610
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Constituents of Class Diagram – Aggregation & …

• Aggregation is the
‘whole/part-of’ relationship
• Cannot have cyclic
relationships i.e. part cannot
contain its whole

Composition:
• Same as aggregation,
except that ‘whole’ takes
control of
creating/destroying ‘part’
• The "no sharing" rule is the
key to composition
• When composite is
destroyed, it must destroy
all its parts

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
611
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Constituents of Class Diagram – Aggregation & …

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
612
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Constituents of Class Diagram - Generalization

A relationship where the generalized behavior is


segregated into
a parent class.
Ex:

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
613
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Class Diagrams - Dependencies
•Changes to the Keyword Meaning
definition of one «call» The source calls an operation in the target.
element (the supplier) «create» The source creates instances of the target.
may cause changes to «derive» The source is derived from the target.
the other (the client) «instantiate» The source is an instance of the target. (Note that
if the source is
a class, the class itself is an instance of the class
class; that is, the target class is a metaclass).

«permit» The target allows the source to access the target's


private features.
«realize» The source is an implementation of a specification
or interface defined by the target
«use» The source requires the target for its
implementation. The general rule should be to
minimize dependencies, particularly when they
cross large areas of a system.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
614
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Class Diagrams – Tips
The trouble with class diagrams is that they are
so rich; they can be overwhelming to use. Here
are a few tips.
• Start with the simple stuff. Introduce other notations
only when you NEED them
• Don't draw models for everything; instead,
concentrate on the key areas
• Use notes and comments to make your intent clear.
See example below

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
615
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sequence Diagrams

• Typically captures the behavior of a single scenario


• Shows a number of objects and the messages that
are passed between these objects within the use
case
• Each participant has a lifeline that runs vertically
down the page
• Displays the interaction using lifelines and the
ordering of messages by reading down the page

Consider a simple order-processing scenario.


The next slide has a sequence diagram that shows one
implementation of this scenario.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
616
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sequence Diagrams ...
An instance of order
sends getQuantity and
getProduct messages
to the order line.

The order invokes a


method on itself and
that method sends
getDiscountInfo to an
instance of customer.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
617
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sequence Diagrams ...
Another possible
approach to this
scenario is given.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
618
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sequence Diagrams – Life of a participant

• Activation bar shows


when the participant is
active in the
interaction
• Deletion of a
participant is indicated
by big X
• An X at the end of a
lifeline
shows a participant
deleting itself

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
619
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sequence Diagrams – Loops & Conditionals

The image to the left implements


the following pseudo code:

procedure dispatch
foreach (lineitem)
if (product.value > $10K)
careful.dispatch
else
regular.dispatch
end if
end for

if (needsConfirmation)
messenger.confirm
end procedure

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
620
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sequence Diagrams – Loops & Conditionals

Loop Meaning
Operator
alt Alternative multiple fragments; only the one
whose condition is true will execute
opt Optional; the fragment executes only if the
supplied condition is true. Equivalent to an alt
with only one trace
par Parallel; each fragment is run in parallel.
region Critical region; the fragment can have only
one thread executing it at once.
loop Loop; the fragment may execute multiple
times, and the guard
indicates the basis of iteration

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
621
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sequence Diagrams – Tips
• Use sequence diagrams when you want to look
at (or explain) the behavior of several objects
within a single use case
• Sequence diagrams are good at showing
communication among the objects
• Not so good at precise definition of the
behavior
• Instead of creating sequence diagrams for all
cases, use them to elucidate only the more
complex cases/scenarios

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
622
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Package Diagrams
• A package is a grouping construct that allows
you to take any construct in the UML and group
its elements together into higher-level units
• Each class is a member of a single package
• Packages can also be members of other
packages forming a hierarchic structure
• A package can contain both subpackages and
classes
• Packages correspond to such grouping
constructs as packages (in Java) and
namespaces (in C++ and .NET)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
623
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Package Diagrams ...
• Each package
Different ways to represent Packages represents a namespace
• Every class must have a
unique name within its
owning package
• Use a fully qualified
name that shows the
owning package
structure
E.g. System::Date
and
MartinFowler::Util::Date

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
624
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Package Diagrams - Dependencies

•A package diagram shows


packages and their dependencies
•Interpackage dependencies
summarize the dependencies
between their contents

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
625
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Package Diagrams – Implementing Packages

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
626
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Package Diagrams – When to use
• Extremely useful on larger-scale systems to
understand dependencies between major
elements of a system
• Correspond well to common programming
structures
• Plotting diagrams of packages and
dependencies helps keep an application's
dependencies under control
• Represent a compile-time grouping
mechanism

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
627
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Deployment Diagrams

Deployment
diagrams show a
system's physical
layout, revealing
which pieces of
software run on
what pieces of
hardware.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
628
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Deployment Diagrams
• The main items on the diagram are nodes
connected by communication paths
• A node is something that can host some software
• Nodes come in two forms. A device is hardware, it
may be a computer or a simpler piece of hardware
connected to a system
• An execution environment is software that itself
hosts or contains other software, examples are an
operating system or a container process

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
629
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Deployment diagrams - When to use
• Deployment diagrams are very handy in
showing what is deployed where
• Useful in understanding the enterprise
architecture and design philosophies

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
630
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thank You

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generics

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generics
Generics are a new feature in version 2.0 of the C# language and the
common language runtime (CLR). Generics introduce to the .NET
Framework the concept of type parameters, which make it possible to
design classes and methods that defer the specification of one or more
types until the class or method is declared and instantiated by client code.

The First Best thing you come to notice while using Generics is that it helps
you avoid run time exceptions which happens because of wrong casting.

Generic classes encapsulate operations that are not specific to a particular


data type. The most common use for generic classes is with collections like
linked lists, hash tables, stacks, queues, trees and so on where operations
such as adding and removing items from the collection are performed in
much the same way regardless of the type of data being stored.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
633
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generics are new in Version 2.0
Through Generics we can create classes which work on classes
You don’t have to give the types of the classes when you write the code
Instead you use placeholders which are “filled in” at runtime in a type safe
manner

Why generics?
• Compile-time type checking
• Performance (no boxing, no downcasts)
• Reduced code bloat (typed collections)

C# generics vs. C++ templates

• C# generics are checked at declaration


• C# generics are instantiated at run-time

C# generics vs. proposed Java generics

• C# generics work over entire type system


• C# generics preserve types at run-time

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
634
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Avoiding run time exceptions using Generics

Lets now take the kid class and work out this assertion.

using System;
using System.Text;
using System.Collections;

namespace TestKid
{
class Kid
{
ArrayList kids;
Kid(string name,int age)
{
kids= new ArrayList();
kids.Add(name);
kids.Add(age);
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
635
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Avoiding run time exceptions using Generics
public void PrintKid()
{
foreach (string k in kids)
{ The Program compiles
Console.WriteLine(k); with no Error but at
} runtime it throws an
invalid cast exception.
}
static void Main(string[]
args)
{
Kid myKid = new Kid(“Roy", 9);
myKid.PrintKid();
}
}
}

It would be better if you can spot these errors at compile time itself.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
636
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generic List
Now lets do this with a Generic List..
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace TestKid
{
class Kid
{
List<string>kids;
Kid(string name,int age)
{
kids = new List<string>();
kids.Add(name);
kids.Add(age);
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
637
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generic List
public void PrintKid()
{
foreach (string k in kids)
{ Now this code generates
Console.WriteLine(k); an error and warns you
} before u go to runtime.

static void Main(string[] args)


{
Kid myKid = new Kid("Ruby", 9);
myKid.PrintKid();
}
}
} What’s More…

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
638
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generics

Using an Arraylist with our Kid class was convenient but this convenience comes at
a cost. Any reference or value type that is added to an ArrayList is implicitly upcast
to Object. If the items are value types, they must be boxed when added to the list,
and unboxed when they are retrieved. Both the casting and the boxing and
unboxing operations degrade performance
Hence it is better to implement the kid code like this

List<string> list1 = new List<string>(); //Noboxing,No


casting:
list1.Add(“Ruby”);
list1.Add(9); // Compile-time error:

For client code, the only added syntax with List<T> compared to ArrayList is
the type argument in the declaration and instantiation. In return for this slightly
greater coding complexity, you can create a list that is not only safer than
ArrayList, but also significantly faster, especially when the list items are value
types.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
639
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
How are C# generics implemented?

• Instantiated at run-time, not compile-time

• Checked at declaration, not instantiation

• Work for both reference and value types

• Exact run-time type information

Generics increases the performance of your code by eliminating Boxing and


UnBoxing.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
640
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generics
Now lets create a method called AddKids to add more Kid objects to the Kid
class.
public class Kid
{
private object[] KidObj=new object[5];
private int count;

public void AddKids(object K) {


KidObj[count++] = K;
}

public int Count {


get { return count; }
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
641
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generics

public class Kid


{
private object[] KidObj;
private int count;

public void AddKids(object K) {


KidObj[count++] = K;
}

public int Count {


get { return count; }
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
642
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generics

class KidMain
{
public static void Main()
{
intList.Add(1); // Argument is boxed
Kid mykid=new Kid(); intList.Add(2); // Argument is boxed
mykid.AddKids(1); intList.Add("Three");
mykid.AddKids(2);
mykid.AddKids("Three");

}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
643
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Now using Generic Type

public class Kid<ItemType>


{
private ItemType[] KidObj=new ItemType[5];
private int count;

public void AddKids(ItemType K) {


KidObj[count++] = K;
}

public int Count {


get { return count; }
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
644
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Now using Generic Type

class KidMain
{
public static void Main()
{
Kid<int> mykid = new Kid<int>();
intList.Add(1); // No boxing
mykid.AddKids(1);
intList.Add(2); // No boxing
mykid.AddKids(2); intList.Add("Three"); // Compile time error
mykid.AddKids("Three");

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
645
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generic Type Parameters
In a generic type or method definition, a type parameters is a placeholder for a
specific type that a client specifies when they instantiate a variable of the generic
type.

A generic class, such as GenericList<T> cannot be used as-is because it is not


really a type; it is more like a blueprint for a type.

To use GenericList<T>, client code must declare and instantiate a constructed type
by specifying a type argument inside the angle brackets.

The type argument for this particular class can be any type recognized by the
compiler.

GenericList<float> list1 = new GenericList<float>();


GenericList<ExampleClass> list2 = new
GenericList<ExampleClass>(); GenericList<ExampleStruct>
list3 = new GenericList<ExampleStruct>();

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
646
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generic Type Parameters
Type parameters can be applied to
• Class, struct, interface, and delegate types

class Dictionary<KeyType, ValueType> {...}

struct Pair<FirstType, SecondType> {...}

interface IComparer<T> {...}

delegate ResType Func<ArgType, ResType>(ArgType arg);

Dictionary<string, Customer> customerLookupTable;

Dictionary<string, List<Order>> orderLookupTable;

Dictionary<int, string> numberSpellings;

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
647
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generics
Type parameters can be applied to
• Class, struct, interface, and delegate types
• Methods

class Array
{
public static T[] Create<T>(int size) {
return new T[size];
}

public static void Sort<T>(T[] array) {


...
}
}

string[] names = Array.Create<string>(3);


names[0] = “Roy";
names[1] = “Rennit";
names[2] = “Allam";
Array.Sort(names);
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
648
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Inheritance with generics
For a generic class Node<T>, derived code can reference the class either by
specifying a type argument, to create a closed constructed type (Node<int>), or it
can leave the type parameter unspecified, for example when specifying a generic
base class, to create an open constructed type (Node<T>). Generic classes can
inherit from concrete, closed constructed, or open constructed base classes:

class BaseNode { }
class BaseNodeGeneric<T> { }
// concrete type
class NodeConcrete<T> : BaseNode { }
//closed constructed type
class NodeClosed<T> : BaseNodeGeneric<int> { }
//open constructed type
class NodeOpen<T> : BaseNodeGeneric<T> { }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
649
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Inheritance with generics
Non-generic — concrete — classes can inherit from closed constructed base
classes, but not from open constructed classes or naked type parameters
because there is no way at run time for client code to supply the type argument
required to instantiate the base class.

//No error
class Node1 : BaseNodeGeneric<int>
{
}
//Generates an error
class Node2 : BaseNodeGeneric<T>
{
}
//Generates an error
class Node3 : T
{
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
650
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Inheritance with generics
Generic classes that inherit from open constructed types must supply type
arguments for any base class type parameters that are not shared by the
inheriting class, as demonstrated in the following code:
class BaseNodeMultiple<T, U>
{
}
//No error
class Node4<T> : BaseNodeMultiple<T, int>
{
}
//No error
class Node5<T, U> : BaseNodeMultiple<T, U>
{
}
//Generates an error
class Node6<T> : BaseNodeMultiple<T, U>
{}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
651
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Inheritance with generics

Generic classes that inherit from open constructed types must specify
constraints that are a superset of, or imply, the constraints on the base type.

class NodeItem<T> where T : System.IComparable<T>, new() { } class


SpecialNodeItem<T> : NodeItem<T> where T : System.IComparable<T>,
new() { }

Generic types can use multiple type parameters and constraints.

class SuperKeyType<K, V, U> where U : System.IComparable<U> where


V : new() { }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
652
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Open constructed and closed constructed types can be used as method
parameters:

void Swap<T>(List<T> list1, List<T> list2) //code to swap


items
{ }
void Swap(List<int> list1, List<int> list2) //code to swap
items
{
}

Remember : Generic classes are invariant.

List<BaseClass>, // compile-time error


List<DerivedClass>.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
653
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Use of Default Keyword in Generic Code

In generic classes and methods, one issue that arises is how to assign a
default value to a parameterized type T when you do not know the
following in advance:

1. Whether T will be a reference type or a value type.


2. If T is a value type, whether it will be a numeric value or a struct.

For this we can use the Default Keyword

The default keyword, which will return null for reference types and zero for
numeric value types. For structs, it will return each member of the struct
initialized to zero or null depending on whether they are value or reference
types.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
654
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Use of Default Keyword in Generic Code
public class GenericList<T>
{
private class Node
{
public Node Next;
public T Data;
}
private Node head;
public T GetNext() {
T temp = default(T);
Node current = head;
if (current != null) { temp = current.Data; current =
current.Next; }
return temp;
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
} }
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
655
Generic Collections
The major advantage that generics brings for
learner programmers is a better way to deploy
collection classes
They remove the need to cast items read from the
collection

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
656
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generic Collections

public class Kid<ItemType>


{
public class Kid<T>
{ private ItemType[] KidObj=new T[5];
private
private T[] KidObj=new T[5];
int count;
private int count;
public void AddKids(ItemType K) {
public void AddKids(T K) {
ifKidObj[count++]
(count == KidObj.Length)
= K;Resize(count * 2);
KidObj[count++]
} = K;
}
public int Count {
public intget
Count{{ return count; }
} { return count; }
get
}}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
657
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generic Collections
intList.Add(1); // No boxing
public class KidCollection intList.Add(2); // No boxing
{ intList.Add("Three");
public static void Main() // Compile time error
{
Kid<int> myKid = new Kid<int>();

myKid.AddKids(1);
myKid.AddKids(2);
myKid.AddKids("Three");

System.Console.WriteLine(myKid.Count);
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
658
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generic Collections List<T>
Dictionary<K,V>
SortedDictionary<K,V>
Stack<T>
Collection classes Queue<T>

IList<T>
Collection interfaces IDictionary<K,V>
ICollection<T>
IEnumerable<T>
Collection base classes IEnumerator<T>
IComparable<T>
IComparer<T>
Utility classes
Collection<T>
KeyedCollection<T>
Reflection ReadOnlyCollection<T>

Nullable<T>
EventHandler<T>
Comparer<T>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
659
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Example (Generic List for Kid Class)
public class Kid
{
protected string name;
protected int age;
public string Name
{
get
{ return name; }
set { name = value; }
}
public int Age {
get { return age; }
set { age = value; }
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
660
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Example (Generic List for Kid Class)
public class MainClass
{
public static void Main(string[] args)
{
List<Kid> objList = new List<Kid>();

Kid objKid = new Kid();


objKid.Name = "Rennit";
objKid.Age = 22;
Kid objKid2 = new Kid();
objKid2.Name = "Pcube";
objKid2.Age = 23;
objList.Add(objKid);
objList.Add(objKid2);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
661
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Example (Generic List for Kid Class)
foreach (Kid user in objList)
{

System.Console.WriteLine(System.String.Format("{0}:{1}",
user.Name, user.Age));
}
System.Console.WriteLine("press enter");
System.Console.ReadLine();
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
662
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generics best practices.

1. Create a generic classes by starting with an existing concrete class, and


changing types into type parameters one at a time until you reach the optimal
balance of generalization and usability.
2. As a general rule, the more types you are able to parameterize, the more
flexible and reusable your code becomes. However, too much generalization
can result in code that is difficult for other developers to read or understand.
3. A good rule is to apply the maximum constraints possible that will still let you
handle the types you need to handle. For example, if you know that your
generic class is intended for use only with reference types, then apply the class
constraint. That will prevent unintended use of your class with value types, and
will enable you to use the as operator on T, and check for null values.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
663
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generics best practices.
4. Since generic classes can serve as base classes, the same design
considerations apply here as with non-generic classes.
5. if you are designing a class that will be used to create items in a
generics-based collection, you may need to implement an interface
such as IComparable<T> where T is the type of your class.
6. With generic classes it is preferable to use generic interfaces, such as
IComparable<T> rather than IComparable, in order to avoid boxing
and unboxing operations on value types.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
664
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Callbacks

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Callbacks
What is a callback?
You call a method of a class and that method invokes
• Methods on the other class ( No big deal! )
• Methods of your class ( Probably I have written both the classes and
they know each other by name! )
• Methods of a class which will be written at a future date ( That
sounds interesting! )
Items 1 & 2 are nothing but 2 classes written about the
same time and the class names are hard coded in each
other or strongly coupled
Imagine how you invoked Sort method Array class
( provided by .net) and sort method invoked your
CompareTo method on the product class!
Here the programmer who wrote the array class would
not have had the slightest clue that a developer in
India is going to use this method to sort an array of
Products
Yes! It was possible because of interfaces! And it is
possible if we use abstract classes too!
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
666
Callbacks
These interfaces / or abstract classes which are
published by a contract maker and whoever
wants to get called they implement the
interface or derive from that abstract class
Using interface is better than inheriting an
abstract class for achieving a callback
functionality because
• With interfaces you can derive from another appropriate
class of your domain
• While inheriting from a contract class you lose that
opportunity
Think for a while how weird it will be when
• You want to add the CompareTo method to Contractor class
to sort on Rate
• And CompareTo method is defined in an abstract class by
name Comparable instead of an interface IComparable!
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
667
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Callbacks
So Interface is better to define a callback /
contract than an abstract class
But we can do better by reducing the coupling still
Because interface forces you to implement all the
functions in the contract, What if you need an
option to selectively respond to callbacks?

Delegates come to help!


• Special feature of .net
• Almost like a function pointer
• A reference type
• Promotes loosely coupled code

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
668
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Delegate
The person who advertises a function does so by
publishing the function prototype
public delegate int DelegateProcess(string s);

When somebody else writes a function to match


this signature that function could be attached to
this publisher ( as a property or a private
variable set thru constructor)

The publisher invokes the method thru this


variable by passing a string and gets a integer
result back

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
669
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Delegate - Sample
public delegate int DelegateProcess(string s);
public class Publisher
{
private DelegateProcess DPMessage; //Declare a variable
public Publisher( DelegateProcess dpMessage)
{
this.DPMessage = dpMessage;
}
public void Publish()
{
int n = DPMessage("xyz");
Console.WriteLine("{0} ", n);
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
670
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Delegate - Implementing
class Subscriber
{
static void Main(string[] args)
{
Subscriber sb = new Subscriber();
DelegateProcess dp = new DelegateProcess( sb.MessageCount);
Publisher p = new Publisher(dp);
p.Publish();
Console.ReadLine();
}
public int MessageCount(string s)
{
return s.Length;
}
}
Main calls Publish method of publisher and Publisher calls
MessageCount method
Note here that the publisher does not have any clue of the
Subscriber class name or the method name which
implements the delegate!

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
671
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Strategy
In the previous sample it is not possible to attach
a method (as delegate) after creating Publisher
This is because it has to be set thru the
constructor
While this is a best practice for other instance
variables, it is not applicable to delegates
Hence it is better to set delegate thru a property
or keep the delegate as a public variable in the
publisher

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
672
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
MultiCast Delegate
Attaching more than one function to a delegate
When publisher calls the delegate all the attached
functions get invoked
Since there are more than one function all
Multicast delegates will be a void type functions!
Let us assume a Publisher sends out Greetings to
people registered
The Greetings are generated based on some
algorithm which we are not going to bother
about
What we consider here is how to register multiple
persons and receive the greeting!

public delegate void DelegateGreetings(string s);


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
673
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Multicast – Publisher
public delegate void DelegateGreetings(string s);
public class Publisher
{
public DelegateGreetings DGMessage;

public void Greet()


{
DGMessage("Good Morning");
}
}

Nothing specific here about multicast


delegate except for void return type

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
674
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Multicast - Subscriber
public class Personal
{
private string Name;
public Personal(string name)
{
this.Name = name;
}
public void GreetMe(string msg)
{
Console.WriteLine(msg + " ," + Name + "!");
}
}
Subscriber – Personal implements a method with
matching Signature to receive the greeting /
Call !

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
675
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
MultiCasting…
Provide a Main method in another class which has
Personal p1 = new Personal("David");
Personal p2 = new Personal("Goliath");
Personal p3 = new Personal("Henry");
//Create 3 delegates
DelegateGreetings dg1 = new DelegateGreetings(p1.GreetMe);
DelegateGreetings dg2 = new DelegateGreetings(p2.GreetMe);
DelegateGreetings dg3 = new DelegateGreetings(p3.GreetMe);

//Delegates could be added with +


p.DGMessage = dg1 + dg2 + dg3;
p.Greet();

//could be removed with –


p.DGMessage -= dg2;
p.Greet();

Publisher invokes the method once but all the


subscribers receive it!
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
676
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Anonymous methods

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Anonymous methods
C# supports delegates for invoking one or multiple methods.
Delegates provide operators and methods for adding and
removing target methods, and are used extensively throughout
the .NET Framework for events, callbacks, asynchronous calls,
and multithreading.
Anonymous methods is a new feature in C# 2.0 that lets you
define an anonymous (that is, nameless) method called by a
delegate.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
678
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Anonymous methods
class Kid
Did you notice that you are forced
{
to create a class or a method just
delegate void KidDelegate(); for the sake of using a delegate.
public void InvokePrint()
{
KidDelegate del = new KidDelegate(PrintKid);
del(); static void Main(string[] args)
{
}
Kid k = new Kid();
void PrintKid() k.InvokePrint();
}
{
System.Console.WriteLine ("Kid is printed");
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
679
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Anonymous methods
You can define and implement the same in a better way with an
anonymous method:
There is no need to invoke a
method just to use a Delegate.
class Kid
{
delegate void KidDelegate();
public void InvokePrint()
{
KidDelegate del = delegate()
{
System.Console.WriteLine ("Kid is printed");
};
del(); Now things are simple…
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
680
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Anonymous methods

Some Q & A
?
What if you want to pass an anonymous method to a method that
accepts an abstract Delegate parameter.

Like
void KidDelegate(Delegate del);

Ans..
cast the anonymous method to the specific delegate type.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
681
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Anonymous methods
•Anonymous methods can be used anywhere that a delegate type is expected.
•You can pass an anonymous method into any method that accepts the
appropriate delegate type as a parameter

class Kid
{
delegate void KidDelegate();
public void PrintKid()
{
InvokePrint(delegate())
{
System.Console.WriteLine ("Kid is printed");
}
}
static void Main(string[] args)
void InvokePrint(KidDelegate del)
{
{ Kid k = new Kid();
del(); k.PrintKid();
} } }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
682
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Anonymous methods
Now Let’s take our Thread example using a Anonymous Method
public class Kid
A anonymous method serves as
{ the thread method, causing the
public void KidThread() message to be displayed from the
new thread.
{
Thread T = new Thread(delegate() {
MessageBox.Show(“Kid is printed");
} );
T.Start();
}}

You saw that we used an anonymous method as a parameter


for launching a new thread without explicitly defining a
ThreadStart delegate or a thread method:

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
683
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Passing Parameters to Anonymous Methods
When defining an anonymous method with parameters, you define the parameter
types and names after the delegate keyword just as if it were a conventional method.
The method signature must match the definition of the delegate to which it is
assigned.
When invoking the delegate, you pass the parameter's values, just as with a normal
delegate invocation.

class Kid{
delegate void KidDelegate(string str);
public void InvokePrint()
{ KidDelegate del = delegate(string str)

{
System.Console.WriteLine(str);
};
del(" Kid is printed”);
}}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
684
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Anonymous methods
?
SomeDelegate del = delegate()
Anonymous methods without parameters
Ans
If the anonymous method has no parameters, you can use a pair of empty
parens after the delegate

class Kid {
delegate void KidDelegate();
public void InvokePrint()
{ KidDelegate del = delegate() {
System.Console.WriteLine("Kid is Printed");};
del(); }}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
685
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Anonymous methods
?
How about Anonymous methods with no parenthesis
Ans
Yes Possible these are called special delegates.

class kid {
delegate void KidDelegate(string str);
public void InvokePrint()
{ KidDelegate del = delegate {
System.Console.WriteLine("Kid is Printed");
};
del("Parameter is ignored"); }}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
686
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Anonymous methods

But wait …..

Note that you must still provide arguments when invoking the delegate
because the compiler generates nameless parameters for the anonymous
method
anonymous methods without a parameter list cannot be used with
delegates that specify out parameters.
An anonymous method can use any class member variable, and it can also
use any local variable defined at the scope of its containing method as if it
were its own local variable.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
687
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generic Anonymous Methods

An anonymous method can use generic parameter types, just like any other
method. It can use generic types defined at the scope of the class
class Kid<T>
{
delegate void KidDelegate (T t);
public void InvokeKid (T t)
{
KidDelegate del = delegate (T item) {...}
Del (t);
}}

Delegates can define generic parameters, an anonymous method can


use generic types defined at the delegate level.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
688
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Anonymous methods
Ok lets sum up this.
Anonymous Methods are useful because it replaces the need for
creating a simple method in cases where only a delegate will suffice.

class KidForm:Form
{
private Button button1;

KidForm()
{
this.button1 = new
System.Windows.Forms.Button();

this.button1.Name = "btnClick";

this.button1.Text = "Click";
this.Controls.Add(button1);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
689
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Anonymous methods
button1.Click += delegate(object sender, EventArgs args)
{
MessageBox.Show("Button Clicked !");
};
}
public static void Main()
{
Application.Run(new KidForm());
} }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
690
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Delegate Inference
The C# compiler's ability to infer from an anonymous method
assignment which delegate type to instantiate is an important capability.
In fact, it enables yet another C# 2.0 feature called delegate inference.
Delegate inference allows you to make a direct assignment of a method
name to a delegate variable, without wrapping it first with a delegate
object.

class Kid In C# 1.1


{
delegate void KidDelegate();
public void InvokePrint() {
KidDelegate del = new KidDelegate(PrintKid);
del();
}
void PrintKid() {...}}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
691
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Delegate Inference

class Kid
{ IN C# 2.0
delegate void KidDelegate();
public void InvokePrint()
{
KidDelegate del = PrintKid;
del();
}
void PrintKid() {...}
}

When you assign a method name to a delegate, the compiler first infers the
delegate's type. Then the compiler verifies that there is a method by that
name and that its signature matches that of the inferred delegate type.
Finally, the compiler creates a new object of the inferred delegate type,
wrapping the method and assigning it to the delegate.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
692
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Events

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Events
Declaring a multi cast delegate as a public property of
a publishing class may result in anybody invoking it

Events are there to rescue us!

Events are similar to multicast delegates they are used


to inform clients of some things happening in the
publisher
But with a difference :
Only the publisher can fire an event (invoke the
delegate method)!

Events use delegates internally

Events are mostly used for UI components


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
694
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Events Greeting
Let us rewrite the greetings application using events
public delegate void GreetingsHandler(string message);
public class Publisher
{
public event GreetingsHandler GotGreetings; //Event
public Publisher() { }
//Wrapper to invoke events – Best Practice
protected virtual void OnGotGreetings(string message)
{
if (GotGreetings != null)
GotGreetings(message);
}
public void Greet() //Exercise Event Firing
{
OnGotGreetings("Good morning");
}
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
695
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Events Greeting
In publisher the event firing code is encapsulated
in a protected virtual function
Any class inheriting Publisher could override or
invoke this code!
Personal class is the same as before
Here is the code for subscribing to events

Personal p1 = new Personal("David");


Personal p2 = new Personal("Goliath");
Personal p3 = new Personal("Henry");

Publisher p = new Publisher();


//Subscribe to events
p.GotGreetings += new GreetingsHandler(p1.GreetMe);
p.GotGreetings += new GreetingsHandler(p2.GreetMe);
p.Greet();
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
696
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Events Conventions
Apart from best practice of making the event raising
wrapper function protected & virtual
• Event methods return void because of multicasting
• Event parameters
• An Object – Sender
• A class derived from EventArgs
Introduce a new class :
public class GreetingEventArgs : EventArgs
{
private string message;
public GreetingEventArgs(string message)
{
this.message = message;
}
public string Message //Property
{
get { return message; }
}
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
697
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Events Conventions
Change Publisher class :
public delegate void GreetingsHandler
(object o, GreetingEventArgs e);
public class Publisher
{
public event GreetingsHandler GotGreetings; //Event
public Publisher() { }
//Wrapper to invoke events – Best Practice
protected virtual void OnGotGreetings(string message)
{
if (GotGreetings != null)
GotGreetings(this, new GreetingEventArgs(message));
}
public void Greet() //Exercise Event Firing
{
OnGotGreetings("Good morning");
}
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
698
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Event Conventions
Change personal class event handler code :
public void GreetMe(object o, GreetingEventArgs e)
{
Console.WriteLine(e.Message + " ," + Name + "!");
}

Exercise :
Create a Timer class which publishes a TimeChanged
event every second. This timer class will run for
only a preset amount of seconds. Notify new time
using eventargs (TimeChangedEventArgs with
hour, minute and second in the parameter)
Hint : Timer runs in a never ending loop but
terminate using the preset seconds. Use
Thread.Sleep and System.DateTime.Now to control
the timer.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
699
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Exception Handling

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Exception Handling
• Error condition(fault) or Unexpected behavior
• Happen in our code or the code that we call
• Can be application specific or the platform or
runtime specific errors
• Can recover from application errors
• Say an invalid input ask user to enter again
• Cannot recover from runtime exceptions
• A resource not found

• It is better to be balanced not over use and at the


same time under use exceptions
• Check the conditions in code where you can
• Handle exceptions when you cannot
We can create our own application specific
exceptions and use them
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
701
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Exception Language elements
There are 3 block definitions (Handle exceptions)
and 1 statement (to raise an exception)
try – Block :
• Have statements that could potentially cause exception(s)
catch – Block :
• Statements that can be used to take an action (log / display
error message, run the recovery code etc.)
• Each type of exception will be caught using a separate catch
statement
finally – Block :
• Statements used to cleanup
• Executes always whether an exception occurred or not
Throw statement :
throw new <exception class(args)>
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
702
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Mechanism
class BadClass //simulates a method which could go wrong
{
public static void BadMethod()
{
throw new ArgumentException("Test throw"); //throw an exception
}
}

static void Main(string[] args)


{
try
{
BadClass.BadMethod();
}
catch(Exception e) //catch Any exception
{
Console.WriteLine("Got an exception : {0}", e.Message);
}
finally
{
Console.WriteLine("Cleaning up");
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
703
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Mechanism
Code in try block executes (Badmethod is invoked)
Exceptions occurs and caught by the catch statement
(Infact any exception could be caught here)
Finally executes
If we remove the BadMethod call in the try we can see that
finally is executed still
Here we have caught the exception using the generic base
class exception
This is not a good idea since all exceptions will be handled
by one catch and we cannot take different action for
different exceptions
The best thing is to catch & handle the individual exceptions
first and catch the generic exception as a last catch
Thorough testing helps Better exception handling

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
704
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Recommended
try {
//statements that could throw exceptions
}
catch (SpecificException1 se1) {
//handle here
}
catch (SpecificException2 se2) {
//handle here
}
catch (SpecificException3 se3) {
//handle here
} …
Finally {
//Clean up resources
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
705
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
User Defined Exceptions
Can be thrown if some other exception is
encountered (in a catch statement) or during
other conditions(mostly a check done in code)
Create a class with name ending in Exception
deriving from ApplicationExcption class

Constructors to be provided
• Avoid default constructor
• When another exception is the cause
public myappException(string message, Exception cause)
• When an exception is thrown this way it is easy to check the
StackTrace property for fixing
• Otherwise
public myappException(string message)
• StackTrace is usefull here also
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
706
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sample
public class EmployeeListNotFoundException:
ApplicationException
{
public EmployeeListNotFoundException(string message)
: base(message)
{
}
public EmployeeListNotFoundException(string message,
Exception inner): base(message, inner)
{
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
707
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Inline Warning

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Inline Warning
   We have seen that in C# 1.1 we can disable specific compiler warnings
using project settings or by issuing command-line arguments to the
compiler.

The problem here is that this is a global suppression, and it also


suppresses warnings that you still want.

In C# 2.0 we have a solution to this crises by using inline


warning.
Inline Warning allows you to explicitly suppress and restore
compiler warnings using the #pragma warning directive.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
709
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Inline Warning
Example
#pragma warning disable 169

public class MyClass


{
int m_Number;
}
#pragma warning restore 169

Note that you cannot programmatically override the project settings, meaning you
cannot use the pragma warning directive to restore a warning that is suppressed
globally.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
710
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Refactoring Support Under
Visual Studio 2005

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Defining the Refactoring Process
Refactoring is a formal and mechanical process, used
to modify existing code in such a way that it does
indeed become 'better' while preserving the
program's intended functionality. In addition to
improving a program's overall design, the refactoring
process tends to yield code which is far easier to
maintain and extend in the long run.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
712
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Refactoring Support Under Visual Studio 2005

In the bad old days, refactoring typically involved a


ton of manual labor. Once developers identified the
code to modify, they tended to make substantial use
of copy, paste, find, replace, compile, test (repeat)
techniques. This was time-intensive difficult and
error prone.

With Visual Studio 2005 you can automate the


refactoring process. Using the Refactoring menu you
can dramatically reshape your code with minimal
fuss and trouble.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
713
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Studio 2005 refactorings.
Refactoring Technique What it does

Extract Method This allows you to define a new method


based on a selection of code statements.

Encapsulate Field Turns a public field into a private field


encapsulated by a .NET property.

Extract Interface Defines a new interface type based on a


set of existing type members.

Reorder Parameters Provides a way to reorder member


arguments.

Remove Parameters As you would expect, this refactoring


removes a given argument from the current list
of parameters.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
714
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Studio 2005 refactorings.
Refactoring Technique What it does

Rename This allows you to rename a code token


(method name, field, local variable, and so on)
throughout a project.

Promote Local Variable to Parameter Moves a local variable to the parameter set
of the defining method.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
715
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough - Extract Method

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
716
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough - Extract Method

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
717
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough - Extract Method

At this point, you will be presented


with a dialog box that allows you to
enter the name of the new method
to be generated

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
718
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough - Extract Method

Notice that the new method is


automatically defined as private and
static, as the code statements did not refer
to any instance level variables (generally
speaking, extracted methods will be given
the most restrictive modifiers possible).

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
719
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Encapsulate Field

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
720
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Encapsulate Field
If you have checked the 'Preview Reference
Changes' checkbox, you will then be presented
with a final dialog that documents the full results
of the proposed change

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
721
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Encapsulate Field

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
722
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Encapsulate Field

Here is the end result of this


Encapsulate Field refactoring.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
723
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Extract Interface

The Extract Interface refactoring allows you


to select a group of existing type members
to yield a new interface abstraction.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
724
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Extract Interface

Note   You can also extract an interface by simply highlighting the name of the class (or structure) and
activating the Refactoring menu, rather than selecting a set of type members.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
725
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Extract Interface

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
726
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Local Variable to Parameter

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
727
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Local Variable to Parameter

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
728
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Reorder Parameters

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
729
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Reorder Parameters
Like other Visual Studio 2005 refactoring options, you
are next presented with a configuration dialog box. In
this case, you are able move a particular argument up
or down the chain

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
730
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Reorder Parameters

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
731
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Rename Parameters

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
732
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Rename Parameters

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
733
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Rename Parameters

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
734
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Remove Parameters

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
735
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Remove Parameters

At this point, you will be presented with a


configuration dialog where you are able to
select the parameters you wish to remove

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
736
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thank You

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Programming
with
.NET Framework

COE – Current Technologies


Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Assembly and CLR

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
• Understanding Assemblies.
• Structure of an Assembly.
• Single file, Multifile Assembly.
• Metadata and Manifest.
• Examining a manifest.
• Creating a multimodule Assembly.
• Private and Shared Assemblies.
• Strong names and Signcode.
• Installing an Assembly into Global Assembly Cache
(GAC).

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
740
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Assemblies
• Assemblies are the .NET unit of reuse,versioning and
deployment.
• Self describing components that have no
dependencies on registry entries.
• Assemblies are a unique feature of .NET applications
that simplify application deployment
• Assemblies solve the versioning problems that can
occur with component based applications.
• To the user an assembly appears as a single .dll
(Collections of classes and methods that are linked
into the program at runtime) or .exe.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
741
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
An end to DLL Hell
An end to “DLL Hell” : Occurred due to version conflicts
where installing one application can break an existing
application because the existing dll was not fully
backward compatible with a previous version.
Assemblies provide a solution to this nightmare by
the unique identification through version number.

As a result of assemblies different versions of .NET


applications can co-exist on the same machine
independently without interference.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
742
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Assemblies
Structure of an Assembly:
In general an assembly can consist of four elements:
• The assembly manifest which contains assembly metadata.
• Type manifest.
• MSIL(Microsoft Intermediate Language) that implements
the types.
• A set of resources.
These resources can be grouped into an assembly in the form
of
• Single-file assembly.
Assembly
Figure 1 metadata
MSIL Code
Type Metadata

Resources

All constituents of an assembly are contained within the same physical file.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
743
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Assemblies
Multifile Assembly:
• The elements of an assembly are contained in several
files.
• These files can be modules of compiled
code(.netmodule) , resources(such as .bmp or .jpg
files) or other
Assembly
files required by the application.
metadata Type metadata

Type metadata MSIL Code

MSIL Code .netmodule


Resources

MyAssembly.dll
Graphic.bmp

Fig 2: Elements of a multifile Assembly

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
744
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Mutimodule Assemblies(Contd..)
Advantage of a Mutimodule Assembly:
• The .NET framework downloads a file only when
referenced keeping infrequently referenced code in a
separate file.
• The files that make up a multimodule assembly are
not physically linked by the file system .
• These files are linked through an assembly manifest
and the CLR manages them as a unit.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
745
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Metadata and Manifest
On disk,assemblies are Portable Executables(PE)
implemented as .dll or .exe and contain a single
entry point(DLLMain, WinMain, Main).
Metadata:
• Is the information stored in the assembly that
describes the types and methods of an assembly.
• Assemlies are self descriptive because metadata fully
describes the contents of each module.
Manifest:
• Is a block of metadata that describes the types and
methods of the assembly.
• Assemblies are self descibing due to the metadata.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
746
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Types of Manifest
Is of 2 types:
(1) Assembly manifest : Contains information about
• Version
• Security
• Dependency of an assembly
(2) Type manifest:
• Contains information about the types within the
assembly.This includes the user defined types e.g.
classes, structs and the build in types.
• .NET maintains a strong type checking before
executing any type.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
747
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Assemblies
Examining the manifest: The structure of manifest can be
examined using the ILDASM.exe which is provided as part of
.NET framework.
On the Visual Studio .NET Command Prompt type ILDASM.In the
file menu open the dll or exe of a project. The file will look like
this.

Figure 3
The figure shows a tree view that allows inspection of the
manifest,various classes and methods contained within the
assembly.On clicking the manifest,it is revealed as in Figure 4.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
748
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating a Multimodule
Assembly(Contd..)

Figure 4

Manifest of an assembly

Modules in the manifest:


• A module is a non executable code with .netmodule extension.
• Assemblies can contain one or more such netmodules which in
turn contains the manifest describing that module.
• The module manifest lists the assemblies and types referenced
by that module.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
749
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating a Multimodule Assembly
A single module assembly has a single file (exe / dll).This single
module contains all the types and implementations for the
application.The Assembly manifest is contained within this
module.
Creating a multi module Assembly:
Step 1: Compiling files with Namespaces referenced with other files
using System;
namespace myNamespace
{
public class MultiMod
{
public void multiMod()
{
System.Console.WriteLine("This is a line from mutiMod
method");
}
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
750
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating a Multimodule Assembly
Use the following command to compile this file
csc /t:module MultiMod.cs
Specifying the /t option indicates that the file should be compiled
as a module rather than an assembly.The compiler produces a
module MultiMod.netmodule,which can be added to the
assembly.
Step 2: Compiling modules with reference to other modules
using System;
using myNamespace; //The namespace created in the
MultiMod.netmodule
class myMultiMod {
//Static method Main is the entry point method.
public static void Main()
{
MultiMod mod=new MultiMod();
Console.WriteLine("Client code executes");
//Calling the multiMod method from the MultiMod class
mod.multiMod();
}©2007
} Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
751
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating a Multimodule Assembly
Use the following command to compile this code
csc /addmodule:MultiMod.netmodule /t:module myMultiMod.cs
This module references a method from the
MultiMod.netmodule.The /t:module option specifies to create a
module that would be later added to the assembly.
Step 3: Creating a Multifile assembly using the Assembly linker
You can use the Assembly Linker(Al.exe) to create an assembly
from a collection of compiled netmodules
At the Visual Studio .NET command prompt type the following:
al myMultiMod.netmodule MultiMod.netmodule
/main:myMultiMod.Main /out:myAssembly.exe /target:exe

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
752
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating a Multimodule Assembly

When the resulting dll is examined with MSIL Disassembler(ILDasm.exe), it


shows the following screen.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
753
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Assemblies
Assemblies are of 2 types based upon their accessibilty
1. Private Assemblies:
• Used by single application.
• Created by default after a .Net application is compiled.
• Can be redeployed on another machine just by
copying the files contained with the application folder.
2. Shared Assemblies:
• Shared by other applications.
• Such an assembly needs to be installed into an area of
filesystem set aside by CLR for Shared assemblies
called Global Assembly Cache(GAC) .
• Before the assembly can be installed into the GAC it
needs to be signed with a unique ID called strong
name.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
754
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Global Assembly Cache
Global Asssembly Cache:
• Each computer which has the CLR has a machine
wide code cache called the GAC .
• GAC stores the assemblies to be shared by several
applications on the computer.
• Each assembly installed into the GAC is uniquely
identified by its name and version.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
755
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Assembly Version
Assembly Versions:
• The GAC allows “side by side versions where the older
version may co-exist with the newer version.T
• The assemblies version number together with the
assembly name and culture information is part of the
assembly’s identity.
The version number is physically represented as part of
the assembly manifest in form of a four part string in
the following format.
<major version>:<minor version>:<build
number>:<revision>
The version checking by the CLR ensures that only the
assembly with the right version number is loaded at
runtime.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
756
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Strong named Assemblies and Signcode:

Signing an assembly with a strong name ensures a


• Globally unique name for the assembly
• Prevent tampering of the assembly by providing
digital signatures and public key encryption.
• The correct assembly authored by the actual creator
is loaded.
All the above is ensured by giving an assembly a Strong
Name using
sn –k utility.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
757
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Strong named Assemblies and Signcode:

To ensure greater security , an assembly can be


signcoded ( with Signcode.exe) using digital
certificates purchased from a third party vendor.
Strong naming and digital certificates guarantee
foolproof integrity.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
758
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Installing an Assembly into the GAC
Assemblies can be shared by installing them into GAC
by any of the ways:
1. Using a Developer tool called Global Assembl Cache
tool (GacUtil.exe).
2. Using Windows explorer to drag the assembly.
Step 1: Strong naming an Assembly:
On the Visual Studio .NET comand prompt type
sn –k myStrongName.snk
The –k option along with sn(strong name utilty)
indicates to create a file containing the key value
pair.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
759
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Installing an Assembly into the GAC
Step 2: Associate the Strong name with the assembly(if
using a VS IDE)
You can associate this strong name with your assembly in
the assemblyinfo.cs file in the predefined attribute
using System.Runtime.CompilerServices;
[assembly:AssemblyKeyFile(“.\myStrongName.key ”)]
If not using a VS IDE associate the strong name with the
exe/dll using
al /out:MyAssembly.dll myMultiMod.netmodule /keyfile:
myStrongName.snk
Step 3: Installing to the GAC.
On the VS.NET command prompt type
gacutil –i myAssembly.dll
“ Assembly successfully added to the cache” message id
displayed on the command prompt.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
760
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Installing an Assembly into the GAC
Assemblies can also be installed into GAC using
windows explorer like utility.
Open C:\Winnt \assembly or C:\Windows\assembly
The window changes to a GAC explorer displaying the
name,type,version,culture and public key token no of
all assembles installed into GAC. Drag and drop
your .dll into the window.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
761
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Installing an Assembly into the GAC
Each assembly is uniquely identified with a public key token number
assigned by the CLR.This number can be seen for any assembly
by writing on the VS.Net command prompt.
sn -Tp myAssembly.dll
Sample output is:

Public key is
002400000480000094000000060200000024000052534131000400
00010001004dcc7b5243839e5789e1f12bbd817daf20a55fe22bc0
a29e7c245137f227c2980cf0415356154221111c37e2ce33ff66652
6a35dd08f1b7e5ca6235abd156f702243df4e86b29a37213cc8105a
9cb774fba036d4b7ac116b8f2a1d41bb73f5644771eefb359fdecd7
059437bedbfd0cf7e2092ddf0bf3ad200b1c5547fa7cbb4
Public key token is a179f8bc5bfc3463

DIY:
Create a mutlimodule assembly, signcode it and install it into the
Global Assembly Cache (GAC).

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
762
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Application Domains

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
• Understanding Application Domains.
• Benefits of Application Domains.
• Creating Application Domains.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
764
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Application Domains
The operating system creates separate process boundaries for
each application.Each Win32 application runs in its own process
along with a 4GB virtual address space.Additional libraries or
components share this address space.
Understanding Application Domains
• Application domains provide a secure and versatile unit of
processing .
• The common language runtime can use Application Domains to
provide isolation between applications.
• You can run several application domains in a single process
with the same level of isolation that would exist in separate
processes.
• Application Domains run without incurring the additional
overhead of making cross-process calls or switching between
processes.
• The ability to run multiple applications within a single process
dramatically increases server scalability.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
765
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Application Domains

EXE EXE EXE

DLL DLL DLL DLL

Process A Process B Process C


Figure 1: The Win32 Process boundary.Separate Processes
PROCESS A

DLL EXE DLL

EXE EXE EXE

App Domain App Domain App Domain


Figure 2 : A PROCESS DIVIDED INTO APPLICATION DOMAINS
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
766
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Benefits of Application Domains
The isolation provided by application domains has the following
benefits:
1) Faults in one application cannot affect other applications.
Because type-safe code cannot cause memory faults, using
application domains ensures that code running in one domain
cannot affect other applications in the process.
2) Individual applications can be stopped without stopping the
entire process. Using application domains enables you to
unload the code running in a single application.
3) Code running in one application cannot directly access code or
resources from another application. The common language
runtime enforces this isolation by preventing direct calls
between objects in different application domains. Objects that
pass between domains are either copied or accessed by proxy.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
767
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Benefits of Application Domains(Contd..)

4) The behavior of code is scoped by the application in


which it runs. In other words, the application
domain provides configuration settings such as
application version policies, the location of any
remote assemblies it accesses, and information
about where to locate assemblies that are loaded
into the domain.
5) Permissions granted to code can be controlled by
the application domain in which the code is running.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
768
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Application Domains
A new Application Domain can be created by calling the
static method CreateDomain() on the AppDomain class.
AppDomain ad =
AppDomain.CreateDomain(“Our Domain", null,
null);
Where the first parameter passed to the CreateDomain
method is the friendlyname,second parameter is the
securityinfo while the last parameter is info belonging
to the System.AppDomainSetup.
You can check the friendly name of the domain you're
working in with the property
System.AppDomain.CurrentDomain.FriendlyName.
Once you have instantiated an AppDomain object, you can
create instances of classes, interfaces, and so forth
using its CreateInstance( ) method. Here's the
signature:
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
769
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Application Domains
public ObjectHandle CreateInstance(
string assemblyName,
string typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
object[] args,
CultureInfo culture,
object[] activationAttributes,
Evidence securityAttributes
);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
770
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Threads

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion

• About Threads
• Creating and starting threads.
• Understanding Threads.
• Thread Lifecycle.
• Suspending a Thread.
• Joining Threads.
• Thread States.
• Thread Priorities.
• Thread Synchronization.
• Race Condition and deadlocks.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
772
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Threads
• Threads are lightweight processes responsible for
multitasking within a single application.
• Threads are typically created when you want a
program to do two things at once.
• The System.Threading namespace provides classes
and interfaces to manage multithreaded programming.
• Threads are closely related to multitasking and are
used by the CLR to manage multiple tasks.
• In .NET , the CLR encapsulates the functionality of
Threading into classes that greatly simplify most
threading tasks.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
773
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating and Starting Threads
• Create a new instance of the Thread class. The constructor of
the Thread class takes a single argument- a delegate type
called ThreadStart which points to a method that we create.
The method passed to the delegate must take no parameters
and returns void.
• Public delegate void ThreadStart(); // Predeclared delegate
The method to be attached to this delegate must take no
parameters and must return void.
• Thread myThread=new Thread(new ThreadStart
(myFunc));
Even though the Thread instance is created,it will not start.To
start the thread call the Start method on the Thread object.
myThread.Start();

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
774
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Understanding Threads
public class ThreadsDemo
{ public void testThread() {
Thread t1=new Thread(new ThreadStart (incrementer));
t1.Start();
Thread t2=new Thread(new ThreadStart (decrementer));
t2.Start(); }
public void incrementer() {
for(int x=2;x<=50;x++)
{Console.WriteLine("Good Morning {0}",x); }
}
public void decrementer()
{ for(int y=50;y>=1;y--)
{
Console.WriteLine("Good Evening {0}",y);
}
}
public static void Main()
{ ThreadsDemo td=new ThreadsDemo();
td.testThread();
} }
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
775
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thread LifeCycle
A Thread, as previously discussed is started with Thread.Start()
method.
A started Thread may be paused or suspended for a period of time.
Suspending Threads:
Calling the Thread.Sleep() method causes the current thread to
suspend for the given time, passed as milliseconds ,yielding the
remainder of its time slice to another thread.
Thread.Sleep() is a public static method and has 2 overloads, one
accepts a timespan and the second the time in milliseconds for
which the thread should be allowed to sleep.The threads resumes
after the given time has lapsed.
Calling Thread.Sleep(Timeout.Infinite) causes a thread to sleep until
it is interrupted by another thread that calls Thread.Interrupt or is
aborted by Thread.Abort.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
776
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thread LifeCycle
Pausing a Thread: A thread can be paused by calling
the static method
Thread.Suspend.The thread remains suspended until
another threads calls the Thread.Resume on the
suspended thread.
Killing Threads:
The Thread.Abort method is used to stop a logical
thread permanently. When you call Abort, the
common language runtime throws a
ThreadAbortException, which the thread can catch.
Thread.Interrupt wakes a thread out of any wait it
might be in and causes a ThreadInterruptedException
to be thrown in the destination thread.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
777
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Suspending a Thread
public class ThreadInterruptDemo {
public static void Main(){
ThreadInterruptDemo thd=new ThreadInterruptDemo();
thd.testInterrupt();}
public void testInterrupt(){
Thread th1=new Thread(new ThreadStart(moveUp));
th1.Start();
Thread.Sleep(5000);//Causes the Thread to sleep for 5 seconds
before starting the other Thread.
Thread th2=new Thread(new ThreadStart(moveDown));
th2.Start(); }
public void moveUp(){
for(int k=0;k<100;k++)
{
Console.WriteLine("Up {0}",k);
}}
public void moveDown(){
for(int m=100;m>1;m--)
{
Console.WriteLine("Down {0}",m);
}
}}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
778
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Joining Threads
Blocks the calling thread until a thread terminates.
When you tell a thread to stop processing and wait until
a second thread
completes its work, you are said to be joining the first
thread to the second. To join thread 1 (t1) onto thread
2 (t2), you write:
t2.Join( );
If this statement is executed in a method in thread t1, t1
will halt and wait until t2 completes and exits.
Blocks the calling thread until a thread terminates or the
specified time elapses. public bool Join(int);
Blocks the calling thread until a thread terminates or the
specified time elapses. public bool Join(TimeSpan);
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
779
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Joining Threads(Demo)
The following example uses the Join() method to wait
for the new thread to terminate. If the Join() method
were not called by the main thread of this sample, a
race condition would occur between the two threads. If
this were to happen, the second thread may not be
able to finish processing before the application exits.
using System;
using System.Threading;
class App {
static void MyThreadMethod() {
Console.WriteLine("This is the secondary thread running.");
}
static void Main() {
Console.WriteLine("This is the primary thread running.");
// MyThreadMethod is the secondary thread's entry point.
Thread t = new Thread(new ThreadStart(MyThreadMethod));
// Start the thread
t.Start();
// Wait for the thread to exit
t.Join();
Console.WriteLine("The secondary thread has terminated.");
} }
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
780
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thread States
The property Thread.ThreadState provides a bit mask that indicates the thread's
current state. A thread is always in at least one of the possible states in the
ThreadState enumeration, and can be in multiple states at the same time.
Action New State
The thread responds to Thread.Start and starts running. Running
The thread calls Thread.Sleep.WaitSleep Join
The thread calls Monitor.Wait on another object. WaitSleepJoin
The thread calls Thread.Join on another thread. WaitSleepJoin
Another thread calls Thread.Suspend. SuspendRequested
The thread responds to a Thread.Suspend request. Suspended
Another thread calls Thread.Resume. Running
Another thread calls Thread.Interrupt. Running
Another thread calls Thread.Abort. AbortRequested
The thread responds to a Thread.Abort. Aborted

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
781
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thread Priorities
Threads are scheduled for execution based on their priority. The scheduling
algorithm used to determine the order of thread execution varies with
each operating system .
ThreadPriority defines the set of all possible values for a thread priority.
Thread priorities specify the relative priority of one thread versus another.

1. AboveNormal : The Thread can be scheduled after threads with Highest


priority and before those with Normal priority.
2. BelowNormal : The Thread can be scheduled after threads with Normal
priority and before those with Lowest priority.
3. Highest : The Thread can be scheduled before threads with any other
priority.
4. Lowest : The Thread can be scheduled after threads with any other
priority.
5. Normal : The Thread can be scheduled after threads with AboveNormal
priority and before those with BelowNormal priority. Threads have Normal
priority by default.Requirements.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
782
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Understanding Threads
public class ThreadsJoin{
public static void Main(){
ThreadsJoin tj=new ThreadsJoin();
tj.workThreads(); }
public void workThreads() { Thread[] th=
{
new Thread(new ThreadStart(goodMorning)),
new Thread(new ThreadStart(goodNoon)),
new Thread(new ThreadStart(goodEvening)) };
for(int i=0;i<3;i++){
th[i].Start(); }
Thread.Sleep(3000);
th[1].Interrupt();
Console.WriteLine("Good Noon interrupted");
th[2].Join();
Console.WriteLine("All the threads have
finished"); }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
783
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Understanding Threads
public void goodMorning()
{ for(int x=0;x<50;x++) {
Console.WriteLine("Good Morning
{0}",x); }
}
public void goodNoon()
{ for(int y=50;y>1;y--) {
Console.WriteLine("Good Noon
{0}",y); }
}
public void goodEvening()
{ for(int m=50;m<100;m++) {
Console.WriteLine("Good Evening
{0}",m);
}}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
784
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thread Synchronization
Thread Synchronization is the mechanism to control
access to a shared resource by simultaneous
Threads so that the other threads do not interfere
while the resource is held by the first thread hs
finished with it. It is achieved through:
1. Interlock class,
2. the C# lock statement,
3. the Monitor class.
Interlock: C# offers a special class, Interlocked to offer
synchronization protection for common tasks such as
incrementing and decrementing.
The following example makes the point clear

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
785
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Synchronization(Contd..)
using System;
using System.Threading;
class Tester {
private int counter = 0;
static void Main( ) { // make an instance of this class
Tester t = new Tester( ); // run outside static Main
t.DoTest( ); }
public void DoTest( ){
Thread t1 = new Thread( new ThreadStart(Incrementer) );
t1.IsBackground=true;
t1.Name = "ThreadOne";
t1.Start( );
Console.WriteLine("Started thread {0}", t1.Name);
Thread t2 = new Thread( new ThreadStart(Incrementer) );
t2.IsBackground=true;
t2.Name = "ThreadTwo";
t2.Start( );
Console.WriteLine("Started thread {0}",t2.Name);
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
786
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Synchronization(Contd..)
t1.Join( ); t2.Join( ); // after all threads end, print a
message
Console.WriteLine("All my threads are done."); }
// demo function, counts up to 1K
public void Incrementer( )
{ try {
while (counter < 1000){
Interlocked.Increment(ref counter); // simulate some work
in this method
Thread.Sleep(1); // assign the decremented value and
display the results
Console.WriteLine("Thread {0}. Incrementer:
{1}",Thread.CurrentThread.Name,counter); } } }
catch (ThreadInterruptedException) {
Console.WriteLine("Thread {0} interrupted! Cleaning
{Console.WriteLine("Thread {0} Exiting.
",Thread.CurrentThread.Name);}}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
787
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Synchronization
Synchronization can also be achieved through the use of
lock.
Lock is a more general synchronization mechanism.
• A lock marks a critical section of your code, providing
synchronization to an object you designate while the
lock is in effect.
• The syntax of using a Lock is to request a lock on an
object and then to execute a statement or block of
statements.
• The lock is removed at the end of the statement block.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
788
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Synchronization
public void Incrementer( )
{ Try
{
while (counter < 1000) {
lock (this) {
int temp = counter;
temp ++;
Thread.Sleep(1);
counter = temp;
}
// assign the decremented value and display the
results
Console.WriteLine( "Thread {0}. Incrementer:
{1}",Thread.CurrentThread.Name,counter); } }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
789
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Race Condition
Race condition
• Exists when the success of your program depends on
the uncontrolled order of completion of two
independent threads.
• Eg while opening a file using a thread the other
thread would not start writing to the file until the first
thread has finished opening the file.
• This is race condition which can be avoided by the
use of Monitor and Wait() method before starting
Thread2.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
790
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DeadLock
DeadLocks:
• Deadlock condition ,also called deadly embrace is
caused when two threads.
• These threads try to access a resource which has
already been locked by the other thread.
• Each thread waits for the other to release the lock on
the resource. In turn neither of the threads would
be able to get access to the resource being held by
the other thread.
• This condition is resolved when either of the threads,
part of the deadlock relinquishes the resource.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
791
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Do it yourself (DIY)
(1)Create a “stop watch” application using Threads. It
should contains 2 buttons to start and stop the
watch. Also time should be depicted in Hrs:
Min:Sec:MilliSecs.
(2)Create a multithreaded application in which the
Principal ,Rate of interest and time for leasing the
loan should be accepted from the console. The
amount to be repaid should be calculated and
displayed using one thread. The other thread should
display the current time and date whenever the
amount is displayed.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
792
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
File Handling

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
• Streams
• Working with Directories.
• Methods of Directory class.
• Methods of Directory and DirectoryInfo class.
• Working with Directories.
• Creating and Deleting subdirectories.
• Finding the No. of subdirectories within specified
directory.
• Moving Directories.
• Working with Files.
• Synchronous and Asynchronous IO.
• FileMode enumeration members.
• Exploring the File Class
• Working with File Class methods
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
794
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
• Readers and Writers.
• Working with BinaryReader and BinaryWriter.
• Working with StreamReader and StreamWriter.
• Working with TextReader and TextWriter.
• Working with Buffered Streams.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
795
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Streams
Stream can be defined as a sequential flow of bytes
travelling from a source to a destination along a
communication path. The end point of a stream is a
backing source which might be a disk file, a network
connection or a memory buffer. The source and
destination of a stream may change depending upon
the condition.
The classes needed for reading from files or writing data
to files as present within the System.IO namespace.
The .NET Framework provides both buffered and
unbuffered streams, and provides classes for
asynchronous I/O as well.
To create a stream of data, your object must be
serialized, or written to the stream as a series of bits.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
796
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Working with Directories
The Directory class represents a directory and contains
static methods for creating, moving and exploring
directories. The directory class being static, the
methods are invoked using the class name and not its
instance.

The DirectoryInfo class is another class which has


instance members and are invoked through the class
instance. DirectoryInfo derives from FileSystemInfo,
which in turn derives from MarshalByRefObject

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
797
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Methods of Directory class
Method Description
CreateDirectory() Creates Directory/SubDirectory specified by the path
argument.
Delete() Deletes the directory and its contents.

Exists() Returns a true value if the directory specified in the path


parameter exists else false.
GetFiles() Returns an array of strings with filenames within the specified
directory.
GetDirectoryRoot Gets the root of the specified directory.
GetCurrentDirectory( Returns or Sets the current Directory.
)
SetCurrentDirectory(
)
GetLogicalDrives Returns an array indicating the logical drives on the hard disk.

GetDirectories Gets an array of subdirectories within the specified directory.


GetLastAccessTime() Gets or sets the last time the specified directory was
SetLastAccessTime() accessed.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
798
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Methods of DirectoryInfo class
The prominent attributes and methods of DirectoryInfo class are :
Method/Property Description
Attributes Gets or sets the attributes of the current file.
CreationTime Gets or sets the creation time of the current file.
Exists Returns a boolean value true if the specified file exists.
LastAccessTime Gets or sets the last access time of a directory.
CreateSubDirectory( Creates a subdirectory on the specified path.
)
Delete() Deletes the specified directory with all its contents.
GetDirectories() Returns an array of subdirectories within a specified
directory.
GetFiles() Method that returns a list of files in the given directory.

MoveTo() Public method that moves the directory along with its
contents to the new path.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
799
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Working with Directories
using System;
using System.IO;
class Test {
public static void Main() {
// Specify the directories you want to manipulate.
DirectoryInfo di = new DirectoryInfo(@“D:\MyDir");
try {
// Determine whether the directory exists.
if (di.Exists){
// Indicate that it already exists.
Console.WriteLine("That path exists already.");
return; }
// Try to create the directory.
di.Create();
Console.WriteLine("The directory was created successfully.");
// Delete the directory.
di.Delete();
Console.WriteLine("The directory was deleted successfully.");}
catch (Exception e){
Console.WriteLine("The process failed: {0}", e.ToString());
} finally {} }}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
800
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating and Deleting Subdirectories

using System;
using System.IO;
public class CreateSubTest {
public static void Main() {
// Create a reference to a directory.
DirectoryInfo di = new DirectoryInfo("TempDir");
// Create the directory only if it does not already exist.
if (di.Exists == false)
di.Create();
Console.WriteLine("Directory "+di.Name+"successfully created");
// Create a subdirectory in the directory just created.
Console.WriteLine("Sub directory "+dis.Name +" created within
"+di.Name+" directory ");
DirectoryInfo dis = di.CreateSubdirectory("SubDir");
// Delete the subdirectory.
dis.Delete(true);
//To view the subdirectories comment out the delete statements
// Delete the directory.
di.Delete(true);
}}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
801
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Finding the No. of subdirectories within specfied
directory
using System;
using System.IO;
class Test {
public static void Main() {
try {
DirectoryInfo di = new DirectoryInfo(@"c:\");
// Get only subdirectories that contain the letter "p."
DirectoryInfo[] dirs = di.GetDirectories("*p*");
Console.WriteLine("The number of directories containing the
letter p is {0}.", dirs.Length);
foreach (DirectoryInfo diNext in dirs) {
Console.WriteLine("The number of files in {0} is {1}",
diNext,
diNext.GetFiles().Length); } }
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
802
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Moving Directories
using System;
using System.IO;
public class MoveToTest
{ public static void Main()
{ // Make a reference to a directory.
DirectoryInfo di = new DirectoryInfo("TempDir");
// Create the directory only if it does not already
exist.
if (di.Exists == false)
di.Create();
// Create a subdirectory in the directory just created.
DirectoryInfo dis = di.CreateSubdirectory("SubDir");
// Move the main directory. Note that the contents move with the
directory.
if (Directory.Exists("NewTempDir") == false)
di.MoveTo("NewTempDir");
try {
// Delete the subdirectory.It has been moved, an exception is
thrown.
dis.Delete(true); }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
803
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Moving Directories
catch (Exception) {
// Handle this exception in some way, such as with the
following code:
Console.WriteLine("That directory does not exist."); }
// Point the DirectoryInfo reference to the new
directory.
//di = new DirectoryInfo("NewTempDir");
// Delete the directory.
//di.Delete(true);
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
804
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Working with Files
File class and the FileInfo class are used for typical operations such as copying,
moving, renaming, creating, opening, deleting, and appending to files.
Like the methods of Directory, all the File methods are static; and like
DirectoryInfo, all the methods of FileInfo are instance methods.
To customize the behavour of various file methods, the following enumerations are
used:

FileAccess Specifies read and write access to a file. Can have


Read(Numeric Value 1) ,Write (Numeric Value 2) and
ReadWrite (Numeric Value 3) members.

FileShare Specifies the level of access permitted for a file that is


already in use. Can have Inheritable (Numeric value
16) ,None (Numeric value 0),Read (Numeric value 1)
,ReadWrite (Numeric value 3),Write (Numeric value 2)
members
FileMode Specifies whether the contents of an existing file are
preserved or overwritten, and whether requests to create
an existing file cause an exception.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
805
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Synchronous and Asynchronous IO

Synchronous I/O means that the method is blocked until


the I/O operation is complete, and then the method
returns its data.
With asynchronous I/O, a user can call BeginRead() or
BeginWrite(). The main thread can continue doing other
work, and later the user will be able to process the data.
Also, multiple I/O requests can be pending
simultaneously.
With large files, or when reading or writing across the
network, you'll want asynchronous I/O,which allows you
to begin a read and then turn your attention to other
matters while the CommonLanguage Runtime (CLR)
fulfills your request. The .NET Framework provides
asynchronous I/O through the BeginRead( ) and
BeginWrite( ) methods of Stream.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
806
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FileMode enumeration members
Member Name Description
Append Opens the file if it exists and seeks to the end of the file, or
creates a new file. FileMode.Append can only be used in
conjunction with FileAccess.Write. Any attempt to read fails
and throws an ArgumentException.
Create Specifies that the operating system should create a new
file. If the file already exists, it will be overwritten.

CreateNew Specifies that the operating system should create a new


file. If the file already exists, an IOException is thrown.

Open Specifies that the operating system should open an existing


file. The ability to open the file is dependent on the the
value specified by FileAccess.
OpenOrCreate Specifies that the operating system should open a file if it
exists; otherwise, a new file should be created

Truncate Specifies that the operating system should open an existing


file. Once opened, the file should be truncated so that its
size is zero bytes.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
807
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Exploring the File Class

Method Description
Create() Creates a new file at the specified path.

CreateText() Creates a StreamWriter to append text to a specified file.

Delete() Deletes a specified file.


Copy() Copies the contents of an existing file to a new file.
Exists() Returns a boolean value true if the given file exists.

OpenRead() Opens a file using FileStream.

OpenWrite() Opens the file for writing using the FileStream.

GetLastAccessTime() Returns or sets the last time the specified file was
SetLastAccessTime() accessed.
GetLastWriteTime() Returns or sets the last time the specified file was written
SetLastWriteTime() to.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
808
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Exploring the FileInfo class
Method/Property Description

Atrributes() Gets or sets the attributes of the current file.

Directory Returns the name of parent directory.

Length Gives the size of the current file.


Name Gives the name of the current file.
Extension Gives the file extension of the current file.

AppendText() Creates a StreamWriter that appends text to a file.

MoveTo() Moves a file to the new location.Used for renaming.

OpenRead() Creates a read only FileStream.

OpenText() Creates a StreamReader to read from an existing file.

OpenWrite() Creates a Read/Write FileStream.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
809
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Working with Files
The following FileStream constructor opens an existing
file (FileMode.Open).
[Visual Basic]
Dim s2 As New FileStream(name, FileMode.Open,
FileAccess.Read, FileShare.Read)
[C#]
FileStream s2 = new FileStream(name, FileMode.Open,
FileAccess.Read, FileShare.Read);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
810
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Working with File Class methods
using System;
using System.IO;
class Test
{ public static void Main()
{
string path = "d:\\Testing.txt";
FileInfo fi1 = new FileInfo(path);
if (!fi1.Exists)
{ //Create a file to write to.
using (StreamWriter sw = fi1.CreateText())
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
} }
//Open the file to read from.
using (StreamReader sr = fi1.OpenText())
{ string s = "";
while ((s = sr.ReadLine()) != null)
{ Console.WriteLine(s); }
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
811
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Working with File class methods
(Contd..)
try {
string path2 = path + "temp";
FileInfo fi2 = new FileInfo(path2);
//Ensure that the target does not exist.
fi2.Delete();
//Copy the file.
fi1.CopyTo(path2);
Console.WriteLine("{0} was copied to {1}.", path,
path2);
//Delete the newly created file.
fi2.Delete();
Console.WriteLine("{0} was successfully deleted.",
path2);
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
812
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Readers and Writers
System.IO namespace provides reader and writer classes to read and write
data in different formats.
The following type of reader and writer classes are available.

• BinaryReader andBinaryWriter:
** Reads and Writes primitive data types as binary values in a specific
encoding.
** Important methods are Read( ), Write( ),BeginRead( ), BeginWrite( ),
and Flush( ).

• StreamReader and StreamWriter.


** StreamReader is designed for character input in a particular
encoding .
** StreamReader is used for reading lines of information from a
standard text file.
**StreamWriter is designed for character output in a particular Encoding,
whereas classes derived from Stream are designed for byte input and
output.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
813
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Readers and Writers (Contd..)
TextReader and TextWriter.

** TextReader and TextWriter are the abstract base class of


StringReader and StringWriter, which read characters from streams
and strings, respectively.
** While TextReader opens a text file for reading a specified range of
characters .
** An instance of TextWriter is used to write an object to a string,
write strings to a file, or to serialize XML.
BufferedStream –Read and Write :
** A buffered stream object allows the operating system to create
its own internal buffer, and read bytes to and from the backing
store.
** The buffer is filled from the in-memory buffer, not from the
backing store.
** The net effect is that the input and output are more efficient
and thus faster.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
814
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Working with BinaryReader and BinaryWriter
using System;
using System.IO;
class MyStream {
private const string FILE_NAME = "Test.data";
public static void Main(String[] args) {
// Create the new, empty data file.
if (File.Exists(FILE_NAME)){
Console.WriteLine("{0} already exists!", FILE_NAME);
return; }
FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew);
// Create the writer for data.
BinaryWriter w = new BinaryWriter(fs);
// Write data to Test.data.
for (int i = 0; i < 11; i++) {
w.Write( (int) i); }
w.Close();
fs.Close();
// Create the reader for data.
fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
// Read data from Test.data.
for (int i = 0; i < 11; i++) {
Console.WriteLine(r.ReadInt32()); }
w.Close(); }}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
815
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Working with StreamReader and StreamWriter

using System;
using System.IO;
class Test
{ public static void Main()
{
// Create an instance of StreamWriter to write text to a file.
StreamWriter sw = new StreamWriter("TestFile.txt");
// Add some text to the file.
sw.Write("This is the ");
sw.WriteLine("header for the file.");
sw.WriteLine("-------------------");
// Arbitrary objects can also be written to the file.
sw.Write("The date is: ");
sw.WriteLine(DateTime.Now);
sw.Close();
StreamReader sr=new StreamReader("TestFile.txt");
while(sr.Peek()> -1) {
Console.WriteLine(sr.ReadToEnd()); }
} }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
816
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Working with TextReader and TextWriter
using System;
using System.IO;
public class TextToFile
{
private const string FILE_NAME = "MyFile.txt";
public static void Main(String[] args)
{
if (File.Exists(FILE_NAME)){
Console.WriteLine("{0} already exists.", FILE_NAME);
return; }
StreamWriter sr = File.CreateText(FILE_NAME);
sr.WriteLine ("This is my file.");
sr.WriteLine ("I can write ints {0} or floats {1}, and so on.",
1,4.2);
sr.Close();
StreamReader sr = File.OpenText(FILE_NAME);
String input;
while ((input=sr.ReadLine())!=null){
Console.WriteLine(input); }
Console.WriteLine ("The end of the stream has been reached.");
sr.Close();
}
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
817
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Working with Buffered Streams
using System;
using System.IO;
class Tester {
const int SizeBuff = 1024;
public static void Main( ) {
// make an instance and run it
Tester t = new Tester( );
t.Run( ); }
// Set it running with a directory name
private void Run( )
{ // create binary streams
Stream inputStream = File.OpenRead(@"D:\testing.txt");
Stream outputStream = File.OpenWrite(@"D:\testing.bak");
// add buffered streams on top of the binary streams
BufferedStream bufferedInput =new BufferedStream(inputStream);
BufferedStream bufferedOutput =new BufferedStream(outputStream);
byte[] buffer = new Byte[SizeBuff];
int bytesRead;
while ( (bytesRead =bufferedInput.Read(buffer,0,SizeBuff)) > 0 ) {
bufferedOutput.Write(buffer,0,bytesRead); }
bufferedOutput.Flush( );
bufferedInput.Close( );
bufferedOutput.Close( ); } }
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
818
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Do it yourself (DIY)
Create a menu driven console application to
1. Accept the employee detail such as
name,empNo,location,department and write the
details to a file.
2. Search for a particular record based upon the empNo
and display the specified record on the console else
display a failure message.
3. Append details to the file.
4. Delete a specified record based upon the empNo.
5. Move the file to another specified location.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
819
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Serialization

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
• Understanding Serialization
• Serialization-Default
• Binary Serialization.
• Soap / XML Serialization.
• Selective Serialization.
• Custom Serilaization.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
821
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Serialization
Persisting the state of an object to a storage medium so
that the object could be resurrected later
Used to pass objects (by value) from one app-domain
to another (even across machines)

• Used for saving session state in ASP.Net


• To copy object to and from clip board in windows
forms

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
822
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Serialization
Persisting the state of an object to a storage medium so
that the object could be resurrected later
Used to pass objects (by value) from one app-domain
to another (even across machines)

• Used for saving session state in ASP.Net


• To copy object to and from clip board in windows
forms

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
823
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Serialization – Default
Any class that needs to be serialized must be marked
with “Serializable” attribute
[Serializable] //Attribute required
class Kid
{
//Other code - Unchanged
}

Two types of serialization


• Binary
• Soap (XML)

Based on the type a formatter is used (BinaryFormatter


or SoapFormatter)
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
824
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Binary Formatter
Kid k1 = new Kid("George", 11);
//Write to the file
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("Kids.bin",
FileMode.Create, FileAccess.Write,
FileShare.None);
formatter.Serialize(stream,k1); //Write Kid to file
stream.Close();
//Reading from file
IFormatter formatterR = new BinaryFormatter();
Stream streamR = new FileStream("kids.bin",
FileMode.Open, FileAccess.Read,
FileShare.Read);
//Read Kid from file
Kid k2 = (Kid)formatterR.Deserialize(streamR);
streamR.Close();
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
825
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Serialization
For the code to work add the following namespaces :
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

For Soap formatting ( XML ) the namespaces are :


using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;

And reference to
System.Runtime.Serialization.Formatters.Soap.dll
assembly

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
826
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Serialization – Soap / XML
Kid[] kids = { new Kid("Craig", 11),
new Kid("David", 9)};

IFormatter formatter = new SoapFormatter();


Stream stream = new FileStream("Kids.xml",
FileMode.Create, FileAccess.Write,
FileShare.None);
formatter.Serialize(stream,kids);
stream.Close();

IFormatter formatterR = new SoapFormatter();


Stream streamR = new FileStream("kids.xml",
FileMode.Open, FileAccess.Read,
FileShare.Read);
Kid[] kids2 = (Kid [])formatterR.Deserialize(streamR);
streamR.Close();
foreach (Kid k2 in kids2)
Console.WriteLine("{0}", k2);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
827
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Selective Serialization
If you don’t want to store some state variables of the
object mark the variables with
[NonSerialized] attribute

[Serializable]
public class MyObject
{
public int n1;
[NonSerialized] public int n2;
public String str;
}

Only n1 and str are stored and restored!

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
828
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Custom Serialization
The default serialization works using reflection and hence
It will access the private state variables and construct by
not using the constructors
If we want to change the way objects are stored
• With different field names (so that the files could be
viewed with another application)
• A Different XML tag set ( interoperability of different
applications)
Custom serialization needs to be used

Done by implementing ISerializable interface!


public void GetObjectData(SerializationInfo info,
StreamingContext context)
Used while serializing the object.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
829
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Custom Serialization
public void GetObjectData(SerializationInfo info,
StreamingContext context)
{
info.AddValue("Name", this.name);
info.AddValue("Age", this.age);
}

To help DeSerialization provide a constructor :


public Kid(SerializationInfo info, StreamingContext context)
{
this.Name = info.GetString("Name");
this.Age = info.GetInt32("Age");
}

Exercise : Provide custom serialization for the


product class, Load products from a file in
catalog’s private constructor
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
830
Thank You

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DOTNET Part II

COE – Current Technologies


Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ADO.NET 2.0

COE – Current Technologies


Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
* For internal use only
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Index
1) Overview of ADO.NET
2) ADO.NET Components
3) ADO.NET and the .NET Framework
4) ADO.NET Architecture
5) A Simple DataGridView - Demo
6) ADO.NET objects
7) Execute Scalar
8) The DataReader
9) The DataSet
10)DataSet Enhancements
11)XML and the DataSet
12)Using Data Set - Demo

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
834
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Index
13)The DataTable
14)The DataRelation
15)The DataView
16)DataBinding
17)DataSet Serialization
18)Bulk Copy Operation
19)Batch Update
20)Data Paging
21)DataTable's Load and Save Methods
22)DbProvidersFactories Class
23)Asynchronous Execution
24)ADO.net Best Practices

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
835
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Overview of ADO.NET

ADO.NET provides consistent access to data sources such as


Microsoft SQL Server and XML, as well as to data sources
exposed through OLE DB and ODBC.

ADO.NET separates data access from data manipulation into


discrete components that can be used separately or in tandem.

ADO.NET includes .NET Framework data providers for connecting


to a database, executing commands, and retrieving results.

Those results are either processed directly, placed in an


ADO.NET DataSet object in order to be exposed to the user in an
ad hoc manner, combined with data from multiple sources, or
remoted between tiers.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
836
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Overview of ADO.NET

The ADO.NET DataSet object can also be used independently


of a .NET Framework data provider to manage data local to
the application or sourced from XML.

The ADO.NET classes are found in System.Data.dll, and are


integrated with the XML classes found in System.Xml.dll.
When compiling code that uses the System.Data namespace,
reference both System.Data.dll and System.Xml.dll

ADO.NET provides functionality to developers writing


managed code similar to the functionality provided to native
component object model (COM) developers by ActiveX Data
Objects (ADO).

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
837
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Features of ADO.NET
Disconnected Data Access
XML Serializable
Data source Independence
XSD
Data Set as a “Relational Data Store”
Transaction Support
The Base-Class-Based Provider Model.
Connection Pooling Enhancements.
Asynchronous Commands.
Bulk Import
Provider Statistics
AttachDbFileName
SQL Server 2005-Specific Features in SqlClient

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
838
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Database connectivity through
ADO.NET
Traditional Data Access Architecture

                                                                                                                                        
ADO.Net Disconnected Data Access Architecture

                                                                                                                                     

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
839
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ADO.NET Components
There are two components of ADO.NET that you
can use to access and manipulate data:

.NET Framework data providers

The DataSet

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
840
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
.NET Framework Data Providers

The .NET Framework Data Providers are components that have


been explicitly designed for data manipulation and fast,
forward-only, read-only access to data. The Connection object
provides connectivity to a data source.

The Command object enables access to database commands to


return data, modify data, run stored procedures, and send or
retrieve parameter information.

The DataReader provides a high-performance stream of data


from the data source. Finally, the DataAdapter provides the
bridge between the DataSet object and the data source. The
DataAdapter uses Command objects to execute SQL commands
at the data source to both load the DataSet with data, and
reconcile changes made to the data in the DataSet back to the
data source.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
841
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataSet

The ADO.NET DataSet is explicitly designed for data access


independent of any data source. As a result, it can be used
with multiple and differing data
sources, used with XML data, or used to manage data local
to the application.

The DataSet contains a collection of one or more DataTable


objects made up of rows and columns of data, as well as
primary key, foreign key, constraint, and relation
information about the data in the DataTable objects.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
842
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ADO.NET and the .NET Framework

Microsoft .NET Framework

Web Services User Interface

Data and XML


ADO.NET XML ... ...

Base Classes

Common Language Runtime

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
843
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ADO.NET namespace hierarchy
• Organizes the object model
• Includes:
System.Data
System.Data.OleDb
System.Data.Common
System.Data.SqlClient
System.Data.SqlTypes

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
844
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
System.Data Namespace

Contains the basis and bulk of ADO.NET


Data-centric namespace
Provides the means to work on and with
your data!
Classes and methods to manipulate your data
Ability to create views of your data
Means to logically represent your data
Enables the use of XML to view, share, and store
data

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
845
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ADO.NET Architecture

Presentation Tier
Windows Forms
MyApp.Exe

DataSet

Business Tier Data Tier


Web Forms Internet
Intranet Data Object (Class)
IE
Data Adapter
DataSet
XML
DataSet
Data Adapter

Business to Business

(BizTalk, for example)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
846
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ADO.NET Architecture

A connection object establishes the connection for the application with the database. The command
object provides direct execution of the command to the database. If the command returns more than a
single value, the command object returns a DataReader to provide the data. Alternatively, the
DataAdapter can be used to fill the Dataset object. The database can be updated using the command
object or the DataAdapter.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
847
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ADO.NET objects
Basic ADO.NET objects

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
848
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ADO.NET object Model

ADO.NET object Model

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
849
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
850
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

> Choose
DataSource

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
851
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

> View Button

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
852
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

> Choose
SqlServerDataSource

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
853
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
854
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

> View
ServerExplorer

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
855
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

> Set Identity

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
856
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

> Save Table

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
857
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
858
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

> Include Password


in ConectionString

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
859
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
860
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
861
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
862
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

> Auto Size Property

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
863
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
864
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo
> Execute Query

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
865
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

> Add New Record

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
866
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

> Create a
DataTable

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
867
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
868
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

> Choose DataType


for Coloumn

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
869
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

> Set RelationShip

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
870
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
A Simple DataGridView - Demo

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
871
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introducing the Objects…

Contains the “main” classes of


System.Data ADO.NET
DataSet In-memory cache of data
DataTable In-memory cache of a database
DataRow table
DataColumn Used to manipulate a row in a
DataTable
DataRelation
Used to define the columns in a
DataViewManager
DataTable
Used to relate 2 DataTables to each
other
Used to create views on DataSets
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
872
ADO.NET objects
Core objects

Connection - Establishes a connection to a database.

Command - Represents an individual SQL statement


that can be executed against the database.

Data reader - Provides read-only, forward-only access


to the data in a database.

Data adapter - Provides the link between the


command and connection objects and a dataset object

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
873
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Connection object
Specifies what data source to connect to
ConnectionString property
Database connections will directly affect
application scalability
Keep connection open for as little time as
possible
Connections are pooled automatically (can
override)

Make sure connection strings are spelled


exactly alike

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
874
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Connection code

public void DoConnect()


{
String connectionString = “”;
connectionString =
“server=P3C20014;uid=sa;pwd=pwd;database=rOY”
SqlConnection conn = new SqlConnection(connectionString);
try
{
conn.Open();
}
catch (Exception e)
{
// Handle and log error
}
finally
{
conn.Close();
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
875
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Command Object
Issues and executes commands on the data store
CommandText – Command to run against data source
CommandType – Type of command (stored proc)
Exposes overloaded constructors to allow customization at
initial object creation
Parameters collection – Pass in parameter objects
ExecuteReader
Executes a query and returns a DataReader
Use CommandBehavior enum to close underlying
connection
ExecuteNonQuery
Executes a query but returns no data
ExecuteScalar
Executes and returns a single value
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
876
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Command Code

String connectionString = “”;


connectionString =
“server=localhost;uid=sa;pwd=pwd;database=Northwind”
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(“<SP Name>", conn);
cmd.CommandType = CommandType.StoredProcedure;
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{ // Handle and log error
}
finally
{
conn.Close();
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
877
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Command Parameters

String connectionString = “”;


connectionString =
“server=P3C20014;uid=sa;pwd=sa;database=Roy”
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new
SqlCommand(“sp_listproductsbycategory", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@categoryid", 1);

SqlParameter parm = New SqlParameter("@categoryid", 1)


cmd.Parameters.Add(parm);

SqlParameter parm2 = new SqlParameter("@categoryid",


SqlDbType.Int, 4);
parm2.Value = 5;
cmd.Parameters.Add(parm2);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
878
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataReader Object

Fast, read-only, forward-only, connected method


for data extraction
Does not support scrolling or updating
Supports databinding to controls
DataReader is not creatable
It’s returned as the result of executing an
appropriate method of a Command object
Close connection automatically with
CommandBehavior enumeration

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
879
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataReader Code

String connectionString = “”;


connectionString =
“server=p3c20014;uid=sa;pwd=sa;database=Roy”
SqlConnection con = new new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("CustomerByCountry",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new
SqlParameter("@publications",SqlDbType.Int)).Value = 3;
con.Open();
ArrayList al = new ArrayList();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read()) {
object[] values = new object[dr.FieldCount];
dr.GetValues(values);
al.Add(values);
}
dr.Close();
con.Close();

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
880
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataAdapter Object

Knows how to load a table from a


DataAdapter
DataStore and write changes Connection
Exposes two methods:
Connection
Fill (DataSet and Table)
Update (DataSet and Table) SelectCommand
SelectCommand
Provides mappings between
tables and columns
UpdateCommand
Users can provide explicit
insert/update/delete commands InsertCommand
InsertCommand
Such as, specify stored
procedures
DeleteCommand
DeleteCommand
Allows single DataSet to be
populated from multiple
data sources
TableMappings
Support for ADO RecordSet

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
881
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataSet Object
Disconnected, feature-rich method for
data access
Relational views of data DataSet

Contains tables, columns, rows, Tables

constraints, Table

views and relations Columns

Read/Write XML/XSD Column


Constraints
Disconnected model
Constraint
Has no knowledge of data source Rows
Strong typing Row
Supports data binding Relations

Supports batch updates Relation

Connects to data source via


DataAdapter

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
882
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataAdapter/DataSet Code

using System;
Using System.Data;
Using System.Data.SqlClient;
Namespace CodeExample{
Class Example{
static void Main(string[] args){
SqlConnection conn = new SqlConnection("data source=p3c20014;initial
catalog=Northwind;UserId = sa; pwd=sa;“
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("select * from Customers",
conn);
da.Fill(ds, “Customers");
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
883
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML and ADO.NET
ADO.NET leverages the power of XML to provide
disconnected access to data. ADO.NET was
designed hand-in-hand with the XML classes in
the .NET Framework both are components of a
single architecture.

ADO.NET and the XML classes in the .NET


Framework converge in the DataSet object.

The DataSet can be populated with data from


an XML source, whether it is a file or an XML
stream.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
884
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Database connectivity through ADO.NET

ADO.NET:
ADO.NET: Data
Data and
and XML
XML

System.Data System.Xml

OleDb SqlClient XSL


Serialization
Common SQLTypes XPath

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
885
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Putting the Objects Together…

DataSet Tables
DataTable DataView
DataRow(s)

Relations DataColumn

DataRelation Constraint(s) DataViewManager


DataRelation
DataTable

DataTable

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
886
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Putting the Objects Together…

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
887
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Execute Scalar Method 
Executes the query, and returns the first
column of the first row in the result set
returned by the query.
Additional columns or rows are ignored.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
888
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Execute Scalar - Demo

private void CmdDisp_Click(object sender, System.EventArgs e)


{
string strConst ="Server=s2b21675;user
id=sa;pwd=sa;Database=pubs";
SqlConnection objSql=new SqlConnection();
objSql.ConnectionString=strConst;
string strQry="Select count(*) from titles where type
='"+TxtTitle.Text+"'";
SqlCommand objCmd=new SqlCommand(strQry,objSql);
objCmd.CommandType= CommandType.Text;
int reportVal=0;
try
{
objCmd.Connection.Open();
reportVal=(int )objCmd.ExecuteScalar();
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
889
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Execute Scalar - Demo

catch(SqlException exc)
{
MessageBox.Show(exc.Message);
}
finally
{
if(objSql.State ==ConnectionState.Open)
{
objSql.Close();
}
}
MessageBox .Show("The title of type "+TxtTitle.Text+" are
"+reportVal);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
890
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
The Data Reader

The DataReader provides a forward-only, read-only, connected


stream recordset from a database.

Unlike other components of the Data Provider, DataReader objects


cannot be directly instantiated. Rather, the DataReader is returned
as the result of the Command object's ExecuteReader method.

The SqlCommand.ExecuteReader method returns a SqlDataReader


object, and the OleDbCommand.ExecuteReader method returns an
OleDbDataReader object.

The DataReader can provide rows of data directly to application


logic when you do not need to keep the data cached in memory.
Because only one row is in memory at a time, the DataReader
provides the lowest overhead in terms of system performance but
requires the exclusive use of an open Connection object for the
lifetime of the DataReader.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
891
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Using Data Reader - Demo

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
892
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Using Data Reader - Demo

private void Reader_Load(object sender, System.EventArgs e)


{
string strConn = "Data
Source=p3c20037;uid=sa;pwd=sa;Initial Catalog=pubs";
SqlConnection objConn = new
SqlConnection(strConn);
string str = "Select * from titles";

SqlCommand objCom = new SqlCommand(str,objConn);


objCom.CommandType=CommandType.Text;
SqlDataReader dr = null;

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
893
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Using Data Reader - Demo

try
{
if(objConn.State==ConnectionState.Closed)
{
objConn.Open();
dr=objCom.ExecuteReader();
while(dr.Read())
{

comboBox1.Items.Add(dr["title_id"].ToString());
}
dr.Close();

}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
894
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Using Data Reader - Demo

catch(SqlException objs)
{
throw objs;
}
finally
{
dr.Close();
if(objConn.State==ConnectionState.Open)
{
objConn.Close();
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
895
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataReader's Execute Methods
DataReader's Execute Methods

Besides the ExecuteNonQuery, ExecuteReader,


ExecuteScaler, and ExecuteXmlReader, the new
execute methods are ExecutePageReader,
ExecuteResultSet, and ExecuteRow.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
896
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
The DataSet

An in-memory cache of data from a data source


Common way to represent and manipulate data
Universal data container
Not just for use with databases
Logical or physical representation of data
Designed to be disconnected from the data
source
Connect, execute query, disconnect
Can use XML
To read and write data
To read and write XMLSchema

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
897
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Typed vs. Untyped Datasets

Data can be loaded into a DataSet at runtime


without having to specify the structure
beforehand.
Have to access fields by “string” that is,
myDataSet.myTable[0][“SomeColumn”]
This is called an Untyped Dataset
Alternative is to use Visual Studio to predefine
the structure and relationships (visually of
course)
This approach is called a Typed DataSet

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
898
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Typed Datasets

Typed Datasets are great!


Means that the table, field and data types are
available at design time.
This leads to huge benefits:
Compile time type checking – can’t put string in int field.
Compiler will spot incorrect spellings as the type won’t
exist
Best of all: tooltip/autocomplete in IDE

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
899
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Typed vs. Untyped - Example

Accessing data in an untyped dataset:

foreach ( DataRow row in myDataSet.Tables[ “MyTable” ] )


{
myStringValue = (String)row[ “MyColumnName” ];
}

Accessing data in a typed dataset:

Foreach ( MyTableRow row in myDataSet.MyTable )


{
myStringvalue = row.MyColumnName;
}

No casting necessary - Clearer to read

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
900
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataSet Enhancements

Performance
Performanceand
andscalability
scalabilityimprovements
improvements
•• Internal
InternalIndexing
Indexingof
ofRows
Rows
Inserts
Insertsand
anddeletes
deletesmuch
muchfaster
faster
Updates
Updatesalmost
almostconstant
constant
Selects
Selectsare
arefaster
fastertoo
too
•• Binary
BinarySerialization
Serializationof
ofContents
Contents
VV1.x
1.xDataSet
DataSetalways
alwaysserialized
serializedtotoXML
XML
Binary
Binaryserialization
serializationan
anoption
optionininVV2.0
2.0

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
901
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataSet Enhancements

More
MoreLoading
LoadingOptions
Options
•• DataAdapter.Fill
DataAdapter.Fill
DataAdapter.FillLoadOption
DataAdapter.FillLoadOption
LoadOptions.OverwriteChanges
LoadOptions.OverwriteChanges
LoadOptions.PreserveChanges
LoadOptions.PreserveChanges
LoadOptions.Upsert
LoadOptions.Upsert

DataSet theSet = new DataSet();

SqlDataAdapter da =
new SqlDataAdapter("SELECT * FROM Customers", "...");

da.FillLoadOption = LoadOption.OverwriteChanges;
da.Fill(theSet, "Customers");

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
902
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataSet Enhancements

DataSet.Load
Load from DataReader directly
FillErrorEventHandler to handle loading errors
Also supports LoadOptions

Stream data From DataSet


DataSet.GetDataReader method
returns a DataTableReader

RowState values are now updateable


DataRow.SetAdded and DataRow.SetModified

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
903
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML and the DataSet
DataSet can read/write XML for its data and/or schema
• You can create or modify data in a DataSet using XML
• You can create or modify the DataSets schema using
XML
XML-related DataSet methods for reading:
• ReadXml: Reads an XML schema and data into the
DataSet
• ReadXmlSchema: Reads an XML schema into the
DataSet
And for writing:
• WriteXml, WriteXmlSchema
• GetXml, GetXmlSchema
Namespace property: sets the namespace for serialization
Full support for SQL Server-style DiffGrams

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
904
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Using Data Set - Demo

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
905
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Using Data Set - Demo

private void Grid_Load(object sender, System.EventArgs e)


{
string str="Server=p3c20014;user
id=sa;pwd=sa;Initial Catalog=pubs";
SqlConnection obj=new SqlConnection(str);
string strcmd="select * from titles";
SqlDataAdapter objAdapter=new
SqlDataAdapter(strcmd,obj);
DataSet ds=new DataSet();
try
{
obj.Open();
objAdapter.Fill(ds);
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
906
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Using Data Reader - Demo

catch(SqlException e1)
{
MessageBox.Show(e1.Message);
}
finally
{
if(obj.State==ConnectionState.Open)
obj.Close();
dataGrid1.DataSource=ds.Tables[0].DefaultView;
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
907
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
The DataTable

May be mapped to a physical table in the data


source
Can be related to one another through
DataRelations
Optimistic concurrency or locking - model
Properties of Interest:
Columns: Returns ColumnsCollection of DataColumns
Rows: Returns DataRow objects as a RowsCollection
ParentRelations: Returns the RelationsCollection
Constraints: Returns the table’s ConstraintsCollection
DataSet: Returns the DataSet of the DataTable
PrimaryKey: Gets the DataColumns that make up the
table’s primary key
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
908
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataSet and DataTable

Create a DataTable and add it to a DataSet

DataSet ds = new DataSet();

DataTable dt= new DataTable( “Customers” );


DataColumn dc;
dc = new DataColumn( “CustID”, Type.GetType("System.Int16"));
dt.Columns.Add( dc );
dt.Columns.Add( “First_Name”,Type.GetType("System String”));
dt.Columns.Add( “Last_Name”, Type.GetType("System String”));

ds.Tables.Add( dt );

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
909
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataTable

First
FirstClass
ClassSupport
Support
DataSet
DataSetoperations
operationsnow
nowavailable
availableon
onDataTable:
DataTable:
ReadXml/WriteXml
ReadXml/WriteXml
ReadXmlSchema/WriteXmlSchema
ReadXmlSchema/WriteXmlSchema
Clear
Clear
Clone
Clone
Copy
Copy DataTable tbl = new DataTable();
Merge
Merge
// Fill the table
GetChanges
GetChanges
DataTable newTbl = tbl.Clone();

tbl.Merge(newTbl);

DataTable changes = tbl.GetChanges();

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
910
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataTable

DataSet not Required


DataAdapters
Fill(DataTable)
Update(DataTable)
DataReader

DataTable.Load(DataReade
r)
Stream from a DataTable

DataTable.GetTableReader(
)
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
911
The DataRelation

Used to create logical relations between your


data
Create relations between two (2) DataTable objects
Requires a DataColumn object from each DataTable
The DataType of both DataColumns must be the same
Cannot relate a Int32 DataColumn and a String
DataColumn
The relation is named (by you!)
DataRelation dr=new DataRelation( “myRelation”,...)
Makes relational navigation possible
RelationsCollection used to hold/group them
Accessed through the DataSet’s Relations property

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
912
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Methods of Reading and Writing XML

String oFile = “C:\\My_ADO.NET\\myXmlOutput.xsd”;


String iFile = “C:\\My_ADO.NET\\myXmlInput.xsd”;

mds.WriteXmlSchema( oFile );
mds.ReadXml( iFile);

mds.WriteXml( "C:\\My_ADO.NET\\myXmlData.txt",
XmlWriteMode.DiffGram);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
913
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
The DataView

Create multiple views on DataTable objects


Bindable to user interface controls
Properties of Interest:
Table: Retrieves or sets the associated DataTable
Sort: Gets or sets the table’s sort columns and sort
order
RowFilter: Gets or sets the expression used to filter
rows
RowStateFilter: Gets or sets the row state filter
None, Unchanged, New, Deleted, ModifiedCurrent,
and others

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
914
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating a DataView

DataView view1 = new DataView( myTable );


DataView view2 = new DataView( myTable );

view1.Sort = “Name ASC”;

view2.RowStateFilter= DataViewRowState.ModifiedOriginal;

DataGrid myGrid = new DataGrid();


myGrid.SetDataBinding( view1, “Customer”);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
915
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataView Enhancements

DataView.ToTable
DataView.ToTable
Creates
Createsaanew
newDataTable
DataTablefrom
fromaaDataView
DataView
Supports
SupportsDistinct
Distinctand
andColumn
ColumnFiltering
Filtering

DataTable filtered =
view.ToTable(true, "CompanyName", "ContactName");

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
916
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Using DataTable and DataView -
Demo

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
917
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Using DataTable and DataView -
Demo

private void SortData_Load(object sender, System.EventArgs e)


{
comboBox1.Items.Add("Ascending");
comboBox1.Items.Add("Descending");

string strConn = "Data Source=p3c20014;uid=sa;pwd=sa;Initial


Catalog=pubs";

SqlConnection objConn = new SqlConnection(strConn);

string strQry = "select distinct(type) from titles";

SqlCommand objCom = new SqlCommand(strQry,objConn);

objCom.CommandType=CommandType.Text;

SqlDataReader dr = null;

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
918
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Using DataTable and DataView -
Demo

try
{
if(objConn.State==ConnectionState.Closed)
{
objConn.Open();
dr=objCom.ExecuteReader();
while(dr.Read())
{

comboBox2.Items.Add(dr[0].ToString());
}
dr.Close();

}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
919
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Using DataTable and DataView -
Demo

catch(SqlException objs)
{
throw objs;
}
finally
{
dr.Close();
if(objConn.State==ConnectionState.Open)
{
objConn.Close();
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
920
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataViewManager

Similar to a DataView but DataSet oriented


Used to create multiple views on a DataSet
Ability to automatically set filters on the tables
Properties of Interest:
DataViewSettings: Gets the DataView for on each
DataTable
DataSet: Gets or sets the DataSet to be viewed
CreateDataView method
Creates a DataView on a DataTable

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
921
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Set

DataSet Tables DataView


DataTable
DataViewManager
DataRow(s)

Relations DataColumn DataViewSettings

DataRelation Constraint(s) DataViewSetting

DataRelation DataViewSetting
DataTable

DataTable

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
922
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Insertion Through DataCommand -
Demo

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
923
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Insertion Through DataCommand - Example

private void cmdOk_Click(object sender, System.EventArgs e)

string strConnection="Server=p3c20014;user id=sa;pwd=sa;Initial


Catalog=roy";

SqlConnection objConnect=new SqlConnection(strConnection);

string strCmd=
"Insert into input(EmpId,EmpName,Department,BasicSal)
values(@Eid,@Ename,@Dept,@Esal)";

SqlDataAdapter objAd=new SqlDataAdapter(strCmd,objConnect);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
924
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Insertion Through DataCommand - Example

objAd.SelectCommand.Parameters.Add("@Eid",SqlDbType.Char,10,
"EmpId");
objAd.SelectCommand.Parameters["@Eid"].Value=textBox1.Text;

objAd.SelectCommand.Parameters.Add("@EName",SqlDbType.Char,10,
"EmpName");
objAd.SelectCommand.Parameters["@EName"].Value=textBox2.Text;

objAd.SelectCommand.Parameters.Add("@Dept",SqlDbType.Char,10,
"Dept");
objAd.SelectCommand.Parameters["@Dept"].Value=textBox3.Text;

objAd.SelectCommand.Parameters.Add("@Esal",SqlDbType.Char,10,
"ESal");
objAd.SelectCommand.Parameters["@ESal"].Value=textBox4.Text;

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
925
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Insertion Through DataCommand - Example

int resVal=0;
try
{
objConnect.Open();
resVal=objAd.SelectCommand.ExecuteNonQuery();
}
catch(SqlException ex)
{ MessageBox.Show(ex.Message); }
finally
{
if(objConnect.State==ConnectionState.Open)
objConnect.Close();
}
if(resVal==0)
{
MessageBox.Show("Data Insertion not completed");
}
else
{ MessageBox.Show(resVal+"row inserted "); }
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
926
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataBinding
DataBinding is the ability to link data to
objects. In practice, it is usually used to display
and manage data on a form from a database in
an easy way.
We can have a table with ten fields shown on a
form and the Data-Bindings would
automatically manage all the changes and
updates made to the fields.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
927
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataBinding

Windows Form controls can be bound to any data source, not just the traditional
database tables. Specifically, objects that implement the IList, IBindingListor, and
IEditableObject interface.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
928
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataBinding - Classes
Binding, BindingContext, BindingManagerBase, &
CurrencyManager

The Binding class represents a single data bind between a data


source and a control's property.

The BindingContext object is the top-most object in the binding


hierarchy and manages the BindingManagerBase objects that control
the interaction between a data source and the controls bound to it.
It only has one property, Item, that exposes its BindingManagerBase
collection.

The BindingManagerBase simply keeps track of the Binding objects


associated with a DataTable on the form. The CurrencyManager,
which inherits from the BindingManagerBase, tracks state
information and creates a cursor for the current record being shown .

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
929
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataBinding - Properties
The three most important properties, Count,
Position, and Current,
Note that the Current property returns a DataRowView which is
then cast to the strong-typed row from which it came.

BindingManagerBase bmb = this.BindingContext[dsMain,


"Contacts"];
Console.WriteLine("Number of Records: " + bmb.Count);
Console.WriteLine("Current Position: " + bmb.Position);
(returns a DataRowView) DataRowView drv = (DataRowView)
bmb.Current;
DataRow dsContacts.ContactsRow row =
(dsContacts.ContactsRow) drv.Row;
Console.WriteLine("Current Contact's Name: " + row.FirstName
+ " " + row.LastName);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
930
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataBinding - Methods
The important methods of a
BindingManagerBase are AddNew,
CancelCurrentEdit, EndCurrentEdit, and
RemoveAt.
When a new record is added. The new record is
not actually added to the DataTable until either
the position changes (invoking EndCurrentEdit)
or EndCurrentEdit is manually called.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
931
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataBinding - Methods

private void AddNewRecord()


{
BindingManagerBase bmb = this.BindingContext[dsMain, "Contacts"];

DialogResult result =
MessageBox.Show("Keep changes made to the current record?",
"", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes) bmb.EndCurrentEdit();
else bmb.CancelCurrentEdit();
bmb.AddNew();
dsContacts.ContactsRow row =
(dsContacts.ContactsRow) ((DataRowView) bmb.Current).Row;

Console.WriteLine(row.RowState);
bmb.EndCurrentEdit();

Console.WriteLine(row.RowState);
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
932
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataBinding - Events

The two important events in the


BindingManagerBase are PositionChanged,
which lets you know when the cursor is moved,
and CurrentChanged that raises when the
current record is being edited.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
933
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ADO.NET: DataRow States
Each DataRow in a DataTable contains state information in
a RowState property. This is how the system keeps track of
the changes made so that they can be accepted or rejected
and saved back to a database.
Here are descriptions of the DataRowState enumerations.

DataRowState.Added
This row is newly added to the dataset. It did not previously exist.
Correlates to an INSERT SQL statement in the Data Adapter.

DataRowState.Deleted
The row has been deleted, but not yet actually removed from the
dataset. Correlates to a DELETE SQL statement.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
934
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ADO.NET: DataRow States
DataRowState.Modified
Changes have been made to the row since the last
AcceptChanges method was called. Correlates to an
UPDATE SQL statement.

DataRowState.Unchanged
The row's fields/properties have not changed since the
dataset was populated or since the last
AcceptChanges/RejectChanges method was called.

DataRowState.Detached
This row does not exist in any DataTable. It is entirely on
its own, not yet having been added to a DataTable.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
935
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Bindings: Format & Parse Events
Frequently data should be displayed differently than
it is stored in the database. A currency would be
stored as a 'decimal' but should be displayed with a
dollar sign, commas, and the decimal placed fixed at
two digits. For this, two events of the Binding class
are exposed, Format & Parse.

Format is raised both when data is pulled from the


data source and before it is shown, and also after the
Parse event. The Parse event is called if data has
changed in a control and before it is written to the
data source (to remove formatting).

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
936
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Bindings: Format & Parse Events

The type of event that is called for both Format & Parse is ConvertEventHandler, which
has its own special event arguments, ConvertEventArgs.
ConvertEventArgs exposes two properties, DesiredType and Value. Value contains the
current data and should be set to the new data format. DesiredType contains the type of
data wanted.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
937
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Bindings: Format & Parse Events

private void InitTextBox()


{
txtPrice.DataBindings[0].Format += new
ConvertEventHandler(txtPrice_Format);
txtPrice.DataBindings[0].Parse += new
ConvertEventHandler(txtPrice_Parse);
}
private void txtPrice_Format(object sender, ConvertEventArgs e)
{
if (e.Value is decimal)
e.Value = ((decimal) e.Value).ToString("c");
}
private void txtPrice_Parse(object sender, ConvertEventArgs e)
{
if (e.DesiredType == typeof(decimal))
{
string price = e.Value.ToString();
price = price.Replace("$", "").Replace(",", "");
e.Value = decimal.Parse(price);
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
938
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Binding - Demo

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
939
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Binding - Demo

private void DataBinding_Load(object sender, System.EventArgs e)


{
string strConn = "Data Source=S2B21675;uid=sa;pwd=sa;Initial
Catalog=pubs";

SqlConnection objConn = new SqlConnection(strConn);


string str = "Select * from titles";

SqlCommand objCom = new SqlCommand(str,objConn);


objCom.CommandType=CommandType.Text;

SqlDataReader dr = null;

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
940
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Binding - Demo

try
{
if(objConn.State==ConnectionState.Closed)
{
objConn.Open();
dr=objCom.ExecuteReader();
while(dr.Read())
{
comboBox1.Items.Add(dr["title_id"].ToString());
}
dr.Close();

}
}
catch(SqlException objs)
{
throw objs;
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
941
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Binding - Demo

finally
{
dr.Close();
if(objConn.State==ConnectionState.Open)
{
objConn.Close();
}
} }

private void cmdOK_Click(object sender, System.EventArgs e)


{
string strConn = "Data Source=p3c20014;uid=sa;pwd=sa;Initial
Catalog=pubs";

SqlConnection objConn = new SqlConnection(strConn);


string strQry = "Select * from titles where
title_id='"+comboBox1.SelectedItem.ToString()+"'";

SqlDataAdapter objAdapt=new SqlDataAdapter(strQry,objConn);


ds = new DataSet();

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
942
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Binding - Demo

try
{
objConn.Open();
objAdapt.Fill(ds);
textBox1.DataBindings.Add("text",ds.Tables[0].DefaultView,
“title");
textBox2.DataBindings.Add("text",ds.Tables[0].DefaultView,
“price");
textBox3.DataBindings.Add("text",ds.Tables[0].DefaultView,
"advance");
textBox4.DataBindings.Add("text",ds.Tables[0].DefaultView,
"type");
}
catch(SqlException ex)
{
MessageBox.Show(ex.Message);
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
943
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Binding - Demo

finally
{
if(objConn.State==ConnectionState.Open)
{
objConn.Close();
}
}
}
private void cmdCancel_Click(object sender, System.EventArgs e)
{
ds.Clear();
textBox1.DataBindings.Clear();
textBox2.DataBindings.Clear();
textBox3.DataBindings.Clear();
textBox4.DataBindings.Clear();

textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
944
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Navigating Records - Demo

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
945
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
App.config

<?xml version="1.0" encoding="utf-8" ?>


<configuration>
<appSettings>
<add key="MyConnection"
value="server=p3c20014;uid=sa;pwd=sa;Initial
Catalog=Pubs" />

</appSettings>
</configuration>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
946
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Navigating Records - Demo
public DataSet ReturnDataSet()
{
String strConn;
strConn=ConfigurationSettings.AppSettings["MyConnection"];
SqlConnection objConn = new SqlConnection(strConn);
string strQry="select * from Publishers";
SqlDataAdapter objAdapt = new SqlDataAdapter(strQry,objConn);
DataSet objDs=new DataSet();
try
{
objConn.Open();
objAdapt.Fill(objDs);
}
catch(SqlException ex)
{ throw ex; }
finally
{
objConn.Close();
}
return objDs; }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
947
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Navigating Records - Demo

private void Navigation_Load(object sender, System.EventArgs e)


{
DataSet ds = ReturnDataSet();
BindingContext bc=this.BindingContext;
bm=bc[ds.Tables[0].DefaultView,""];
bm.Position=0;

textBox1.DataBindings.Add("Text",ds.Tables[0].DefaultView,
"pub_id");
textBox2.DataBindings.Add("Text",ds.Tables[0].DefaultView,
"pub_name");
textBox3.DataBindings.Add("Text",ds.Tables[0].DefaultView,
"city");
textBox4.DataBindings.Add("Text",ds.Tables[0].DefaultView,
"state");
textBox5.DataBindings.Add("Text",ds.Tables[0].DefaultView,
"country");

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
948
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Navigating Records - Demo

private void cmdFirst_Click(object sender, System.EventArgs e)


{
bm.Position = 0;
}

private void cmdPrevious_Click(object sender, System.EventArgs e)


{
bm.Position -= 1;
}

private void cmdNext_Click(object sender,System.EventArgs e)


{
bm.Position +=1;
}

private void cmdLast_Click(object sender,System.EventArgs e)


{
bm.Position=bm.Count-1;
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
949
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataSet Serialization
The DataSet object in ADO.NET is an in-memory representation of
disconnected, cached set of data and provides a consistent relational
programming model regardless of the data source. When we require
sending a DataSet class instance across process boundaries, the DataSet
needs to be serialized.

Unfortunately, the DataSet class in the earlier version of ADO.NET used to


serialize data as XML even if the BinarySerializer was specified. This
resulted in slower serialization and an overhead of large sized serialized
data. In ADO.NET 2.0 however, DataSet serialization has been improved
to a large extent and you can now use the RemotingFormat property of
the DataSet class to specify that the data is to be stored directly in binary
format. Hence, the DataSet class ADO.NET 2.0, unlike ADO.NET 1.1,
supports both XML and Binary Serialization formats. This is shown in the
code example below.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
950
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataSet Serialization
BinaryFormatter binaryFormatter = new
BinaryFormatter();

FileStream fileStream = new FileStream("c:\\emp.dat",


FileMode.CreateNew);

DataSet empDataSet = GetEmployeeDataSet(); //This is


a custom method that creates, populates and then
returns a DataSet instance.

empDataSet.RemotingFormat =
SerializationFormat.Binary;

binaryFormatter.Serialize(fileStream,empDataSet);

fileStream.Close();

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
951
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Bulk Copy Operation

Bulk copying of data from a data source to another data


source is a new feature added to ADO.NET 2.0. Bulk copy
classes provides the fastest way to transfer set of data from
once source to the other. Each ADO.NET data provider
provides bulk copy classes. For example, in SQL .NET data
provider, the bulk copy operation is handled by SqlBulkCopy
class, which can read a DataSet, DataTable, DataReader, or
XML objects. Read more about Bulk Copy here.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
952
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Bulk Copy Operation is faster
No per-row statement execution. When you do multiple inserts
without bulk-copy, each insert is a statement in itself (regardless
of whether it's batched together with other statements). With
bulk-copy, we don't incur the cost of executing a statement for
each row, the whole copy operation is a single thing.

No multiple network round-trips. Once the bulk-insert operation


is setup, we send rows from the client to the server continously,
without going back-and-forth over the wire.

Server storage engine also can greatly optimize how rows are
inserted when performing a bulk-copy operation. How much can
be optimized depends a lot on the recovery model the tarder
database is set to; in "simple" and "bulk logged" the overhead of
logging is greatly reduced during bulk-copy operations, helping a
lot with performance.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
953
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Bulk Copy Operation - Demo

string strConnection="Server=p3c20014;user id=sa;pwd=sa;


Initial Catalog=Roy";
SqlConnection source = new SqlConnection(connectionString);
SqlConnection destination =
new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("DELETE FROM BulkDataTable",
destination);

source.Open();
destination.Open();
cmd.ExecuteNonQuery();

cmd = new SqlCommand("SELECT * FROM Products", source);

SqlDataReader reader = cmd.ExecuteReader();

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
954
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Bulk Copy Operation - Demo
SqlBulkCopy bulkData = new SqlBulkCopy(destination);

bulkData.DestinationTableName = "BulkDataTable";

bulkData.WriteToServer(reader);

bulkData.Close();
destination.Close();
source.Close();

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
955
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Batch Update

Batch update can provide a huge improvement in the


performance by making just one round trip to the server for
multiple batch updates, instead of several trips if the database
server supports the batch update feature.
The UpdateBatchSize property provides the number of rows to
be updated in a batch. This value can be set up to the limit of
decimal.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
956
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Paging
Data Paging is a very powerful feature in ADO.NET. It can be
recollected that in the earlier version of ADO.NET we needed to
make use of stored procedures for incorporating Data Paging
functionality in our applications. Now, with ADO.NET 2.0, it is
much simplified with the introduction of the ExecutePageReader
method in the SqlDataReader class.

Now command object has a new execute method called


ExecutePageReader. This method takes three parameters -
CommandBehavior, startIndex, and pageSize. So if you want to
get rows from 101 - 200, you can simply call this method with
start index as 101 and page size as 100.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
957
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Paging

SqlConnection sqlConnection = new


SqlConnection(connectionString);

sqlConnection.Open();

SqlCommand sqlCommand = new SqlCommand("Select * from


Employee", sqlConnection);

SqlDataReader sqlDataReader =
sqlCommand.ExecutePageReader(CommandBehavior.CloseConn
ection, 1, 25);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
958
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataTable's Load and Save Methods

ADO.NET 2.0 allows loading a DataReader object into a DataSet


or a DataTable and vice versa. Both the DataSet and the
DataTable classes in ADO.NET 2.0 contain the Load method
that can be used to load a DataReader instance into a DataSet
or a DataTable.

You can also load a DataReader object into a DataTable by


using the Load method.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
959
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DataTable's Load and Save Methods
SqlConnection sqlConnection =
new SqlConnection(connectionString);

sqlConnection.Open();

SqlCommand sqlCommand = new SqlCommand("Select * from


Employee", sqlConnection);

SqlDataReader sqlDataReader =
sqlCommand.ExecuteReader(CommandBehavior.CloseConnecti
on);

DataTable dataTable = new DataTable("Employee");

dataTable.Load(sqlDataReader);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
960
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DbProvidersFactories Class

This class provides a list of available data providers


on a machine.
You can use this class and its members to find out
the best suited data provider for your database when
writing a database independent applications.

Customized Data Provider


By providing the factory classes now ADO.NET
extends its support to custom data provider. Now
you don't have to write a data provider dependent
code. You use the base classes of data provider and
let the connection string does the trick for you.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
961
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DbProvidersFactories Class

This class is named DbProviderFactories and also resides in the System.Data.Common


namespace. Since it is static, you don’t need to create an instance of the class in order to
access it

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
962
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DbProvidersFactories Class
The purpose of an abstract factory is to provide an interface for
creating families of related objects, without specifying their
concrete classes. It is a creational pattern. When we write code
to use the interface exposed by an abstract factory, we
decouple our code from the specific factory or factories that
create the objects we wish to consume. This allows us to define
GetFactory
multiple factories that produce different objects meant for
Function:
different situations.
Name Description
DbProviderFactories.GetFactor Returns an instance of a
y (DataRow) DbProviderFactory.

DbProviderFactories.GetFactor Returns an instance of a


y (String) DbProviderFactory.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
963
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DbProvidersFactories - Demo

Private cmdGetOleDB_Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs)
{
 
Data.Common.DbProviderFactory dbFactory;
 
dbFactory =
System.Data.Common.DbProviderFactories.GetFactory("System.Da
ta.OleDb")
 
DemonstrateFactory(dbFactory)
 
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
964
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DbProvidersFactories - Demo

Private DemonstrateFactory(FactorySystem.Data.Common.DbProviderFactory
Factory)
{
Data.Common.DbConnection Connection;
Data.Common.DbDataAdapter DA;
Data.Common.DbCommand Command;
Data.Common.DbParameter Parm;

Connection = Factory.CreateConnection
DA = Factory.CreateDataAdapter
Command = Factory.CreateCommand
Parm = Factory.CreateParameter

String str;
str = Connection.GetType.ToString,
str = str & DA.GetType.ToString,
str = str & Command.GetType.ToString,
str = str & Parm.GetType.ToString,
MsgBox.Show(str);
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
965
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Managed Provider
Provider Model
ADO.NET v1.1 was based on interfaces
Not enough for provider-agnostic code
Hard to evolve

ADO.NET v2.0 introduces a common API


Abstract base classes instead of interfaces
Better versioning story
Provider factories enabled at the API level
SQL syntax is still back-end specific

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
966
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Managed Provider

IDb* interfaces (e.g. IDbConnection)

Provider-
independent apps
Db* abstract base classes (e.g. DbConnection) Code to this layer

Db*Base implementation classes

Provider-
specific apps
SqlClient OleDb Odbc Oracle 3rd 3rd Code to this layer
Client Party Party

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
967
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Managed Provider

Provider
ProviderFactories
Factories
Can
Canenumerate
enumerateManaged
ManagedProviders
Providers
Can
Cancreate
createaaDbProviderFactory
DbProviderFactoryfrom
fromName
Name
Factory
Factoryto
tocreate
createcommon
commonobjects
objects

DbProviderFactory factory =
DbProviderFactories.GetFactory("System.Data.SqlClient");

DbConnection conn = factory.CreateConnection();


DbCommand cmd = factory.CreateCommand();
DbDataReader rdr = cmd.ExecuteReader();
DbDataAdapter da = factory.CreateDataAdapter();
DataSet theSet = new DataSet();
da.Fill(theSet);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
968
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Asynchronous Execution

Asynchronous
AsynchronousExecution
Execution
Added
AddedBeginXXX,
BeginXXX,EndXXX
EndXXXto
tomost
mostExecutions
Executions
BeginExecuteNonQuery,
BeginExecuteNonQuery,EndExecuteNonQuery
EndExecuteNonQuery
BeginExecuteReader,
BeginExecuteReader,EndExecuteReader
EndExecuteReader
Only
Onlysupported
supportedon
onSqlClient
SqlClientso
sofar
far
Must
Mustadd
add“Asynchronous
“AsynchronousProcessing=true”
Processing=true”

conn = new SqlConnection(


"Server=.;database=...;Asynchronous Processing=true");
cmd = conn.CreateCommand();
// ...
conn.Open();
cmd.BeginExecuteReader(new AsyncCallback(SomeMethod), this);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
969
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Using Stored Procedures
A stored procedures is a pre-defined, reusable
routine that is stored in a database.  SQL Server
compiles stored procedures, which makes them more
efficient to use.  Therefore, rather than dynamically
building queries in your code, you can take
advantage of the reuse and performance benefits of
stored procedures. 

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
970
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Using Stored Procedures

SqlCommand type can be used to execute stored


procedures. 

There are two tasks require to make this happen: let


the SqlCommand object know which stored
procedure to execute and tell the SqlCommand
object that it is executing a stored procedure.  These
two steps are shown below:

SqlCommand cmd = new SqlCommand(“myStoredProcedure",


conn);

procedure cmd.CommandType =
CommandType.StoredProcedure;

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
971
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sending Parameters to Stored
Procedures

Using parameters for stored procedures is the


same as using parameters for query string
commands. 

SqlCommand cmd = new SqlCommand("CustOrderHist",


conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@CustomerID",
custId));

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
972
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Stored Procedures - Demo

using System;using System.Data;


using System.Data.SqlClient;
class StoredProcDemo
{
static void Main()
{
StoredProcDemo spd = new StoredProcDemo();
spd.RunStoredProc();
spd.RunStoredProcParams();
}
public void RunStoredProc()
{
SqlConnection conn = null;
SqlDataReader rdr = null;

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
973
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Stored Procedures - Demo

Console.WriteLine("\nTop 10 Most Expensive Products:\n");


try
{
conn = new SqlConnection("Server=p3c20014;DataBase=Northwind;
UserId=sa;pwd=sa");
conn.Open();
SqlCommand cmd = new SqlCommand("myStoredProc", conn);
cmd.CommandType = CommandType.StoredProcedure;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine("Product: {0,-25} Price: ${1,6:####.00}",
rdr["TenMostExpensiveProducts"],
rdr["UnitPrice"]
);
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
974
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Stored Procedures - Demo

finally
{
if (conn != null)
{
conn.Close();
}
if (rdr != null)
{
rdr.Close();
} }
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
975
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
CommandBuilder object
Used to generate single-table insert/update/delete
commands for data adapter

Retrieves metadata from select command about


table structure

Select command must have at least one primary


key or unique column
Call .Update() method of DataAdapter

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
976
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
CommandBuilder Code

conn = new SqlConnection("datasource=p3c20014;initial


catalog=northwind;UserId =sa; pwd =;");
String SqlString = "Select * from customers" ;
SqlCommand cmd = new SqlCommand(SqlString, cnn)
DataSet ds = new DataSet();
SqlDataAdapter sqlda = New SqlDataAdapter(cmd);
sqlda.Fill(ds);
ds.Tables("Customers").Rows(0)("City") = "Chevy
Chase“;
SqlCommandBuilder cb = New SqlCommandBuilder(sqlda);
sqlda.Update(ds, "Customers")
If (cnn.State = ConnectionState.Open)
cnn.Close();

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
977
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Concurrency Options

Pessimistic concurrency – Data is unavailable to users


from the time the record is fetched until it is
updated in the database.
• Not supported in ADO.NET, can simulate with
transactions

Optimistic concurrency – Data is not locked,


attempting to update a record that has already
been changed results in a concurrency exception
(DBConcurrencyException).
"Last in wins" – Overwrite the last changes

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
978
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Optimistic Concurrency
Use date time stamp to check for change
Update table set col1 = @newvalcol1, col2=@newvalcol2
where tableid = @tableid
and datetimestamp=@datetimestamp
Match old columns exactly
Update table set col1 = @newvalcol1, col2=@newvalcol2
where tableid = @tableid
and col1=@oldcol1
and col2=@oldcol2
Can catch concurrency exceptions
Apply your business logic
Show original, current, and proposed records

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
979
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Best Practices (Designing DAL)
Retrieving result set & iterating

Use a SqlDataAdapter object to generate a DataSet


or DataTable

Use a SqlDataReader to provide a read-only,


forward-only data stream

Use an XmlReader to provide a read-only, forward-


only data stream
of XML data

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
980
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Best Practices (Designing DAL)
Retrieving a single item from a specified row

Use the CommandBehavior.SingleRow enumerated


value when
calling the ExecuteReader method of the SqlCommand
object

In case of parameters and outputs ensure that


DataReader is
closed

Use ExecuteScalar for single values.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
981
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Reader vs. DataSet vs. XMLReader
Use DataSet when:

You require a disconnected memory-resident cache of data, so that


you can pass it to another component or tier within your application.
You require a disconnected memory-resident cache of data, so that
you can pass it to another component or tier within your application.
You are working with data retrieved from multiple data sources,
such as multiple databases, tables, or files.
You want to update some or all of the retrieved rows and use the
batch update facilities of the SqlDataAdapter.
You want to perform data binding against a control that requires a
data source that supports IList.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
982
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Reader vs. DataSet vs. XMLReader
Use DataReader when:

Dealing with large volumes of data—too much to


maintain in a single cache.
Reduce the memory footprint of your application.
Want to avoid the object creation overhead
associated with the DataSet
Want to perform data binding with a control that
supports a data source that implements
IEnumerable
Wish to streamline and optimize your data access
Reading rows containing binary large object
(BLOB) columns

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
983
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Reader vs. DataSet vs. XMLReader
Use XMLReader when

processing the retrieved data as XML, without


incurring performance overhead of creating a DataSet

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
984
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Stored Procedures vs. SQL Text
Stored Procedures are:
Pre-compiled code!
Tightly Integrated with back end (Database)
Server
Looks neater with parameters
Even better with CLR Integration in SQL
Server 2005

SQL Text is:


 (could be) ANSI compatible
 Interpreted at runtime
 Loosely coupled with the backend database
server

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
985
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Best Practices (Passing Data
Through Tiers)
Data Access Logic Components
CRUD Operations

Business Entities
Abstract Data Types
DALC’s messaging format
Could be:
XML (XML String or XML DOM)
DataSet
Typed DataSet
Business Entity (with/without CRUD Ops)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
986
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Implementing
Business Entities
Don’t access database directly
Can be passed as an IO/Message to the
business process
Can travel on the wire (Serializable)
Do not initiate any transactions
Can be represented as:
XML
DataSet (typed/un-typed)
Custom Object (with / without CRUD)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
987
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Insert/Update/Delete - Demo

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
988
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Insert Record

private void cmdInsert_Click(object sender, System.EventArgs e)


{
string strConn = "Data Source=p3c20014;uid=sa;pwd=sa;Initial
Catalog=Roy";
SqlConnection objConn = new SqlConnection(strConn);

string strCmd="prcInsertEmp";
SqlCommand objCmd=new SqlCommand(strCmd,objConn);
objCmd.CommandType=CommandType.StoredProcedure;
int resval=0;
try
{
objConn.Open();
SqlCommandBuilder.DeriveParameters(objCmd);

objCmd.Parameters[1].Value=textBox1.Text;
objCmd.Parameters[2].Value=textBox2.Text;
objCmd.Parameters[3].Value=textBox3.Text;
objCmd.Parameters[4].Value=textBox4.Text;
resval=objCmd.ExecuteNonQuery();
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
989
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Insert Record
catch(SqlException sq)
{
MessageBox.Show(sq.Message);
}
finally
{
if(objConn.State==ConnectionState.Open)
{
objConn.Close();
}
}
if(resval == 0)
{
MessageBox.Show("Data Insertion Failed");
}
else
{
MessageBox.Show("Data Added" + resval);
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
990
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Update Record

private void cmdUpdate_Click(object sender, System.EventArgs e)


{

string strConn = "Data Source=p3c20014;uid=sa;pwd=sa;Initial


Catalog=Roy";
SqlConnection objConn = new SqlConnection(strConn);
string cmd = " Update EmployeeDetails set EmpName =
'"+textBox2.Text+"',Department = '"+textBox3.Text +"' where EmpID =
'"+ textBox1.Text+"'";
SqlDataAdapter objad = new SqlDataAdapter(cmd,objConn);

int resval=0;
try
{
objConn.Open();
resval=objad.SelectCommand.ExecuteNonQuery();

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
991
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Update Record
catch(SqlException sq)
{
MessageBox.Show(sq.Message);
}
finally
{
if(objConn.State==ConnectionState.Open)
{
objConn.Close();
}
}
if(resval == 0)
{
MessageBox.Show("Data updation Failed");
}
else
{
MessageBox.Show("Data updated" + resval);
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
992
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Delete Record

private void cmdDelete_Click(object sender, System.EventArgs e)


{
string strConn = "Data Source=S2B20793;uid=sa;pwd=sa;Initial Catalog=Roy";
SqlConnection objConn = new SqlConnection(strConn);
string strQry="prcDelEmp";
SqlCommand objcmd = new SqlCommand(strQry,objConn);
objcmd.CommandType = CommandType.StoredProcedure;
objcmd.Parameters.Add(new
SqlParameter("@EmpId",SqlDbType.Char,12,"EmpID")).Value = textBox1.Text;
int resval=0;
try
{
objConn.Open();
resval=objcmd.ExecuteNonQuery();
}
catch(SqlException sq)
{
MessageBox.Show(sq.Message);
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
993
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Delete Record
finally
{
if(objConn.State==ConnectionState.Open)
{
objConn.Close();
}
}
if(resval == 0)
{
MessageBox.Show("Data Deletion Failed");
}
else
{
MessageBox.Show("Data Deleted" + resval);
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
994
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thank You !

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Microsoft
Application
Blocks
for .NET

COE – Current Technologies


Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Access Application
Block

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
About Data Access Application Block
Why Data Application Blocks?
Advantages of using Data Access Application Block.
Structure of Data Application Block.
Referencing a Data Access block in an Application.
Developing Applications with Data Access Block.
Retrieving Multiple Rows using SqlDataReader.
Methods of SqlHelperParameterCache.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
998
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
About Data Application Block
The Microsoft Data Access Application Block for .NET
consists of
• A single .NET-based assembly.
• Contains all of the functionality necessary to
perform the most common data access
tasks against a Microsoft SQL Server 2000
database.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
999
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Why Data Application Block: 
The Data Access Application Block was designed to
• Encapsulate best practice for data access.
Applications often need to execute commands such as
Transact-SQL statements or stored procedures in a
SQL Server database. These commands can be used to
perform
• Database updates
• Retrieve single values or rows
• To retrieve XML data.
While the Microsoft ActiveX Data Objects (ADO) .NET
class library in the .NET Framework provides
• A high level of abstraction
• A great deal of functionality.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1000
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Why Data Application Block: 
  Developers find the following problems while working with data access.
• Confused with the multitude of implementation choices available
when they build data access solutions.
• Developers often find themselves
 Duplicating similar code to open and close connections
 Assign parameters to commands to perform other data
access.
The Data Access Application Block was designed to address these problems
by providing encapsulated logic to perform the most common data access
tasks with a minimal requirement for custom code.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1001
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Advantages of using Data Access Application
Block
The following Data operations can be achieved using Data
Access Application Blocks.
• Call stored procedures or SQL text commands.
• Specify parameter details.
• Return SqlDataReader, DataSet, XmlReader objects, or
single values.
• Use strongly typed table and field names.
• Support parameter caching, where required.
• Allow additional tables to be added by passing in pre-
existing datasets.
• Update a dataset with user-specified update commands.
• Create SqlCommand objects.
• Allow strongly typed data rows to be passed in place of
parameters.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1002
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Structure of Data Access Application Block:

There are two major categories of data access logic


that needed to be encapsulated by the Data Access
Application Block
• The actual execution of database commands.
• The management and caching of parameters.
To meet these needs, the designers of the Data
Access Application Block made the decision to
create two classes
• SqlHelper class, which provides methods for
executing database commands
• SqlHelperParameterCache class, which provides
parameter management functionality.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1003
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Structure of Data Access Application Block

In order to minimize the code required to use the


Data Access Application Block, the design decision
was taken to declare all public functions in each class
as static methods, allowing them to be called without
instantiating an object instance of the class.
 
Since client applications do not need to instantiate
the Data Access Application Block classes, both the
SqlHelper and SqlHelperParameterCache were
designed to be non-inheritable, and to implement
private constructors.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1004
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Referencing a Data Application Block in an
Application
When you create a data access client that uses the Data
Access Application Block, you should perform the
following steps:
• Set a reference to the Data Access Application Block assembly
Microsoft.ApplicationBlocks.Data.dll.
• (C:\Program Files\Microsoft Application Blocks for .NET\Data
Access
v2\Code\CS\Microsoft.ApplicationBlocks.Data\bin\Debug).
• Add a using statement at the top of your data access client source
file(s) to reference the Microsoft.ApplicationBlocks.Data
namespace. All Data Access Application Block types are located
within this namespace.
• Add a using statement to reference the System.Data and
System.Data.SqlClient namespaces. The SqlHelper methods use
various types from these namespaces as input and return
parameters.
• Optionally, add a using statement to reference the System.Xml
namespace. This is required only if you use the SqlHelper
ExecuteXmlReader methods.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1005
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Developing Applications with Data Access block.
The following methods are available with SQLHelper class each of which is
overloaded to support a variety of functionalities.
• ExecuteNonQuery (9 overloads).
• Executes a command that does not return rows.
• public static int ExecuteNonQuery(method_parameters).
• Overloaded Members
 ExecuteNonQuery(string connectionString, CommandType commandType,string
commandText).
 ExecuteNonQuery(string connectionString, CommandType commandType,string
commandText, params SqlParameter[] commandParameters).
 ExecuteNonQuery(string connectionString, string spName, params object[]
parameterValues)
 ExecuteNonQuery(SqlConnection connection, CommandType commandType,
string commandText)
 ExecuteNonQuery(SqlConnection connection, CommandType
commandType,string commandText, params SqlParameter[]
commandParameters)
 ExecuteNonQuery(SqlConnection connection, string spName, params object[]
parameterValues)
 ExecuteNonQuery(SqlTransaction transaction, CommandType
commandType,string commandText)
 ExecuteNonQuery(SqlTransaction transaction, CommandType commandType,
string commandText, params SqlParameter[] commandParameters)
 ExecuteNonQuery(SqlTransaction transaction, string spName, params object[]
parameterValues)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1006
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Developing Applications with Data Access block.
• ExecuteDataset (9 overloads)
• Executes a command that returns rows as a DataSet.
• public static DataSet ExecuteDataset(method_parameters)
• Overloaded members
 ExecuteDataset(string connectionString, CommandType commandType, string commandText).
 ExecuteDataset(string connectionString, CommandType commandType,string commandText, params SqlParameter[]
commandParameters).
 ExecuteDataset(string connectionString, string spName, params object[] parameterValues).
 ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText).
 ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[]
commandParameters).
 ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[]
commandParameters).
 ExecuteDataset(SqlConnection connection, string spName, params object[] parameterValues)
 ExecuteDataset(SqlTransaction transaction, CommandType commandType,string commandText).
 ExecuteDataset(SqlTransaction transaction, CommandType commandType,string commandText, params
SqlParameter[] commandParameters)
 ExecuteDataset(SqlTransaction transaction,string spName, params object[] parameterValues)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1007
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Developing Application with Data Access
Block
• ExecuteScalar (9 overloads).
• Executes a command that returns a single value as an object.
• public static object ExecuteScalar (method_parameters).
• Overloaded members
 ExecuteScalar(string connectionString, CommandType commandType, string commandText)
 ExecuteScalar(string connectionString,CommandType commandType, string commandText,params
SqlParameter[] commandParameters)
 ExecuteScalar(string connectionString, string spName, params object[] parameterValues)
 ExecuteScalar(SqlConnection connection, CommandType commandType,string commandText)
 ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText, params
SqlParameter[] commandParameters)
 ExecuteScalar(SqlConnection connection, string spName, params object[] parameterValues).
 ExecuteScalar(SqlTransaction transaction,CommandType commandType, string commandText)
 ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText,params
SqlParameter[] commandParameters)
 ExecuteScalar(SqlTransaction transaction,string spName, params object[] parameterValues)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1008
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Developing Application with Data Access Block
• ExecuteXmlReader ( 6 overloads).
• Executes a command that returns XML in an XmlReader.
• public static XmlReader ExecuteXmlReader
(method_parameters)
• Overloaded members

 ExecuteXmlReader(SqlConnection connection, CommandType


commandType,string commandText)
 ExecuteXmlReader(SqlConnection connection, CommandType
commandType,string commandText, params SqlParameter[]
commandParameters)
 ExecuteXmlReader(SqlConnection connection, string spName,params object[]
parameterValues)
 ExecuteXmlReader(SqlTransaction transaction, CommandType
commandType, string commandText)
 ExecuteXmlReader(SqlTransaction transaction, CommandType
commandType, string commandText,params SqlParameter[]
commandParameters)
 ExecuteXmlReader(SqlTransaction transaction,string spName, params
object[] parameterValues)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1009
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Developing Application with Data Access Block
• FillDataSet ( 9 overloads)
• Executes a command that populates a DataSet that is provided as a
parameter.
• public static void FillDataset(method_parameters).
• Overloaded members.
 FillDataset(string connectionString, CommandType commandType,string commandText,
DataSet dataset, string[] tableNames)
 FillDataset(string connectionString, CommandType commandType,string commandText,
DataSet dataSet, string[] tableNames,params SqlParameter[] commandParameters)
 FillDataset(string connectionString, string spName, DataSet dataSet,string[]
tableNames, params object[] parameterValues)
 FillDataset(SqlConnection connection, CommandType commandType,string
commandText, DataSet dataSet, string[] tableNames)
 FillDataset(SqlConnection connection, CommandType commandType, string
commandText, DataSet dataSet, string[] tableNames, params SqlParameter[]
commandParameters)
 FillDataset(SqlConnection connection, string spName, DataSet dataSet, string[]
tableNames, params object[] parameterValues)
 FillDataset(SqlTransaction transaction, CommandType commandType, string
commandText, DataSet dataSet, string[] tableNames)
 FillDataset(SqlTransaction transaction, CommandType commandType, string
commandText, DataSet dataSet, string[] tableNames, params SqlParameter[]
commandParameters)
 FillDataset(SqlTransaction transaction,string spName, DataSet dataSet, string[]
tableNames,params object[] parameterValues)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1010
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Developing Applications with Data Access block

• ExecuteNonQueryTypedParams.
• Executes a command that does not return rows using a
DataRow’s column values as parameters.
• ExecuteDatasetTypedParams.
• Executes a command that returns rows as a DataSet
using a DataRow’s column values as parameters.
• ExecuteReaderTypedParams.
• Executes a command that returns rows as a
SqlDataReader using a DataRow’s column values as
parameters.
• CreateCommand
• Creates a command object given a stored procedure and
parameters.
• UpdateDataset
• Updates a dataset using an existing connection and
user-specified update commands.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1011
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Retrieving multiple rows using a SqlDataReader

The following example assumes that this stored


procedure has been created in the database to
which the connection string in the code relates. 
CREATE PROCEDURE getProductsByCategory
@CategoryID INTEGER
AS
SELECT ProductID, ProductName, QuantityPerUnit, UnitPrice
FROM Products
WHERE CategoryID = @CategoryID
The following overload of the ExecuteReader
method can be used to call a stored procedure
with command parameters.
public static SqlDataReader ExecuteReader(string
connectionString,
CommandType commandType,
string commandText,
params SqlParameter[] commandParameters);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1012
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Retrieving multiple rows using a SqlDataReader
The following code fragment illustrates how the SqlHelper
class can be used to retrieve a SqlDataReader obect. After
it's retrieved, the SqlDataReader could be bound to a
control such as a DataList.

private SqlDataReader RetrieveDataReader(string


connectionString, int categoryID)
{
// Call ExecuteReader static method of SqlHelper class
that returns a SqlDataReader
// We pass in database connection string, stored
procedure name and value of categoryID parameter
SqlDataReader reader =
SqlHelper.ExecuteReader(connectionString,
"getProductsByCategory", categoryID);
return reader;}
Similarly by the use of other overloaded methods of the
SqlHelperClass the Data Access operations can be greatly
simplified.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1013
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Methods of SqlHelperParameterCache
• CacheParameterSet
• Caches a SqlParameter array for reuse.
• GetCachedParameterSet
• Retrieves a cached SqlParameter array.
• GetSpParameterSet
• Retrieves the required parameter array for a specified
stored procedure. 

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1014
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Exception Management
Application Block

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
• About Exception Management Application Block.
• Advantages of using Exception Management
Application block.
• Design of Exception Management Application block.
• Main Elements of Exception Management Application
block.
• Classes and Interfaces in the Exception Management
Application block.
• BaseApplicationException class.
• BaseApplicationException class constructors.
• ExceptionManager Component.
• Application Configuration files.
• ExceptionManagerSectionHandler Class.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1016
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
• Publisher interface
• Publisher class.
• Developing Applications using Exception Management
Application Block.
• Creating Custom ApplicationExceptions.
• Publishing an Exception.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1017
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Exception Management Application Block
• Provides a simple yet extensible framework for
logging exception information to the default
location of the Windows Application Event Log.
• Custom components can be created to
• Log exception details to other data sources
• To notify operators, without affecting your application code.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1018
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Advantages of using Exception Management Application
block
Specifically, the Exception Management
Application Block will help you:
• Manage Exceptions in an efficient and consistent
manner.
• Isolate exception management from business
logic code.
• Handle and log exceptions with minimum
amount of custom code e.g. Catch (Exception ex)

{
ExceptionManager.Publish(ex)
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1019
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Design of Exception Management Application block

The flow of logic when an Exception Management block is used to


publish an exception as follows:
• The application throws an Exception which is derived from the
BaseApplicationException class provided in the Exception
Management Application block.
• The Application calls the Publish method of the
ExceptionManager class.
• The ExceptionManager class uses the
ExceptionManagerSectionHandler for retrieving the application’s
exception management settings.
• The exception management settings are read from the
configuration file to determine how the exception should be
published.
• There can be 2 possibilities
• If no settings are found the exception is published in the Windows
event log using the default publisher class.
• If the exception settings are found the default/custom publisher
classes are used to publish the exception.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1020
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Main Elements of Exception Management Application
Block

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1021
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Classes and interfaces in the Exception Management
Application block.
The Exception Management Application block consists of the
following classes and interfaces.
• BaseApplicationException: Base exception class.Custom
exceptions can be derived from this class.
• ExceptionManagementSectionHandler: Used to retrieve the
exception management settings from the application’s
configuration file which can be used to fine tune the runtime
behaviour.
• ExceptionManager: Primary class through which the application
interacts to publish and log the exception.
• ExceptionManagerInstaller:This class is used when you install
the Exception Management Application Block to create the two
Event sources used by the default publisher and by custom
publishers when writing to the Microsoft Windows Event Log.
• DefaultPublisher: provides logging functionality and writes
information to the Event Log.
• IExceptionPublisher and IExceptionXmlPublisher: These
interfaces are implemented by the publisher classes.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1022
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
BaseApplicationException Class
The primary features of this class are:
• The class provides a base exception class from
which all application exception classes can
derive.
• The class contains information that is valuable
to all application exceptions.
• The base class should be lightweight and
should include only information that is valuable
to all application exception classes.
• The base class is serializable to ensure that it
can be remoted across .NET remoting
boundaries.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1023
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
BaseApplicationException Class Constructors
The BaseApplicationException class derives from the System.ApplicationException
and implements the following 3 public constructors.
• Constructor taking no parameters.
public BaseApplicationException() : base()
{
// Initialization code
}
• Constructor allowing the Message property to be set.
public BaseApplicationException(string message) : base(message)
{
// Initialization code
}
• Constructor allowing the Message and InnerException property to be set.
public BaseApplicationException(string message,Exception inner)
: base(message, inner)
{
// Initialization code
}
The provision of these constructors allows exception classes derived from
BaseApplicationException to be instantiated in three different ways.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1024
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ExceptionManager Component
The primary goals of the ExceptionManager Component are:
• The component should require a minimal amount of code
by the developer to integrate into an application.
• Behavior should be based on configuration settings that
can be modified allowing changes to be made without
recoding, recompiling, and in the case of ASP.NET
applications, without restarting the application.
• Internal exceptions thrown by custom publishers should
be caught and logged.
• XML serialization of the exception chain is an issue. The
XmlSerializer object only serializes read/write values,
which limits its use for exception objects. The exception
manager component provides its own XmlSerializer
implementation.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1025
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Application Configuration Files
Contains settings that can be read by an Application at run
time.
Settings in the file indicate
• Whether or not exceptions should be logged or
notification sent.
• Name of the publisher class that must be used to publish
the exception.
• Whether or not the publisher should receive the
exception information as an Exception object or XML
document.
• Specific exceptions that should be included or excluded
when publishing.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1026
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ExceptionManagerSectionHandler Class
The ExceptionManagerSectionHandler class is used to
read the exception management configuration settings
from the application’s configuration file.
The ExceptionManager Class:
• Declared as Sealed class with a private constructor to
prevent inheritance.
• Exposes a static method Publish that is called from the
application.
• Publish method calls the publishes specified in the
configuration file.
Internal Exception Handling:
• The ExceptionManagement assembly includes an
exception class CustomPublisherException derived from
BaseApplicationException.
• Used to raise internal exceptions if exception is thrown
by custom publisher.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1027
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Publisher interface
The publisher assembly consists of the following 2 interfaces:
• IExceptionPublisher : Defines a single method called Publish which
accepts 3 parameters
• System.Exception object-Representing the exception to publish.
• NameValueCollection object containing the AdditionalInfo
collection.
• NameValueCollection object representing the settings in the
configuration file.
• IExceptionXmlPublisher: It also defines a single method called
Publish which takes the following 2 parameters.
• XmlDocument object representing the Exception information.
• NameValueCollection object representing the settings in the
configuration file.
public interface IExceptionPublisher
{
void Publish( Exception exception, NameValueCollection additionalInfo,
NameValueCollection configSettings);
}
public interface IExceptionXmlPublisher
{
void Publish( XmlDocument exceptionInfo,NameValueCollection configSettings);
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1028
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Publisher Class
There are 2 primary kinds of publisher solutions:
• The DefaultPublisher class.
• Provides a default publisher that implements the
IExceptionPublisher interface.
• Publishes the entire exception chain and any other
information in the Event Log.
• Custom Publisher class.
• Used for creating publisher classes by implementing
IExceptionPublisher or IExceptionXmlPublisher interface.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1029
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Developing Applications using Exception Management
Application Block

The Exception Management Application block is


implemented as two dll’s named:
• Microsoft.ApplicationBlocks.ExceptionManagement.dll
• This is the main exception management assembly.
• It contains the ExceptionManager class, which is used
to publish exceptions.
• This assembly is referred to as the
ExceptionManagement assembly.
• Microsoft.ApplicationBlocks.ExceptionManagement.Inter
faces.dll
• This assembly contains the interface definitions
• Definitions are used by the default publisher in the
ExceptionManagement assembly and by your own
custom publishers.
• This assembly is referred to as the Interfaces
assembly.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1030
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating CustomApplication Exceptions
Our Custom Exception classes should derive from
BaseApplicationException class. Deriving from this class
ensures that our exception type supports the following:
• The computer name where the exception occurred.
• The date and time of the exception.
• The name of the application domain hosting the
application.
• The name of the Thread and windows identities.
• Custom information specified in the configuration files.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1031
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating CustomApplication Exceptions
using System;
using System.Runtime.Serialization;
using Mirosoft.ApplicationBlocks.ExceptionManagement;
[Serializable]
public class LogonException : BaseApplicationException
{
// Default constructor
public LogonException() : base()
{
}
// Constructor with exception message
public LogonException(string message) : base(message)
{
}
// Constructor with message and inner exception
public LogonException(string message, Exception inner): base(message,inner){ }
// Protected constructor to de-serialize data
protected LogonException(SerializationInfo info,StreamingContext context) :
base(info,context) { }
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1032
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Publishing an Exception
using System;
using System.IO;
using System.Windows.Forms;
using Microsoft.ApplicationBlocks.ExceptionManagement;
private bool DoLogon(string userName, string password)
{ try {
using (FileStream fs = new FileStream( "Accounts.dat",
FileMode.Open,
FileAccess.Read ))
{
return CheckUserDetails(fs, userName, password);
}
}
catch (FileNotFoundException ex )
{
throw new LogonException(
"Internal Logon Failure. User file not found", ex );
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1033
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Publishing an Exception
private void btnLogon_Click(object sender, System.EventArgs e)
{
try
{
if ( DoLogon(txtUserName.Text, txtPassword.Text) == true )
{
MessageBox.Show("Your Logon Was Successful");
}
else
{
MessageBox.Show("Logon failed. Invalid user name or password");
}
}
catch( LogonException lex)
{ // publish exception using ExceptionManager
ExceptionManager.Publish( lex );
MessageBox.Show(lex.Message);
}
}
private bool CheckUserDetails( FileStream fs,string username,string password)
{
// access user file and check username and password
return true; // Simulation
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1034
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Quiz
• List the components of the
ExceptionManagement Application block.
• How is it advantageous to use the Application
blocks?
• Enumerate the process flow of Exception
publishing using the ExceptionManagement
Application block.
• Use the ExceptionManagement Application
block for exception handling in your application.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1035
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thank You !

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to NUnit

COE – Current Technologies


Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Objective
• To Learn on how to use write NUnit test cases.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1038
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Prerequisites for the course
• Knowledge of .NET programming.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1039
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
H/w & S/w Required
• NUnit should be installed

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1040
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
1. NUnit
• Introduction
• What is Unit Test
• Why do we need NUnit
• Sample Test Case

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1041
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
What is Unit Test?
Unit Testing – This checks the correctness and
completeness of a module, when treated in
isolation

Basic unit in a .NET program is Class, which is


tested for correctness and completeness in
isolation

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1042
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
What is NUnit?
NUnit is an open source .NET testing framework
used to write
and run repeatable tests.
NUnit features include:
• Assertions for testing expected results
• Test fixtures for sharing common test data
• Test suites for easily organizing and running tests
• Graphical and textual test runners
• Uses an Attribute based programming model
• With features like watching a file/assembly
change events and reloading it as soon as they
are changed ,a developer can perform
development and test cycles sides by side.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1043
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Why is NUnit required ?
• Mistakes are Inevitable It doesn't matter
how much time you put into design and how
careful you are when programming

• Regression Testing ensures, that changes


do not break the system

• NUnit – a savior for .NET Programmers,


performs the regression testing

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1044
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sample Code – To be tested
Consider the following piece of code that needs to
be unit tested
namespace bank{
public class Account{
private float balance;
public void Deposit(float amount){
balance+=amount;
}
  public void Withdraw(float amount){
balance-=amount;
}
public void TransferFunds(Account destination, float amount){
}
  public float Balance{
get{ return balance;}
}
}
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1045
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Writing test case
namespace bank{
using NUnit.Framework;
 [TestFixture]
public class AccountTest{
[Test]
public void TransferFunds(){
Account source = new Account();
source.Deposit(200.00F);
Account destination = new Account();
destination.Deposit(150.00F);
  source.TransferFunds(destination, 100.00F);
Assertion.AssertEquals(250.00F,destination.Balance);
Assertion.AssertEquals(100.00F, source.Balance);
}
}
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1046
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Testing the test case

To create a test case,add the following references to the test case


• Reference of the NUnitTestClass containing the code to test.
• Reference of the nunit.Framework.dll from C:\Program Files\NUnit
V2.1\bin (if nUnit is installed in C:\ ).
• Reference of the nunit.util.dll from C:\Program Files\NUnit
V2.1\bin (if nUnit is installed in C:\ ).
• Import the namespaces in your test case Application as
using NUnit.Framework;

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1047
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Adding reference
• Create a new C# project in VS.Net
• Add the NUnit reference – In the Solution Explorer right
click on the reference and click on add a reference

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1048
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Adding Reference
• Navigate to NunitV2 directory and go into the bin
subdirectory

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1049
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Testing
• Add the test case
• Compile the project
• Start the Nunit- GUI

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1050
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Adding the test case to NUnit GUI
• Go under File->Open and navigate to your projects
“bin” directory .
• Select the exe or dll file of your compiled project and
click Open.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1051
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Testing

Click on Run

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1052
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Examining the results

Green bar indicates the test has succeeded.


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1053
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Examining the results
If a red bar appears the test has failed.
Make corrections in the code as per the
suggestions and re-test your code.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1054
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thank You !

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FxCop 1.32

COE – Current Technologies


Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FxCop - Introduction
FxCop is a code analysis tool that checks managed code
assemblies for conformance to Microsoft .NET Framework
design guidelines plus custom guidelines.

FxCop uses introspection, MSIL parsing, and call graph


analysis to inspect assemblies for more than 200 defects
in the following areas
Library design,
Localization,
Naming conventions,
Performance,
Security.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1057
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FxCop
FxCop includes both GUI and command line versions of
the tool.
FxCop provides XML based test reports.
You can write custom rules based on your company
standards and add-up in FxCop tool to test your
assembly.

Why FxCop

To ensure that coding standards such as naming


conventions, localization etc.
To avoid bad coding and make use of best practices.
Well-formatted test reports.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1058
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FxCop - WorkFlow
Analyse the assemblies
Review the reported messages and determine the
disposition for each:
• Code defect - fix the source code.
• Message is reporting an intentional variance from the rule -
exclude the message.
Exclude items as appropriate.
Correct any code defects detected by FxCop.
Rebuild your assemblies.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1059
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FxCop - Analysis
To create a project and run an FxCop analysis

• Start FxCop from the Start menu, or double-


click FxCop.exe in the
• installation directory.
• From the Project menu, select Add Targets.
• Browse to the assembly (.exe or .dll file) to
add, and click Open.
• Run the analysis by clicking the Analyze button
on the toolbar.
• The analysis report is displayed in the
messages pane.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1060
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FxCop - Analysis

From the Project menu, select Add Targets.


Browse to the assembly to add, and click Open.
Click the Analyze button on the toolbar or
From the Project menu, select Analyze.
Press the F5 function key.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1061
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FxCop - Analysis

• Select a rule library to display only messages generated


by the rules in that library.
• Select a specific rule to display only messages
generated by that rule.
• Select a target to display only messages for that target
and its child nodes.

Filtering is an optional feature that allows you to see a subset of the messages present in a report.
After performing an analysis, you can filter the displayed messages by clicking items in the
configuration pane.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1062
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FxCop - Analysis

The analysis report is saved to an XML file. The XML schema, FxCopReport.xsd, is located in
the \Xml subdirectory installed by FxCop.
This directory also contains XSL style sheets that transform the analysis report XML into formatted
reports.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1063
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FxCop - CommandLine
Command-line options are used to specify the assemblies to be
analyzed, the rules
used to analyze the assemblies, and the location of the output file.

To specify the assemblies and rules, use one of the following:


The /project option, which uses a project saved from the FxCop
application.
The /file and /rule options, which directly specify the assemblies and
rules, respectively.

To specify the location of the output file, use one of the following:
The /out option, which saves the results of an analysis in an XML file.
The /console option, which displays the results in a console window or, if
integrated with Visual Studio, in Visual Studio's Output window.

The following are examples of a minimum command line:


FxCopCmd /p:SomeProject.FxCop /c
FxCopCmd /f:SomeAssembly.dll /r:"C:\Rules
Directory\SomeRules.dll" /o:OutputFile.xml

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1064
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FxCop – Integrate with Visual Studio
To integrate FxCopCmd into Visual Studio, you
must configure Visual Studio to run FxCopCmd
as an external tool.

Once configured, FxCopCmd uses the /console


and /consoleXsl options to send an abbreviated
analysis report, including source code
information if available, to Visual Studio's
Output window.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1065
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FxCop – Integrate with Visual Studio
From the Tools menu in Visual Studio, select External Tools, and then
Add to display the External Tools new configuration dialog box.

1. In the Title text box, type FxCop.


2. To set the value of the Command text
box, browse to the location where
FxCop is installed, and select
FxCopCmd.exe.
3. In the Arguments text box, specify
/console (or /c) in addition to any
command-line options you use when
running the analysis from the
command line.
4. Set the Initial Directory to the location
where FxCopCmd should start.
5. Select the Use Output window check
box.
6. Click OK.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1066
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thank You !

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
HTML

COE – Current Technologies


Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
* For internal use only
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
• Understand HTML
• Understand CSS
• Knowledge on how to use CSS in HTML
• Understand Java Scripts
• Knowledge on how to use Java Scripts in HTML
• Understand DHTML

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1069
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
1. HTML
 Introduction
 Document structure
 Structuring document content with Headings
 The document body
 Text formatting
 Constructing Lists
 Images
 Tables
 Creating Links
 Forms
 Other useful tags
 Scripts

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1070
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction
HTML was originally designed so that scientists could create
text-based documents containing both basic formatting
commands (known as markup) and links to other information
(known as hypertext or hyperlinks).

For instance, a document about earthquakes could contain a


link to another document about plate tectonics written by a
different scientist

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1071
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Document Structure
 All HTML documents are composed of
• An HTML element that describes the document as a HTML
document
• A declarative header section, which is enclosed in the <HEAD>
element
• The main body of the document, which contains the actual
document content. The body can be contained within either the
<BODY> or <FRAMESET> elements.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1072
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Structuring document content with
Headings
• The first markup tag used in any HTML document should be
<HTML> and the last should be </HTML>.
• Then comes the document-header data, which uses <HEAD>
element.
• Eg:
<HTML>
<HEAD>
<TITLE> My first HTML document</TITLE>
<HEAD>
</HTML>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1073
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Structuring document contents with
Headings
<HTML>
<HEAD>
<TITLE> Resume</TITLE>
</HEAD>
<BODY BGCOLOR=“white” TEXT=“black”>
<H1>Employment History</H1>
<H1> Education</H1>
</H2> Undergraduate</H2>
<H2> Graduate</H2>
<H1>Skills</H1>
<H2>Managerial</H2>
<H2>Computer Related</H2>
</H3> Hardware/Software</H3>
<H3> Internet/Web</H3>
<H1>References</H1>
</BODY>
</HTML>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1074
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
The Document Body
• Contains the content of the document.
• Eg:
<HTML>
<HEAD>
<TITLE> MY FIRST HTML DOCUMENT </TITLE>
</HEAD>
<BODY BGCOLOR=“teal” TEXT=“white” LINK=“navy”
VLINK=“maroon”>
</BODY>
</HTML>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1075
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Text Formatting
 Paragraph Element
 <P> The idea of text formatting may at first seem to go
against our previous statements that HTML should only
provide structure for the document.</P>
 Providing Emphasis
 <P> “I <EM> really don’t want to go to school today,” the
little girl said.</P>
 Strong Emphasis
 <P> “I <STRONG> really don’t </STRONG> want to go to
school today,” the little girl said.</P>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1076
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Constructing Lists
 Unordered lists
<P> Vehicles I have owned</P>
<UL>
<LI> 1993 Saturn SL1</LI>
<LI>1996 Ford Contour </LI>
<LI>1999 Ford Ranger</LI>
<UL>
 Ordered lists
<P> Things to do today </P>
<OL>
<LI> Check Email </LI>
<LI> Write a chapter</LI>
<LI> Teach Class <LI>
<OL>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1077
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Constructing Lists
 Definition Lists
<DL>
<DT> RAM
<DD>Random Access Memory</DD>
</DT>
<DT> BIOS
<DD> Basic Input Output System </DD>
</DT>
</DL>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1078
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Images
 <img src="URL">
 Where URL is a complete or partial path to the
source image file to be loaded, including the file
name.
Eg: <b>This is a transparent inline image
<img src="bearico1.gif">
of a bear.</b>
 align=value, allowed values are top, middle, center,
bottom, abstop, absmiddle, absbottom, right, left
Eg: This image is aligned <img src="orb.gif"
align=absmiddle> in the absolute middle of the text line.
This image is aligned in the absolute middle of the text line.
Eg: <img src="image.gif" alt="This is an image.">
The text “This is an image” would display if the image file
image.gif could not be displayed.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1079
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Tables
<TABLE WIDTH=“75%” BORDER=“5” CELLPADDING=“10”>
<TR ALIGN=“RIGHT”>
<TD ROWSPAN=“2”> Seuss’ Fish</TD>
<TD>One Fish</TD>
<TD BGCOLOR=“red”> Red Fish </TD>
</TR>
<TR>
<TD> Two fish</TD>
<TD BGCOLOR=“blue” ALIGN =“CENTER”> Blue Fish </TD>
</TR>
<TR>
<TD COLSPAN=“3” ALIGN=“CENTER”> Learn HTML with Dr.
Seuss!</TD>
</TR>
</TABLE>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1080
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Links
 <a href="URL">Link Text or Object</a>
 <P> Additional details about our new widgets can be found
on the <A HREF=“details.html”>widgets details page</A>
 An image can be used as a link object
<a href="index.html"><img src="return.gif"></a> to the top
level.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1081
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generating Forms
 The form container has two attributes METHOD & ACTION
 Method describes how the data collected by the form should
be sent to the form processor. For most purposes , this value
will be “post”.
 ACTION defines the form processor to be used. Two options
are generally available: an e-mail processor and a CGI script
 The URL defined as the ACTION value points to a CGI script
that will receive and act upon the data sent by the browser
when the user hits the “submit” button.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1082
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Form Input Controls

Text Creates a text input box


Password Creates a specialized input box. The characters entered are
obscured to maintain security.
Checkbox Creates a box which holds a checkmark and acts as a toggle
between an on and off state.
Radio Similar to checkbox, but used for groups. Only one option per group
may be selected at any time.
Submit Creates a standard button used to instruct the browser to apply the
action defined in the <FORM> element
Reset Creates a button which will return all form elements to their original
state.
Textarea Creates a text input area that can contain more than one line.

Each of these control elements takes similar syntax.

<INPUT TYPE= ”Control Type” NAME= ”MyControl”>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1083
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Form Input Controls
. Select Creates an drop down select (or list) box

Syntax

<Select name=”ControlName”>
<Option value=”Value1”>Value2 </option>
.
.
</Select>

Where
Value1 - Value to be submitted to the server
Value2 - Value to be displayed in the browser

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1084
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Other useful tags
 Comment tags
It is often useful to make notes, or comments, inside your HTML files that
will not actually display on the screen.
For Example:
<!–
Author: Eric Schurman
Purpose: Demonstrate comments
Location: Chapter 4
-->
 Meta Tags
This tag can also be used to furnish a number of services not directly
related to the content of the page. Following is a list of some of the tasks
you can accomplish with <META> tags, along with the corresponding code:
 Force a page to refresh after a set number of seconds (5 in the sample below).
<META HTTP-EQUIV="REFRESH" CONTENT="5">

 Force a page to not be cached (stored locally). Some browsers do not support
this feature
<META NAME="Pragma" CONTENT="No-Cache">

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1085
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Other useful tags
 Redirect the user to a different page after a set period of time:
<META HTTP-EQUIV="refresh"
CONTENT="5;URL=http://www.microsoft.com">

 Indicate that the document's contents expired at a point in the past,


which forces the page not to be read from the local cache:
<META HTTP-EQUIV="Expires" CONTENT="Thursday, 18-Jan 96
16:26:30 GMT">

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1086
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Scripts
 Functionality that isn’t available in HTML can be added to
documents using various scripting languages, such as
JavaScript, VBScript etc.
 The <SCRIPT> element is used for this .
 SCRIPT elements can appear in either the HEAD or BODY
elements of a document, depending on the purpose of the
script.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1087
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Advanced topics - Cascaded Style
Sheet Example
MyHtml.html

<HEAD>
<TITLE>SORT POS Force Match Screen</TITLE>
<LINK REL="stylesheet" TYPE="text/css"
HREF="MYSTYLESHEET.CSS">
</HEAD>

<TABLE BORDER="0" CELLSPACING="0" BORDERCOLOR="#5C3317"
BGCOLOR="#c0c0c0" WIDTH="100%">
<TH align="center"HEIGHT="20" class=PageTitleFont>POS Force
Match - Order/POS Inquiry</TH>
<TR> <TD WIDTH="100%" class=TableHeaderFontLeft>
</TD></TR>
</TABLE>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1088
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DHTML

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
DHTML
 What is Dynamic HTML
 Components
 Object Oriented scripting
 Scripting Dynamic Styles
 Creating movement on the Screen

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1090
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
What is Dynamic HTML?
Dynamic HTML is not just one particular technology, language
or set of features. Instead, DHTML comprises a number of
different technologies and describes how these technologies
interact.
In Simple terms, DHTML allows you to use conventional HTML,
script, and a variety of other technologies to dynamically
change how HTML displays text and graphics on a screen.

Making HTML Dynamic

HTML pages are static; generally, the only way to change a


screen display with HTML alone is to load another page.
Internet Explorer versions 4 and 5, however, support an
extensive Document Object Model that exposes all the
elements of a page, including the HTML elements. This allows
any HTML element in Internet Explorer to be manipulated at
any time, even if the page has already been loaded, turning
plain, old HTML into Dynamic HTML

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1091
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
What is Dynamic HTML?
Contd..
For example, let's say that you have a Web page containing
the image shown on this screen.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1092
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
What is Dynamic HTML?
Contd..
If you want to change the image using just HTML, your only real
option is to go to another page that displays a new image. With
Dynamic HTML, you can change the image simply by changing the
attributes of the HTML image tag. This would allow us to create a
page in which the light bulb could be turned on by just clicking it
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function ChangeImage()
{
MyImage.src="bulbon.gif"
}
</SCRIPT>
</HEAD>
<BODY>
<IMG ID="MyImage" SRC="bulboff.GIF"
ALIGN="center" ONCLICK="ChangeImage()">
<B>Click to Turn On!</B> 
</BODY>
</HTML>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1093
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Components
Objects
HTML page contains elements, which are usually defined by opening
and closing tags surrounding specific content. Some elements are
contained within others; a table row (TR) element is contained in a
table element, for example.

Every element on a page is represented in the Dynamic Object Model


as an object, the basic unit of the Object Model.

Examples:
 image
 a span of text
 the body region of an HTML document
Note:
Anything described in the text of an HTML file

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1094
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Components Contd..
Properties
In traditional HTML, you can modify an element by setting its
attributes. The attributes contain information describing that element.

For instance, here is a simple image tag with three HTML attributes:
SRC, WIDTH and ID:
<IMG SRC="oldpic.gif" WIDTH="10" ID="MyImage">
Events
An action or occurrence on the page, such as a mouse click, is referred
to as an event. Here are few examples of events:
 onmousedown
 onmouseover
 onmouseout
 onkeypress
 Onfocus

Note:
The onclick event is a special event that can be fired by either the
mouse or the keyboard.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1095
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Components Contd..
Methods
Methods describe the actions an object can take.

For instance, here is a simple image tag with three HTML


attributes: SRC, WIDTH and ID:
<IMG SRC="oldpic.gif" WIDTH="10" ID="MyImage">

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1096
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Object-Oriented Scripting
Reading and Changing Properties
In Internet Explorer, virtually all properties can be both read and
manipulated through script. In the below code changes the image
height and width attributes dynamically
<HTML>
<HEAD>
<TITLE>Listing 7-1</TITLE>
</HEAD>
<BODY>
<IMG ID="Img1" SRC="circle.gif">
<SCRIPT LANGUAGE="JavaScript">
alert("Img1 has width "+Img1.width+" and height "+Img1.height)
Img1.height=150
Img1.width=30
alert("Now it has width "+Img1.width+" and height "+Img1.height)
</SCRIPT>
</BODY>
</HTML>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1097
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Scripting Dynamic Styles
With dynamic styles in, an element's formatting can be changed
at any time with script.

Dynamic styles in your Web page gives you the ability to


 Change the size, weight, and even the font style of your text in
response to a user's input
 Expand and collapse outlines
 Move items on the screen

Note:
• Use dot notation to read or set a property of style sheet object
Example
<SPAN ID="MySpan" STYLE="color: blue">Hello!</SPAN>
Can be accessed using MySpan.style.color

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1098
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Scripting Dynamic Styles
Example:
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!–
function changeIt(oClicked)
{
oCS=oClicked.style
alert("You clicked the element named "+oClicked.id+".")
alert("It is "+oCS.fontWeight+". Click OK to change it.")
if (oCS.fontWeight==`bold')
{
oCS.fontWeight=`normal‘
}
else
{
oCS.fontWeight=`bold‘
}
}
//-->
</SCRIPT> </HEAD>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1099
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Scripting Dynamic Styles
<BODY>
<SPAN ID=MySpan STYLE="font-weight: bold; cursor: hand"
onclick="changeIt(this)">
Click me! Then click me again!
</SPAN>
</BODY>
</HTML>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1100
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Movement on the Screen
Dynamic styles allows you to precisely position objects at specific
locations on the screen. By changing the properties that specify
location, the objects can be moved
Example:
<HTML>
<HEAD>
<TITLE>Listing 15-4</TITLE>
<STYLE>SPAN {position:absolute}</STYLE>
<SCRIPT LANGUAGE="JavaScript">
function moveSpans()
{
Span1.style.top=15
Span2.style.posTop=Span2.style.posTop+1
Span3.style.left=10
Span4.style.top=window.event.y
Span5.style.posLeft=window.event.x
Span6.style.pixelTop=window.event.x
Span6.style.posLeft=window.event.y
}
</SCRIPT>
</HEAD>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1101
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Movement on the Screen
<BODY onmousemove="moveSpans()">
<SPAN ID="Span1" STYLE="top: 0; left: 0">First Span</SPAN>
<SPAN ID="Span2" STYLE="top: 50; left: 50">Second
Span</SPAN>
<SPAN ID="Span3" STYLE="top: 100; left: 100">Third
Span</SPAN>
<SPAN ID="Span4" STYLE="top: 150; left: 150">Fourth
Span</SPAN>
<SPAN ID="Span5" STYLE="top: 200; left: 200">Fifth
Span</SPAN>
<SPAN ID="Span6" STYLE="top: 250; left: 250">Sixth
Span</SPAN>
</BODY>
</HTML>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1102
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Exercises

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Exercise 1
1. Design an HTML page with following information
• Page heading as “Employee Information System” with
 font-style: italic
 font-size: 24pt
 color: Blue
• Following input controls
 Employee Number - text box
 Should allow only Numbers
 Employee Name - text box
 Should allow both alphabets and Special Characters
 Date of Birth - text box
 Should be less than current date
 Grade – Select box
 Location [Chennai – Bangalore] – Radio button
 Basic Salary – Text box
 Should allow only whole numbers
 HRA
 Should allow only whole numbers
 PF
 Should allow only whole numbers

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1104
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Exercise 1
• Following buttons
 Clear
 Should clear user inputs
 Validate
 Should validate user inputs
 Should calculate the Gross and Net salary
 Display Gross and Net Salary in the same page

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1105
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
CSS

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
CSS
 Introduction
 In-Line Styles
 Style Sheets
 Style Sheets – Global Style sheets
 Style Sheets – Linked Style sheets
 Classes
 Links

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1107
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction
The Cascading Style Sheets (CSS) specification was developed
by the World Wide Web Consortium (W3C) to provide a simple
model that separates the style of a document from the content.

Example
A style sheet can be created that defines <H1> tags as bold 24-
point Verdana type with a 1-centimeter white border and a red
background. Changing this one definition can change the
appearance of all <H1> tags on the site.

Advantages:
 Changing style of document can be done with a few simple
tweaks to the document style
 We can alter everything from the size, style, and color of
text to the spacing between letters and lines, the border and
padding around elements, and the exact position of an
object on the page.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1108
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
In-Line Styles
An in-line style is a style applied to a particular tag on a Web page.
You can apply an in-line style to any tag on a page by using the
STYLE attribute Like other attributes, STYLE affects only the tag
that contains it, just as setting the WIDTH attribute for an image
affects only that image. Therefore, in-line styles are most useful
for precise control of a single element, rather than for large-scale
changes to an entire page or site.
Example:
<HTML>
<HEAD>
<TITLE>Listing 11-3</TITLE>
</HEAD>
<BODY>
<SPAN STYLE="font-weight: bold; font-style: italic">
This text is in a SPAN.
</SPAN>
<BR> This text is not in a SPAN.
</BODY>
</HTML>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1109
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Style Sheets
 A style sheet consists of one or more style
definitions (also called style rules).

 A style sheet can be contained within a Web


document or kept in a file outside the document.
 A style definition is made up of a selector followed
by a declaration block

Example
SPAN {font-weight: bold; font-style: italic}

Note:
 declaration block follows the selector and is enclosed
in curly braces
 list of style declarations, separated by semicolons

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1110
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Style Sheets - Global Style Sheets
Global Style Sheets
A global (or embedded) style sheet is included as part of
the HTML in a document. This type of style sheet defines
its boundaries by the <STYLE> and </STYLE> tags and
must be placed in the header region of the HTML
document.
Example 1:
<HTML>
<HEAD>
<STYLE>SPAN {font-weight: bold; font-style: italic}
</STYLE>
</HEAD>
<BODY>
<SPAN>This text is in a SPAN. </SPAN>
<BR> This text is not in a SPAN.<BR>
<SPAN>This text is in a SPAN. </SPAN>
<BR> This text is not in a SPAN.<BR>
<SPAN>This text is in a SPAN. </SPAN>
<BR> This text is not in a SPAN.<BR>
</BODY>
</HTML>
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1111
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Style Sheets - Global Style Sheets
Example 2:
<HTML>
<HEAD>
<TITLE>Listing 11-6</TITLE>
<STYLE>
H1 {font-size: 16pt; font-weight: bold; color: red}
H2 {font-style: italic; font-size: 24pt; color: green}
SPAN {font-weight: bold; font-style: italic}
</STYLE>
</HEAD>
<BODY>
<SPAN>This text is in a SPAN.</SPAN>
<H1>This text is in an H1.</H1>
<H2>This text is in an H2.</H2>
</BODY>
</HTML>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1112
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Style Sheets - Linked Style Sheets
Linked Style Sheets
The formatting flexibility described in the preceding
sections does not end at the level of the single Web
page; you can control styles across several pages or
even across an entire Web site by using linked style
sheets.

A linked (or external) style sheet is simply a text file


that includes style definitions; it is saved using the CSS
filename extension.

The file, which is external to the HTML file, can be


referenced by (or linked to) an HTML document that
uses the HTML <LINK> tag.
Example:
sample.css
H1 {font-size: 16pt; font-weight: bold; color: red}
H2 {font-style: italic; font-size: 24pt; color: green}
SPAN {font-weight: bold; font-style: italic}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1113
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Style Sheets - Linked Style Sheets
Sample.html

<HTML>
<HEAD>
<TITLE>Listing 11-8</TITLE>
<LINK HREF=“sample.css" REL="STYLESHEET"
TYPE="text/css">
</HEAD>
<BODY>
<SPAN>This text is in a SPAN.</SPAN>
<H1>This text is in an H1.</H1>
<H2>This text is in an H2.</H2>
<H2 STYLE="font-size: 36pt">This is modified H2
text.</H2>
</BODY>
</HTML>

Note:
 @import: command enables one style sheet to include
another

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1114
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Classes
CSS supports the creation of classes. Put simply, a class is a
variation of an existing element.
For example, suppose you want to use the <B> tag
throughout your document, but you want slight variations
depending on where each tag is used.
<HTML>
<HEAD>
<TITLE>Listing 11-11</TITLE>
<STYLE>
B.large {font-size: 24pt}
B.small {font-size: 8pt}
</STYLE>
</HEAD>
<BODY>
<B>This is a standard B.</B>
<B CLASS="small">This uses the small class.</B>
<B CLASS="large">This uses the large class.</B>
</BODY>
</HTML>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1115
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Classes
Note:
 A class is defined by a selector name followed by a
period and the class name
 value is then assigned to the class, using a
statement enclosed in curly braces
 To create a global class that is usable by all
elements, do no specify a particular tag as a
selector
Example:
<STYLE>
.large {font-size: 24pt}
.small {font-size: 8pt}
</STYLE>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1116
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Links
Using dynamic styles, you can also change the
style of the different states of a hypertext link,
which is defined by the anchor tag, <A>.
Example
<HTML>
<HEAD>
<TITLE>Listing 11-13</TITLE>
<STYLE>
A:link {text-decoration: none}
A:hover {color: red; text-decoration: underline}
A:visited {color: green}
</STYLE>
</HEAD>
<BODY>
<A
HREF="http://msdn.microsoft.com">msdn.microsoft.com</A><BR>
<A HREF="http://microsoft.com">microsoft.com</A><BR>
<A HREF="http://www.w3.org/style/">www.w3.org/style</A><BR>
<A HREF="http://www.w3.org">www.w3.org</A><BR>
</BODY>
</HTML>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1117
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thank You !

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML

COE – Current Technologies


Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Course Objectives

• Lean what XML is


• What are the industrial uses of XML
• How to write an XML
• What are XML Parsers and its types
• XSL
• X Path Expressions and Functions
• XSLT Elements

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1120
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Prerequisites for the course
• WWW, HTML and the basics of building Web pages
• Web scripting languages like JavaScript or VBScript

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1121
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Session Plan
• Overview
• Syntax
• XML DTD
• XML Parsers
• Beautification of XML
• XSL
• xPath Expressions
• xPath functions
• XSLT Elements.
• Literal Result Elements
• Conditional formatting
• XSL FO

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1122
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to XML
• XML stands for Extensible Markup Language.
• XML is a cross-platform, software and hardware independent tool for transmitting
information.
• 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.
• XML uses a Document Type Definition (DTD) or an XML Schema to describe the data.
• XML was designed to describe data and to focus on what data is. HTML was designed to
display data and to focus on how data looks.
• The main difference between XML and HTML:
• XML was designed to carry data.
• XML is not a replacement for HTML.
• XML and HTML were designed with different goals:
• HTML is about displaying information, while XML is about describing information.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1123
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to XML
• XML was not designed to DO anything. XML was created to structure, store and to send
information.
• The following example is a note to Tove from Jani, stored as XML:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

• The note has a header and a message body. It also has sender and receiver information.
But still, this XML document does not DO anything. It is just pure information wrapped in
XML tags. Someone must write a piece of software to send, receive or display it.
• XML documents are meant to be like Web pages, and viewed in a browser
• There are "browsers" or other tools that are meant to be used with XML
• XML creates "pages" similar to HTML

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1124
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to XML - Viewing XML Files
• To view an XML document in IE 5.0 (and higher) you can click on a link, type the URL in the address
bar, or double-click on the name of an XML file in a files folder. If you open an XML document in IE, it
will display the document with color coded root and child elements. A plus (+) or minus sign (-) to the
left of the elements can be clicked to expand or collapse the element structure. If you want to view the
raw XML source, you must select "View Source" from the browser menu.

• To view an XML document in Netscape 6 you'll have to open the XML file and then right-
click in XML file and select "View Page Source". If you open an XML document in Netscape
6, it will display the document with color coded root and child elements.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1125
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to XML
• XML tags are not predefined.
• The tags used to mark up HTML documents and the structure of HTML documents are
predefined. The author of HTML documents can only use tags that are defined in the
HTML standard (like <p>, <h1>, etc.).
• XML allows the author to define his own tags and his own document structure.
• The tags in the example above (like <to> and <from>) are not defined in any XML
standard. These tags are "invented" by the author of the XML document.
• Below is a sample xml portraying the “Plant Catalog”, which describes each plant in terms
of below parameters/properties.
• BOTANICAL name
• COMMON name
• ZONE
• LIGHT
• PRICE
• AVAILABILITY
Exercise: Write an XML to describe employees in your organization.

plant_catalog.xml

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1126
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Uses of XML
• XML was designed to store, carry, and exchange data
• XML can Separate Data from HTML. With XML, data is stored outside the HTML.
• When HTML is used to display data, the data is stored inside the HTML. With XML, data can be stored in
separate XML files. This way developer can concentrate on using HTML for data layout and display, and
be sure that changes in the underlying data will not require any changes to the display HTML.
• XML data can also be stored inside HTML pages as "Data Islands". One can still concentrate on using
HTML only for formatting and displaying the data.
• E.g.: The unofficial <xml> tag is used to embed XML data within HTML. XML data can be embedded
directly in an HTML page like this:
<html>
<body>
<xml id="cdcat" src="cd_catalog.xml"></xml>
<table border="1" datasrc="#cdcat">
<tr>
<td><span datafld="ARTIST"></span></td>
<td><span datafld="TITLE"></span></td>
</tr>
</table>
</body>
</html>

cd_catalog.xml

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1127
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Uses of XML
• With XML, data can be exchanged between incompatible systems.
• In the real world, computer systems and databases contain data in incompatible formats. One of
the most time-consuming challenges for developers has been to exchange data between such
systems over the Internet.
• Converting the data to XML can greatly reduce this complexity and create data that can be read by
many different types of applications.
• With XML, plain text files can be used to share data.
• Since XML data is stored in plain text format, XML provides a software- and hardware-independent
way of sharing data.
• This makes it much easier to create data that different applications can work with. It also makes it
easier to expand or upgrade a system to new operating systems, servers, applications, and new
browsers.

• With XML, plain text files can be used to store data.


• XML can also be used to store , exchange, import and export data in files or in
databases. Applications can be written to store and retrieve information from the store,
and generic applications can be used to display the data.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1128
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Uses of XML
• With XML, your data is available to more users.
• Since XML is independent of hardware, software and application, you can
make your data available to other than only standard HTML browsers.
• Other clients and applications can access your XML files as data sources,
like they are accessing databases. Your data can be made available to all
kinds of "reading machines" (agents).
• XML can be used to Create new Languages
• XML is the mother of WAP and WML.
• The Wireless Markup Language (WML), used to markup Internet applications
for handheld devices like mobile phones, is written in XML.

Exercise: List any other 3-5 uses of XML

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1129
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DAY1: Syntax
• XML Syntax
• XML Elements
• XML Validation - Well Formed XML
• XML Validation - Valid XML

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1130
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML Syntax
• XML documents use a self-describing and simple syntax.
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
• The first line in the document - the XML declaration - defines the XML version and the
character encoding used in the document. In this case the document conforms to the 1.0
specification of XML and uses the ISO-8859-1 (Latin-1/West European) character set.
• The next line describes the root element of the document (like it is saying: "this
document is a note"):
• The next 4 lines describe 4 child elements of the root (to, from, heading, and body):
• And finally the last line defines the end of the root element:

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1131
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML Syntax
• XML elements must have a closing tag. With XML, it is illegal to omit the closing tag.
• In HTML some elements do not have to have a closing tag. The following code is legal in
HTML:
<p>This is a paragraph
<p>This is another paragraph
• In XML all elements must have a closing tag, like this:
<p>This is a paragraph</p>
<p>This is another paragraph</p>
• XML declaration is not required to have a closing tag. This is not an error. The declaration is not
a part of the XML document itself. It is not an XML element, and it should not have a closing tag.
• XML tags are case sensitive
• Unlike HTML, XML tags are case sensitive.
• With XML, the tag <Letter> is different from the tag <letter>.
• Opening and closing tags must therefore be written with the same case:
<Message>This is incorrect</message>
<message>This is correct</message>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1132
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML Syntax
• Improper nesting of tags makes no sense to XML.
• In HTML some elements can be improperly nested within each:
 <b><i>This text is bold and italic</b></i>.

• In XML all elements must be properly nested:


 <b><i>This text is bold and italic</i></b>

• All XML documents must contain a single tag pair to define a root element. All other
elements must be within this root element. All elements can have sub elements (child
elements). Sub elements must be correctly nested within their parent element:
E.g.: <root>
<child>
<subchild>.....</subchild>
</child>
</root>
• XML elements can have attributes in name/value pairs just like in HTML. In XML the
attribute value must always be quoted. Study the two XML documents below. The first
one is incorrect, the second is correct:

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1133
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML Syntax
<?xml version="1.0" encoding="ISO-8859-1"?>
<note date=12/11/2002>
<to>Tove</to>
<from>Jani</from>
</note>
<?xml version="1.0" encoding="ISO-8859-1"?>
<note date="12/11/2002">
<to>Tove</to>
<from>Jani</from>
</note>
The error in the first document is that the date attribute in the note element is not quoted.
Correct date="12/11/2002". Incorrect date=12/11/2002.
• With XML, the white space in your document is not truncated. This is unlike HTML. With
HTML, a sentence like -
Hello my name is Tove,
will be displayed like this:
Hello my name is Tove,
because HTML strips off the white space.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1134
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML Syntax
• With XML, a new line is always stored as LF.
• The syntax for writing comments in XML is similar to that of
HTML.
• <!-- This is a comment -->

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1135
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML Elements
• With XML, documents can be Extended to carry more information. E.g.: Given
<note>
<to>Tove</to>
<from>Jani</from>
<body>Don't forget me this weekend!</body>
</note>
• an application that extracted the <to>, <from>, and <body> elements from the XML document produces below output:
To: Tove
From: Jani
Don't forget me this weekend!
• Imagine that the author of the XML document added[Extended] some extra information to it:
<note>
<date>2002-08-01</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
• The application will still be able to find the <to>, <from>, and <body> elements in the XML document and produce the
same output.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1136
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML Elements
• Elements are related as parents and children. Imagine that this is a
description of a book:. Next slide displays the XML document in the
hierarchical format representing this book.

My First XML
Introduction to XML
 What is HTML
 What is XML

XML Syntax
 Elements must have a closing tag
 Elements must be properly nested

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1137
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML Elements
<book>
<title>My First XML</title>
<prod id="33-657" media="paper"></prod>
<chapter>Introduction to XML
<para>What is HTML</para>
<para>What is XML</para>
</chapter>

<chapter>XML Syntax
<para>Elements must have a closing tag</para>
<para>Elements must be properly nested</para>
</chapter>

</book>
• Book is the root element. Title, prod, and chapter are child elements of book. Book is the
parent element of title, prod, and chapter. Title, prod, and chapter are siblings (or sister
elements) because they have the same parent.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1138
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML Elements
• XML elements can have attributes. In HTML (and in XML) attributes provide additional
information about elements: <img src="computer.gif"> <a href="demo.asp">.
• Attributes are used to provide additional information about elements. Attributes often
provide information that is not a part of the data. In the example below, the file type is
irrelevant to the data, but important to the software that wants to manipulate the element:
• <file type="gif">computer.gif</file>
• Attribute values must always be enclosed in quotes, but either single or double quotes can
be used. For a person's sex, the person tag can be written like this:
• <person sex="female”> or <person sex='female'>

Exercise: Write a program to describe the regional hierarchy in the world. [Ex: for India]
World
Continents
Counteries
States
……….

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1139
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML Validation - Well Formed XML
• A "Well Formed" XML document is a document that conforms
to the XML syntax
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1140
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML Validation - Valid XML
• A "Valid" XML document is a "Well Formed" XML document, which
also conforms to the rules of a Document Type Definition (DTD):
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE note SYSTEM "InternalNote.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Here, the xml being properly structured is not sufficient, but also has to
adhere to the rules specified in the file InternalNote.dtd.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1141
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DAY1: XML DTD
• XML DTD
• XML DTD - Internal
• XML DTD - External

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1142
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML DTD
• DTD (Document Type Definition) defines legal building blocks of an XML
document.
• DTD defines the document structure with a list of legal elements.
• XML provides an application independent way of sharing data. With a DTD,
independent groups of people can agree to use a common DTD for
interchanging data.
• An application can use a standard DTD to verify that the data received from
the outside world is valid. You can also use a DTD to verify your own data.
• A DTD can be declared inline in your XML document, or as an external
reference.
• Following slides give an overview of internal and external DTDs. For further
information on DTD, refer to http://xmlfiles.com/dtd/dtd_building.asp site.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1143
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML DTD - Internal
• This is an XML document with a Document Type Definition:
<?xml version="1.0"?>
<!DOCTYPE note [
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
• The DTD is interpreted like this:
!ELEMENT note (in line 2) defines the element "note" as having four elements: "to,from,heading,body".
!ELEMENT to (in line 3) defines the "to" element to be of the type "CDATA".
!ELEMENT from (in line 4) defines the "from" element to be of the type "CDATA"
and so on.....

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1144
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML DTD - External
• This is the same XML document with an external DTD:
<?xml version="1.0"?>
<!DOCTYPE note SYSTEM "note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
• This is a copy of the file "note.dtd" containing the Document Type Definition:
<?xml version="1.0"?>
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1145
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DAY1: XML Parsers
• XML Parsers
• XML DOM Parsers
• XML SAX Parsers

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1146
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML Parsers
• A parser is a program that initially reads through the XML file and transforms
the information into some form that another program can use directly.
• In order to process XML data, every program or server process needs an XML
parser. The parser extracts the actual data out of the textual representation
and creates either events or new data structures from them.
• XML parser is used to read and update - create and manipulate - an XML
document. An XMLparser is a processor that reads an XML document and
determines the structure and properties of the data.
• A generalized XML parser reads XML files and generates a hierarchically
structured tree, then hands off data to viewers and other applications for
processing. A validating XML parser also checks the XML syntax and reports
errors. It goes beyond the XML rules for well formed and validates the
document against an XML DTD, the parser is said to be a "validating" parser

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1147
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML Parsers
• There are two different kinds of XML parsers.
• Non Validating Parser: These parser do not check a document
against any DTD (Document Type Definition). It is only checked
whether the document is properly marked up according to XML
syntax rules(well-formed or not).
• Validating Parser: checks, whether the document is valid. The
parser verifies that the document conforms to a specific DTD
(either internal or external to the XML file being parsed).

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1148
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML Parsers
• Parsers are different not only in their support for checking and
transforming documents but also in the way they read a document.
• Event-based parsers read the text sequentially, and whenever a
start or end tag appears an event is sent to the application. The
Simple API for XML (SAX) is such an API.
• With the second approach the parser builds a hierarchical data
structure from the content of the document. This is how the
Document Object Model (DOM) API works, similar to the HTML
document tree in a Web browser.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1149
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML DOM Parsers
• XML parser is used to load an XML document into the memory of the
computer. When the document is loaded, its information can be retrieved
and manipulated by accessing the DOM.
• The DOM represents a tree view of the XML document.
• A DOM tree is composed of nodes that result from parsing an XML
document. A node is the in-memory representation of an XML entity. The
standard W3C DOM model has several types of nodes. For example, a
text node represents a block of text in the XML document, an element
node represents an element of the XML document, and an attribute node
represents the name and value of an attribute placed within an element.
• The DOM is a tree because (except for the root or document node) every
other node has a parent. For example, attribute nodes are always
associated with an element node, while the text enclosed within the
element's open tag and close tag is mapped to a text node. The text
node is a child node of the element node. So, representing even a very
simple form of XML document may require multiple node types .

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1150
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XML SAX Parsers
• The Simple API for XML or SAX is faster and more efficient than using the DOM. SAX is a
Java based API that is very robust and effective. These SAX parsers make it easy for you to
start using the Simple API for XML.
• Unlike DOM (Document Object Model) which creates a tree based representation for the
information in your XML documents, SAX does not have a default object model. This means
that when you create a SAX parser and read in a document (unlike DOM) you will not be
given a default object model. A SAX parser is only required to read in your XML document
and fire events based on the things it encounters in your XML document. Events are fired
when the following things happen:
 open element tags are encountered in your document
 close element tags are encountered in your document
 #PCDATA and CDATA sections are encountered in your document
 processing instructions, comments, entity declarations, are encountered in your document.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1151
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thank
You !

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Java Script

COE – Current Technologies


Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
Java Script
• Introduction
• Operators
• Statements
• Core Objects
• Document Objects
• Window Objects
• Form Objects
• Events

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1154
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction
JavaScript is a compact, object-based scripting language for
developing client and server Internet applications.

The significant advantage of Java Scripts is that scripts run on the


client side. Once a page has been downloaded, all its scripts run
on the user's browser rather than on a server that might be
halfway around the world.

Anyone who views your Web pages with a script-capable browser


can use your scripts without installing any extra software—and
potentially without even knowing that scripts are being used. To
the viewer, scripts are seamless and invisible.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1155
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Operators
 Arithmetic
 String
 Logical
 Bitwise
 Assignment
 Comparison
 Special

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1156
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Operators - Arithmetic
 + (Addition) Adds 2 numbers.
 ++ (Increment) Adds one to a variable representing
a number
 - (Unary negation, subtraction) As a unary
operator, negates the value of its argument.
As a binary operator, subtracts 2 numbers.
 -- (Decrement) Subtracts one from a variable
representing a number (returning either the
new or old value of the variable)
 * (Multiplication) Multiplies 2 numbers.
 / (Division) Divides 2 numbers.
 % Computes the integer remainder of dividing 2
numbers.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1157
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Operators - String
 + (String addition) Concatenates 2 strings.
 += Concatenates 2 strings and assigns the result to the first
operand.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1158
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Operators - Logical
 && (Logical AND) Returns true if both logical operands are
true. Otherwise, returns false.
 || (Logical OR) Returns true if either logical expression is true.
If both are false, returns false.
 ! (Logical negation) If its single operand is true, returns
false; otherwise, returns true.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1159
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Operators - Bitwise
 & (Bitwise AND) Returns a one in each bit position if bits
of both operands are ones
 ^ (Bitwise XOR) Returns a one in a bit position if bits of one
but not both operands are one.
 | (Bitwise OR) Returns a one in a bit if bits of either
operand is one.
 ~ (Bitwise NOT) Flips the bits of its operand.
 << (Left shift) Shifts its first operand in binary representation the
number of bits to the left specified in the second operand,
shifting in zeros from the right.
 >> (Sign-propagating right shift) Shifts the first operand in
binary representation the number of bits to the right
specified in the second operand, discarding bits shifted off.
 >>> (Zero-fill right shift) Shifts the first operand in binary
representation the number of bits to the right specified
in the second operand, discarding bits shifted off, and shifting
in zeros from the left.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1160
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Operators - Assignment
 = Assigns the value of the second operand to the first operand
 += Adds 2 numbers and assigns the result to the first.
 -= Subtracts 2 numbers and assigns the result to the first.
 *= Multiplies 2 numbers and assigns the result to the first.
 /= Divides 2 numbers and assigns the result to the first.
 %= Computes the modulus of 2 numbers and assigns the result
to the first.
 &= Performs a bitwise AND and assigns the result to the first
operand.
 ^= Performs a bitwise XOR and assigns the result to the first
operand.
 |= Performs a bitwise OR and assigns the result to the first operand.
 <<= Performs a left shift and assigns the result to the first operand.
 >>= Performs a sign-propagating right shift and assigns the result to
the first operand.
 >>>= Performs a zero-fill right shift and assigns the result to the first
operand.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1161
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Operators - Comparison
 == Returns true if the operands are equal.
 != Returns true if the operands are not equal.
 > Returns true if left operand is greater than right
operand.
 >= Returns true if left operand is greater than or equal to
right operand.
 < Returns true if left operand is less than right operand.
 <= Returns true if left operand is less than or equal to right
operand.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1162
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Operators - Special
 ?: Lets you perform a simple "if...then...else”
 , Evaluates two expressions and returns the result of the
second expression.
 delete Lets you delete an object property or an element at a
specified index in an array.
 new Lets you create an instance of a user-defined object type
or of one of the built-in object types.
 this Keyword that you can use to refer to the current object.
 typeof Returns a string indicating the type of the unevaluated
operand.
 void The void operator specifies an expression to be
evaluated without returning a value.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1163
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Statements
 break
 continue
 do….while
 for
 for…in
 function
 if….else
 return
 switch
 var

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1164
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Core Objects
 Array Represents an array.
 Boolean Represents a Boolean value.
 Date Represents a date.
 Function Specifies a string of JavaScript code to be compiled
as a function.
 Math Provides basic math constants and functions; for
example, its PI property contains the value of pi.
 Number Represents primitive numeric values
 Object Contains the base functionality shared by all
JavaScript objects.
 String Represents a JavaScript string.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1165
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Date-object

 JavaScript lets you use some predefined objects. This is for


example the Date-object, the Array-object or the Math-
object. There are several other objects - please refer to the
documentation provided by Netscape for a complete
reference. As the name implies this object lets you work
with time and date.
 today= new Date()
 This creates a new Date-object called today
 In order to get another date and time we can use another
constructor (this is the Date() method which is called
through the new operator when constructing a new Date-
object):
 today= new Date(1997, 0, 1, 17, 35, 23)
 This will create a Date-object which represents the first of
January 1997 at 17:35 and 23 seconds. So you specify the
date and time like this:
 Date(year, month, day, hours, minutes, seconds)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1166
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Functions
Functions
 We will use functions in most of our JavaScript programs. Basically
functions are a way for bundling several commands together.
<html>
<script language="JavaScript">
<!-- hide
function myFunction()
{
document.write("Welcome to my homepage!<br>");
document.write("This is JavaScript!<br>");
}
myFunction();
myFunction();
myFunction();
// --></script>
</html>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1167
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Functions
 Functions can also be used in combination with event-
handlers.

// -->
<html>
</script>
<head>
</head>
<script
<body>
language="JavaScript">
<form>
<!-- hide
<input type="button"
function calculation() {
value="Calculate"
var x= 12;
onClick="calculation()">
var y= 5;
</form>
var result= x + y;
</body>
alert(result);
</html>
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1168
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Array-object
 Arrays can be seen as many variables bundled together. You can
access them through one name and a number. Let's say out array is
called names. Then we can access the first name through names[0].
The second name is called name[1] and so on. Since JavaScript 1.1
(Netscape Navigator 3.0) you can use the Array-object. You can
create a new array through
 myArray= new Array().
 Now you can assign values to this array:
 myArray[0]= 17;
 myArray[1]= "Stefan";
 myArray[2]= "Koch";
 JavaScript arrays are really flexible. You do not have to bother
about the size of the array - its size is being set dynamically. If you
write myArray[99]= "xyz" the size of the array get 100 elements (a
JavaScript array can only grow - it hasn't got the ability to shrink.
So keep your arrays as small as possible.).
 It doesn't matter if you store numbers, strings or other objects in an
array

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1169
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
String-object
 The string object offers properties and methods to perform a
variety of manipulations on a given string.
 The Math object provides those functions and methods
necessary to perform mathematical calculations, from PI
value to trigonometric functions.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1170
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Methods of the string Object

anchor() Surrounds the string with an anchor tag


big() Surrounds the string with the BTML BIG
tag
charAt() Given an index as an argument, returns
the character at the specified index
strike() Surrounds the string with the HTML
strike tag
substring() Given two indexes, returns the substring
starting at the first index and ending
with the character before the last index.
If the second index is greater , the
substring starts with the second index
and ends with the character before the
first index.
toLowerCase() Makes the entire string lowercase
toUpperCase() Makes the entire string uppercase
split() Returns an array of strings by splitting
the string into substrings at a separator
passed to the method as the argument.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1171
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Methods of Math Object
random() Returns a random no between zero and one
round() Rounds a no to the nearest integer
sin() Calculates the sine of a no
sqrt() Calculates the square root of a no
pow() Calculates the value of one no to the power
of a second no- takes two arguments
Min() Returns the least of two nos
Log() Calculates the natural logarithm of a no
Floor() Returns the next integer less than or equal to
a number

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1172
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Document Objects
 Document :-Contains information about the
current document, and provides methods for
displaying HTML output to the user.
 The following are event handlers for the document
object.
 onClick , onDblClick , onKeyDown , onKeyPress ,
onKeyUp, onMouseDown , onMouseUp

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1173
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Window Objects
 Frame A window that can display
multiple,independently scrollable frames on a single
screen, each with its own distinct URL.
 History Contains an array of information on the URLs
that the client has visited within a window.
 Location Contains information on the current URL.
 screen Contains properties describing the display
screen and colors.
 Window Represents a browser window or frame. This
is the top-level object for each document,
Location, and History object group.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1174
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Window
Creating windows
• Opening new browser windows is a great feature of
JavaScript. You can either load a new document (for
example a HTML-document) to the new window or you
can create new documents (on-the-fly).
<html> <body>
<form>
<head>
<input type="button" value="Open
<script new window" onClick="openWin()">
language="JavaScript">
</form>
<!-- hide
</body>
function openWin() </html>
{
myWin= open("bla.htm");
} function openWin2()
// --> {
myWin= open("bla.htm",
</script> "displayWindow",
</head> "width=400,height=300,status=no,toolb
ar=no,menubar=no");
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1175
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Window
 The name of a window As you have seen we have used
three arguments for opening a window:
myWin= open("bla.htm", "displayWindow",
"width=400, height=300, status=no,
toolbar=no,menubar=no");
 What is the second argument for? This is the name of the
window. We have seen how to use the target-property
earlier. If you know the name of an existing window you can
load a new page to it with <a href="bla.html"
target="displayWindow">
 Here you need the name of the window (if the window does
not exist, a new window is created through this code). Please
note that myWin is not the name of the window. You can just
access the window through this variable. As this is a normal
variable it is only valid inside the script in which it is defined.
The window name (here displayWindow) is a unique name
which can be used by all existing browser windows.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1176
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Window
Closing windows
 You can close windows through JavaScript. For this
you need the close() method. Let's open a new window
as shown before. In this window we load the following
page:
<html>
<script language="JavaScript">
<!-- hide
function closeIt()
{
window.close();
}
</script>
</html>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1177
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Form Objects
 Button A push button on an HTML form.
 Checkbox A checkbox on an HTML form.
 FileUpload A file upload element on an HTML form.
 Form Lets users input text and make choices
from Form elements such as checkboxes, radio
buttons, and selection lists.
 Hidden A Text object that is suppressed from
form display on an HTML form.
 Password A text field on an HTML form that
conceals its value by displaying asterisks (*).
 Radio A set of radio buttons on an HTML form.
 Reset A reset button on an HTML form.
 Select A selection list on an HTML form.
 Submit A submit button on an HTML form.
 Text A text input field on an HTML form.
 Textarea A multiline input field on an HTML form.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1178
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Form Objects Contd…
Validating form input
• Forms are widely used on the Internet. The form input is often
being sent back to the server or via mail to a certain e-mail
account. But how can you be certain that a valid input was done by
the user? With the help of JavaScript the form input can easily be
checked before sending it over the Internet.
• Setting the focus to a certain form-element with the help of the
focus() method you can make your form a little bit more user-
friendly. You can define which element is in focus at the beginning.
You can do this with the following piece of script:
function setfocus()
{
document.first.text1.focus();
}
• This script would set the focus to the first text-element in the script
I have shown above. You have to specify the name of the whole
form - which is called first here - and the name of the single form
element - here text1. If you want to put the focus on this element
when the page is being loaded you can add an onLoad-property to
your <body> tag. This looks like this:
<body onLoad="setfocus()">

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1179
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Form Objects Contd…
We can extend this with the following code:
function setfocus() {
document.first.text1.focus();
document.first.text1.select();
}
 Evaluating a form using the button element
<HTML>
<HEAD>
<TITLE>button Example</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS
function calculate(form)
{
form.results.value = eval(form.entry.value);
}
// STOP HIDING FROM OTHER BROWSERS -->
</SCRIPT>
</HEAD>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1180
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Form Objects Contd…
<BODY>
<FORM METHOD=POST>
Enter a JavaScript mathematical expression:
<INPUT TYPE="text" NAME="entry" VALUE=""><BR>
The result of this expression is:
<INPUT TYPE=text NAME="results“
onFocus="this.blur();">
<BR>
<INPUT TYPE="button" VALUE="Calculate"
onClick="calculate(this.form);">
</FORM>
</BODY>
</HTML

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1181
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Events
Events and event handlers are very important for
JavaScript programming. Events are mostly caused
by user actions. If the user clicks on a button a Click-event
occurs. If the mouse pointer moves across a link a
MouseOver-event occurs. There are several different
events.
We want our JavaScript program to react to certain
events. This can be done with the help of event-handlers.
A button might create a popup window when clicked. This
means the window should pop up as a reaction to a Click-
event. The event-handler we need to use is called
onClick.
<form>
<input type="button" value="Click me" onClick="alert('Yo')">
</form>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1182
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Events
<html>
<head>
<title> Events </title>
<script>
<!--hide from other browsers
var name=“”;
//stop hiding from other browsers-->
</script>
</head>
<body onLoad=“name=prompt(‘enter your name:’,’Name”);
alert (‘Greetings’ + name+’, welcome to my page!’);”
onUnload= “alert(‘goodbye’+name+’,sorry to see you go!’);”>
<img src=“title.gif”>
</body>
</html>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1183
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Application Development
with ASP.NET 2.0

COE – Current Technologies


Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Session Topics

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Discussion Topics
Introduction
• An E-Commerce Web Site scenario
• ASP.NET Architecture
• Web Application Development
• Web Application folders

Features
Featuresadded
addedininASP.NET2.0
ASP.NET2.0
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1186
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Discussion Topics
Web Forms
• ASP.NET Process
• Application Lifecycle and Events
• Page Life cycle
• Compilation Life cycle
• ASP.NET Objects
Master Pages
Themes
• Skins
• Style Sheets

Features
Featuresadded
addedininASP.NET2.0
ASP.NET2.0
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1187
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Discussion Topics
ASP.NET Controls
• HTML Controls
• Standard Server Controls
• Login Controls
• Validation Controls
• Navigation
Advanced Controls
• User Controls
• Composite Controls
• Custom Controls
• Web parts

Features
Featuresadded
addedininASP.NET2.0
ASP.NET2.0
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1188
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Discussion Topics
Server Side Data Access
• Data Binding Model
Data Controls
• Data Source Controls
• Data Bound Controls
 DataGrid
 GridView
 DataList
 DetailsView
 FormView
 Repeater

Features
Featuresadded
addedininASP.NET2.0
ASP.NET2.0
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1189
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Discussion Topics
Web Application Management
• State Management
 Client Side state Management
 Server Side state Management
• Caching Techniques
 OutputCaching
 FragmentCaching
 DataCaching
 PostCacheSubstitution
• Tracing and Logging
• Exception Handing
 ErrorPages
 CustomExceptions

Features
Featuresadded
addedininASP.NET2.0
ASP.NET2.0
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1190
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Discussion Topics
Web Site Management
• Web site Configuration
 Web Administration Tool
• Security
 Authentication
 Windows
 Forms
 Digest
 Authorization
 Allow/Roles/Verbs
• Health Monitoring
• Deployment

Features
Featuresadded
addedininASP.NET2.0
ASP.NET2.0
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1191
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to ASP.NET

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET 2.0 Features
Controls

Data Login Other New


Web Parts
Controls Controls Controls
Framework

Themes Improved Compilation


Page

Master Pages
and Skins Client Scripting & Localization

Role
Membership Profiles Configuration
and APIs

Management
Services

Site Health Other New


Maps Monitoring Services

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1193
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET 2.0 Features
ASP.NET “Control Buckets”

Security
Security Data
Data Navigation
Navigation Web
WebParts
Parts

ASP.NET “Page Framework” Features

Master
MasterPages Themes/Skins Localization Adaptive
Pages Themes/Skins Localization AdaptiveUIUI

ASP.NET “Building Block” APIs

Membership
Membership Role
RoleManager
Manager Personalization
Personalization

Site
SiteNavigation
Navigation Database
DatabaseCaching
Caching Management
Management
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1194
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Web Application Scenario
• An E-Commerce Web
Site scenario
 Consumer viewpoint
 Website interface to
view product listing,
description and make
orders.
 Retailer viewpoint :
 Provide services to
validate credit card
payment and deliver
products through
courier service.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1195
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Web Architecture

“A“Aweb
webapplication
applicationininASP.NET
ASP.NETisisaacollection
collectionofofpages,
pages,
controls,
controls,code
codemodules,
modules,and
andservices
servicesallallrunning
runningunder
underaasingle
singleweb
web
server
serverapplication
applicationdirectory
directory(usually
(usuallyIIS)
IIS)“ “
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1196
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Layered Architecture

Presentation
PresentationTier
Tier UI Pages Web Form
(.htm) (.aspx)

User Controls Code-Behind File Graphic


(.ascx) (.aspx.vb or .aspx.cs) Files

Business
BusinessLogic
LogicTier
Tier
Proxy ADO.NET RCW

XML Web Services .NET COM COM+


(.asmx) Objects Objects Services

Data
DataTier
Tier Data Source

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1197
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Namespaces
ASP.NET Namespaces

System.Web
Services UI
Description HtmlControls

Discovery WebControls

Protocols

Caching Security
Configuration SessionState

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1198
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Web Application
Development
Web Site Options:
1 Choose Installed Templates
ASP.NET Web Site 1
2 Choose Locations:
File System:
An Web Application in VS2005
runs in a default development Server using
any ports available. The application itself is
stored in the file system which could be later
copied into Web Server during deployment.
HTTP: 2

To work under the Web Server


FTP:
To work with web applications and
code that reside in a remote server
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1199
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Web site Development
Code Behind Model
1

1 Default.aspx -HTML File

2 Default.aspx.cs -C# File


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1200
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Web Forms

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Web Forms
Topics for Discussion
• ASP.NET Web Application Files and Folders
• ASP.NET Process
• Application Lifecycle and Events
• Page Life cycle
• Compilation Life cycle
• ASP.NET Objects

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1202
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Application file extensions
Type Extension
Solution .sln
Project File .csproj

ASP.NET Page File .aspx


.aspx.cs (code
behind)
ASP.NET User Control .ascx
File .ascx.cs (code
behind)
ASP.NET WEB Service asmx
asmx.cs (code
behind)
Library File .cs

Configuration File .config


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1203
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Application folders
Folder Description

App_Browsers Contains browser definitions


(.browser files) that ASP.NET uses
to identify individual browsers and
determine their capabilities..
App_Code Contains source code for utility
classes and business objects (for
example, .cs, .vb, and .jsl files)
App_Data Contains application data files
including MDF files, XML files, as
well as other data store files.
App_GlobalResourc Contains resources (.resx and
es .resources files) that are compiled
into assemblies with global scope
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1204
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Application folders
Folder Description
App_LocalResource Contains resources (.resx and
s .resources files) that are associated
with a specific page, user control,
or master page in an application.
App_Themes Contains a collection of files (.skin
and .css files, as well as image files
and generic resources) that define
the appearance of ASP.NET Web
pages and controls..
App_WebReference Contains reference contract files
s (.wsdl files), schemas (.xsd files),
and discovery document files
(.disco and .discomap files)
defining a Web reference for use in
an application.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1205
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Process Model with IIS
ASP.NET Process Model
• The IIS (INETINFO.EXE), runs as a System Process.
• ASP.NET applications are created by creating a new Virtual
Directory and specifying an Application Name.
• Standard IIS ISAPI filtering is used to route all ASP.NET requests to
the ISAPI filter ASPNET_ISAPI.DLL.
• ASPNET_ISAPI.DLL routes all requests to a single instance of the
worker process, ASPNET_WP.EXE, through a named pipe.
• ASP.NET applications run side-by-side in partitions within the
worker process known as “App Domains”.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1206
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Application Life cycle
Steps in Application Life Cycle
• User requests an application
resource from the Web server
• ASP.NET receives the first
request for the application.
• ASP.NET core objects are
created for each request.
• An HttpApplication object
is assigned to the request
• The request is processed
by the HttpApplication pipeline

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1207
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Application Life cycle
Application Life cycle
The following events are executed by the
HttpApplication class while the request is
processed.
• Validate the request, which
examines the information sent by
the browser and determines
whether it contains potentially
malicious markup
• Perform URL mapping, if any URLs
have been configured in the
UrlMappingsSection section of the
Web.config file.
• Based on the file name extension
of the requested resource ,select a
class that implements IHttpHandler
to process the request
• Call the ProcessRequest method of
the appropriate IHttpHandler class
for the request.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1208
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Application Life cycle
Global.asax
During the application life cycle, the application raises events.
• To handle application events or methods, create a file named
Global.asax in the root directory of the application.
• ASP.NET compiles it into a class derived from the HttpApplication
class, and then uses the derived class to represent the application.
 An instance of HttpApplication processes only one request at a
time.
 ASP.NET automatically binds application events to handlers in
the Global.asax file using the naming convention
Application_event, such as Application_BeginRequest.
 The Application_Start and Application_End methods are special
methods that do not represent HttpApplication events.
 ASP.NET calls them once for the lifetime of the application
domain, not for each HttpApplication instance.
 HttpApplication.InitCalled once for every instance of the
HttpApplication class after all modules have been created.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1209
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Page Life cycle

Page Development Parse Generate Code-


ASPX
Dynamic Compilation Engine
behind
class
file

Request
ASPX Instantiate Gen’d
File
ASPX Page
File Class
Request File

Response
Page
Response Class
Instantiate, process and render

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1210
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Compilation Life cycle

Item Description
App_GlobalResources The application's global
resources are compiled and a
resource assembly is built. Any
assemblies in the application's
Bin folder are linked to the
resource assembly.
App_WebResources Proxy types for Web services are
created and compiled. The
resulting Web references
assembly is linked to the
resource assembly if it exists
Profile properties If profile properties are defined
defined in the in the application's Web.config
Web.config file file, an assembly is generated
that contains a profile object.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1211
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Compilation Life cycle

Item Description
App_Code Source code files are built and
one or more assemblies are
created. All code assemblies and
the profile assembly are linked
to the resources and Web
references assemblies if any.
Global.asax The application object is
compiled and linked to all of the
previously generated
assemblies.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1212
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Compilation Life cycle
Item Description
App_LocalResources If the folder containing the
requested item contains an
App_LocalResources folder, the
contents of the local resources
folder are compiled and linked to
the global resources assembly.
Individual Web pages Compiled as needed and linked
(.aspx files), user to the local resources assembly
controls (.ascx files), and the top-level assemblies
HTTP handlers (.ashx
files), and HTTP
modules (.asmx files)
Themes, master Skin files for individual themes,
pages, other source master pages, and other source
files code files referenced by pages
are compiled when the
referencing page is compiled.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1213
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Page Directives
Directive Description
Assembly Links an assembly to the Page or user control
for which it is associated.
Control Page directive meant for use with user controls
(.ascx).
Impleme Implements a specified .NET Framework
nts interface.
Import Imports specified namespaces into the Page or
user control.
Master Enables you to specify master page–specific
attributes and values to use when the page
parses or compiles. This directive can be used
only with master pages (.master).
MasterTy Associates a class name to a Page in order to
pe get at strongly typed references or members
contained within the specified master page.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1214
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Page Directives

Directive Description
OutputCache Controls the output caching policies of a
Page or user control.

Page Enables you to specify page specific


attributes and values to use when the
page parses or compiles. This directive
can be used only with ASP.NET pages
(.aspx).
PreviousPage Enables an ASP.NET page to work with a
Type postback from another page in the
application.
Reference Links a Page or user control to the
current Page or user control.

Register Associates aliases with namespaces and


class names for notation in custom server
control syntax.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1215
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Objects
Types of ASP.NET Objects
• Request
• Response
• Server
• Application
• Session

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1216
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Request Object
Request Object Properties and Methods
• Application Path – Gets the path of the page.
• Path – Gets the Path and Name of the Page.
• PhysicalApplicationPath – Gets the full Path of the Page in physical form.
• Browser – Provides Access to the browser Object.
• Cookies – Provides access to the cookies collection.
• IsSecureConnection – Provides Info on the HTTP Connection.
• RequestType – Get or Post.
• QueryString-Gets Parameters Passed to the Page using Get.
• URL-Gets the Complete Address as submitted by the Browser.
• RawUrl-Gets the complete address Without Domain name and protocol.
• UserHostName-Gets the name of the Machine Requesting the page.
• UserHostAddress-Gets the IP Address of the machine requesting the page.
• UserLangage-Gets the language settings set by the browser.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1217
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Response Object
Response Object Properties and Methods
• Buffer-Default is True.
• ContentType-Specifies the MIME type.
• Cookies-Provides access to the cookies collection.
• Clear()-Buffer will be emptied and contents discarded.
• Flush()-All the HTML in the buffer is sent to the browser.
• End()-Ends page execution and sends HTML in the buffer to the
browser.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1218
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Server Object
Server Object Properties and Methods
• MachineName- Gets the Windows name of the machine that
ASP.NET is Running on.
• ScriptTimeOut- Gets /Sets the amount of time before an ASP.NET
page time out.
• HTMLEncode() – Takes a string and Encodes it to be displayed in
the browser.
• HTMLDecode()- Contrary to HTMLEncode().
• MapPath()- Takes a Virtual Path and Returns the Complete Physical
Path.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1219
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Application Object
Application Object Properties and Methods
Used to persist state at a Web Application level.
• Lock()- Used to lock all Application level variables.
• UnLock()- Used to unlock all Appliction level variables for
processing

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1220
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Session Object
Session Object Properties and Methods
Used to persist state at user level.
• Abandon()-Ends the current session.
• Clear()- Removes all information from the session.
• IsNewSession-Specifies if the current request amounts to a new
session.
• TimeOut-Period of Idle time in minutes before a session expires.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1221
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Master Pages

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Master Pages

Master
MasterPages
Pagesprovides
provideswith
withan
aneasy
easymethod
methodofofcreating
creatingaa
“Consistent
“Consistentlook
lookand
andfeel”
feel”
for
foraaWeb
Website.
site.

Site.master default.aspx http://.../default.aspx

Content-
Content
PlaceHolder

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1223
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Master Pages
Topics for Discussion:
• Need for Master Pages
• Building a Master Page
• Creating a content page
• Configuring master files
• Specifying Page titles
• Dynamically loading master pages
• Exposing properties and methods of a master page
• Nested Master Pages
• Container specific master pages
• Event Ordering b/w master and content pages

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1224
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Need for Master Pages

Header

Common
Page Items

Footer

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1225
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Need for Master Pages
Problems with Maintaining Consistent Page Layout
• Most sites follow a consistent layout
 Header, footer, navigation
 Site ‘structure’ is repeated on most pages
• Today lots of code and markup duplication
 Makes site updates very challenging to coordinate
Current Solutions Available
• User Controls
 Problem: Unbalanced html tags (example: tables)
 Problem: Lots of different controls on a page (adds more pieces
to puzzle)
• Tool-based solution
 Problems: Done at design-time, requires merging and modifying
every file
 Problems: Forces you to stick with a single tool

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1226
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Master Pages-The Solution
Master Pages Enable Flexible and Reusable UI layout

Master Pages Can Contain:


• Page markup
• Content (Header, Footer, HTML, ASP.NET controls)
• Replaceable regions for specialized content

Key Benefits:
• Consistent page layout
• Shared UI & code elements
• Can be defined both programmatically and declaratively

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1227
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Master Pages
Create a master page with .master extension

Define a master directive:


• <%@ master .. %>
Add content:
• Can contain any html or control page content
• Define replaceable place-holder regions:
 Use an <asp:contentplaceholder> control
 Add default content within it (optional)
• At runtime, the ASP.NET engine combines these elements into a
single page for the end user

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1228
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Master Pages

1 Opting for Code Behind Model


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1229
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Master Pages

1 Master Page File

2 Content Place Holders for Content Pages


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1230
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Master Pages

<%@ Master Language="C#" AutoEventWireup="true"


CodeFile="ShopMaster.master.cs" Inherits="ShopMaster" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>My Master Page</title>
</head>
<body>
<form id="form1" runat="server">
<table cellpadding="3" border="1">
<tr bgcolor="silver">
<td colspan="2">
<h1>My Shopping Home Page</h1>
</td></tr>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1231
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Master Pages

<tr><td>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1"
runat="server">
</asp:ContentPlaceHolder>
</td>
<td>
<asp:ContentPlaceHolder ID="ContentPlaceHolder2"
runat="server">
</asp:ContentPlaceHolder>
</td>
</tr>
<tr>
<td colspan="2">
Copyright 2007 - My Company
</td>
</tr>
</table>
</form></body></html>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1232
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Content Pages
Create an ASP.NET page (.aspx extension)

On the page directive:


• <%@ page masterpagefile= %> attribute to reference master
• Set the title attribute <%@ Page title=“Home Page” %>

Optionally add content to override the master:


• Only <asp:content> controls or server-side script allowed
• <asp:content> controls replace regions in the master:
 The contentplaceholderid identifies master’s region
 <asp:content> controls can contain any page content

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1233
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Content Pages

1 Opting for Code Behind Model


Selecting a particular Master page
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1234
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Content Pages

1 Selecting a particular Master page


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1235
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Content Pages

<%@ Page Language="C#" MasterPageFile="~/ShopMaster.master"


AutoEventWireup="true" CodeFile="MyFirContent.aspx.cs"
Inherits="MyFirContent" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"
Runat="Server">
<b>Enter your name:</b><br />
<asp:Textbox ID="TextBox1" runat="server" />
<br /> <br />
<asp:Button ID="Button1" runat="server" Text="Submit"
OnClick="Button1_Click" /><br />
<br />
<asp:Label ID="Label1" runat="server" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2"
Runat="Server">
<asp:Image ID="Image1" runat="server" ImageUrl="logo.png" Width=100
Height=100 />
</asp:Content>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1236
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Runtime Behavior of Master Pages
During Runtime, the ASP.NET engine combines both master and content pages into a single page
for the end user

my.master
MyShop.master default.aspx (content-page)
Default.aspx (content-page)

<%@ master %> <%@ page masterpagefile=“~/my.master” %>

Header Header
Navigation Navigation

<asp:contentplaceholder <asp:contentplaceholder
<asp:content
Id=“MainContent”> contentplaceholderid=“MainContent”>
Id=“MainContent”>
Here is my basic HereHere
is the
is the
content
content
default content thatthat
replaces
replaces
… …
</asp:contentplaceholder> </asp:contentplaceholder>
/asp:content>

Footer Footer
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1237
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Configuring Master Pages

Specifying
Specifyingthe
themaster
masterpage
pageininthe
theWeb.config
Web.configfile
file

<configuration>
<system.web>
<pages masterPageFile="~/MyShopMaster.master" />
</system.web>
</configuration>

Specifying
Specifyingthe
themaster
masterpage
pagefor
foraaspecific
specificfolder
folderininthe
theWeb.config
Web.configfile
file
<configuration>
<location path="AdministrationArea">
<system.web>
<pages masterPageFile="~/ShopAdmin.master" />
</system.web>
</location>
</configuration>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1238
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Working with Master Pages

Coding
Codingaacustom
custompage
pagetitle
titlefor
forthe
thecontent
contentpage-
page-MyFirContent.aspx.cs
MyFirContent.aspx.cs
protected void Page_LoadComplete(object sender, EventArgs e)
{ Master.Page.Title = "This page was generated on: " +
DateTime.Now.ToString();
}
Working
Workingwith
withControls
Controlsand
andProperties
Propertiesfrom
fromthetheMaster
MasterPage
Page
AAmaster
masterpage
pagethat
thatcreates
createsaaGUID
GUIDononthe
thefirst
firstrequest
request–MyShopMaster.aspx.cs
–MyShopMaster.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{ if (!Page.IsPostBack)
{ Label1.Text =
System.Guid.NewGuid().ToString(); } }
Getting
Gettingatatthe
theLabel’s
Label’sText
Textvalue
valueininthe
thecontent
contentpage-MyFirContent.aspx
page-MyFirContent.aspx
Your GUID number from the master page is:<br />
<asp:Label ID="Label1" runat="server" /></b><p>
protected void Page_LoadComplete(object sender, EventArgs e)
{ Label1.Text = (Master.FindControl("Label1") as Label).Text;
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1239
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Nesting Master Pages
Master-pages can be nested
• Enables a master to master relationship
Useful when a site enforces an overall layout and defines
sub-layouts within
• Content Pages can also be Master Pages.
• It is possible to derive a Master page from another Master
Page.
• Content Pages would then derive from the appropriate
section master for the section the Content Page belongs to.

ASPX
ASPX MASTER(ASPX
MASTER (ASPXContent-page)
Content-page)

MASTER(ASPX
MASTER (ASPXContent-page)
Content-page)

MASTER(MASTER)
MASTER (MASTER)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1240
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Event ordering
Event Ordering between Master and Content Pages
• Master page child controls initialization
• Content page child controls initialization
• Master page initialization
• Content page initialization
• Content page load
• Master page load
• Master page child controls load
• Content page child controls load

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1241
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Container Specific Master Pages
Container Specific Master Pages
• Web applications may be viewed in a variety of Containers
(Browsers). Depending upon the viewing container used by
the end user, the ASP.NET engine pulls the appropriate
master file.
• Build container specific master pages to provide end users
with the best possible viewing experience by taking
advantage of the features of specific containers

<%@
<%@ Page
Page Language="C#"
Language="C#"
MasterPageFile="~/MasterShop.master"
MasterPageFile="~/MasterShop.master"
Mozilla:MasterPageFile="~/MozillaShop.master"
Mozilla:MasterPageFile="~/MozillaShop.master"
Opera:MasterPageFile="~/OperaShop.master"
Opera:MasterPageFile="~/OperaShop.master" %>
%>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1242
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Themes and Skins

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Themes and Skins
“Themes define visual styles for web pages”
“Themes can be applied at the application, page or a server
control level”
Topics for discussion:
Creating a theme
• Creating Folder Structure
• Creating a skin
• Creating a CSS
• Creating images folder
Applying theme to
• A aspx page
• An entire application
Removing themes from
• Server Controls
• Web Pages
Themes and Master Pages
Assigning themes to pages dynamically

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1244
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Current Situation
Web developers want to:
• Customize the visual appearance of a web site or page
• Enforce a look-’n’-feel for the site

Some of today’s approaches and problems include:


• Inline styles
 Developer must touch every control
 More difficult to set styles on dynamic controls
• CSS style-sheet
 More difficult to set styles on dynamic controls
 Does not work on control properties, collection or templates

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1245
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Themes and Skins
Themes enable rich customization of UI
• Enables consistent look-’n’-feel for controls in an application
• Enables easy co-operation of developer + designer

Themes can contain:


• Skins: Properties to set on one or more server control types
• Styles: CSS stylesheet files
• Resources: Images

Themes can be set both declaratively and programmatically

Can be used both as a pre-step and post-step operation


• “Theme” attribute applies after control created (total control)
• “StyleSheetTheme” attribute applies before control (control override)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1246
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating folder structure
Creating the Proper Folder Structure
• Create a Theme folder by right-clicking on the project in Visual
Studio and selecting Add Folder@Theme.
• Within the App_Themes folder, Create an additional theme folder
for each and every theme to use in application
• Each theme folder must contain the elements of the theme, which
can include the following:
 A single skin file
 CSS files
 Images

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1247
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Skin
A skin is a definition of styles applied to the server controls
in a ASP.NET page.
• Skins can work in conjunction with CSS files or images.
• To create a theme to use in your ASP.NET applications, you use
just a single skin file in the theme folder.
• The skin file can have any name, but it must have a .skin file
extension
• The control definitions must contain the runat=”server” attribute.
• No ID attribute is specified in the skinned version of the control

<asp:Label
<asp:Labelrunat="server"
runat="server"ForeColor="#004000"
ForeColor="#004000"Font-Names="Verdana"
Font-Names="Verdana"
Font-Size="X-Small"
Font-Size="X-Small"/>/>
<asp:Textbox
<asp:Textboxrunat="server"
runat="server"ForeColor="#004000"
ForeColor="#004000"Font-Names="Verdana"
Font-Names="Verdana"
Font-Size="X-Small"
Font-Size="X-Small"BorderStyle="Solid"
BorderStyle="Solid"BorderWidth="1px"
BorderWidth="1px"
BorderColor="#004000"
BorderColor="#004000"Font-Bold="True"
Font-Bold="True"/>/>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1248
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Style
• ASP.NET pages are routinely made up of HTML server controls, raw
HTML, or even raw text
• For a theme that goes beyond the server controls, define the
theme style so that HTML server controls, HTML, and raw text are
all changed according to the theme.

• Achieve this with a CSS file within Themes folder.


 To create a comprehensive theme with this dialog, you define
each HTML element that might appear in the ASP.NET page.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1249
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Images
• A lot of controls use images to create a better visual appearance.
• The first step in incorporating images into server controls that
consistently use themes is to create an Images folder within the
Themes folder

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1250
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Applying and Removing Themes

Applying
ApplyingaaTheme
ThemetotoaaSingle
SingleASP.NET
ASP.NETPage
Page
<%@ Page Language=“C#" Theme=“Fall" %>

Applying
ApplyingaaTheme
Themetotoan
anEntire
EntireApplication
Application
<configuration>
<system.web>
<pages theme=“Fall” />
</system.web>
</configuration>

Removing
RemovingThemes
Themesfrom
fromServer
ServerControls
Controls
<asp:Textbox ID="TextBox1" runat="server"
BackColor="#000000" ForeColor="#ffffff" EnableTheming="false"/>

Removing
RemovingThemes
Themesfrom
fromWeb
WebPages
Pages
<%@ Page Language=“C#" EnableTheming="False" %>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1251
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Applying and Removing Themes

<%@
<%@ Master
Master Language=“C#"
Language=“C#" EnableTheming="false"
EnableTheming="false" %>
%>

• If the content page that is using this master page doesn’t make
any specification on theming (it does not use the EnableTheming
attribute)

• Even if the EnableTheming value is set in the content page, any


value that is specified in the master page takes precedence.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1252
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Assigning Themes dynamically

Assigning
Assigningthe
thePage’s
Page’sTheme
ThemeProgrammatically
Programmatically

protected void Page_PreInit(object sender, System.EventArgs e)


{
Page.Theme = Request.QueryString["ThemeChange"];
}

Assigning
AssigningaaControl’s
Control’sSkinID
SkinIDProgrammatically
Programmatically

protected void Page_PreInit(object sender, System.EventArgs e)


{
TextBox1.SkinID = "TextboxDashed";
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1253
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Controls

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Controls
Topics for discussion:
• HTML Controls
• Server Side Controls
• Login Controls
• Validation Controls
• Navigation

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1255
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Post Back Mechanism

Mapping a browser event to server event

IPostBackEventHandler

ASP.NET Server App


Button1 .RaisePostBackEvent()

Control
Click!
Click! calls OnClick()
Control

Control
invokes event handler
Button1_Click()
HTTP form post

Controls registered to receive


post-back event notification
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1256
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Controls Rendering

Page/Control Processing
First load

Each control instantiated, set to initial state, added to control


Init tree
User code runs, tests !IsPostBack condition to data bind 1st
Load
values
CreateChildControls() ensures controls are ready to render
PreRender
Controls save current state (if different than initial values)
SaveViewState
Each control renders itself to the Response
Render
Pages and all controls are disposed
Dispose

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1257
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Postback Rendering
Page/Control Processing
Post back
Init
Last state of the controls is restored from ViewState values
LoadViewState

Load
Posted data (in the HTTP form) is passed to its associated
Postback data
control are fired for controls in tree order, except the event
Events
Postback events that caused the post. It’s fired last.

PreRender

SaveViewState

Render

Dispose

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1258
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Postback and ViewState
Hello2.aspx.cs
If (!IsPostBack) …
First Request
Hello2.aspx

Response <asp:textbox
__VIEWSTATE = "dDwt…" id="TextBox1"
runat="server" />
<Input id="TextBox1">
Minder Chen

Post back
to the same page
__VIEWSTATE = "dDwt…"
Textbox1.Text = "Minder Chen"

Response
Default value
__VIEWSTATE = "dDwt…"
<Input id="TextBox1" value="Minder Chen" …>

States of a page is maintained via the


ViewState between the Postback

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1259
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET HTML Controls

HTML Controls

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1260
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Features of HTML Controls
“HTML server controls are HTML elements containing
attributes that make them programmable in server code”
HTML server controls offer the following features:
• An object model that you can program against on the server using
familiar object-oriented techniques.
• A set of events for which you can write event handlers and the
event is handled in server c
• The ability to handle events in client script.
• Automatic maintenance of the control's state.
• Interaction with ASP.NET validation controls
• Data binding to one or more properties of the control.
• Support for styles.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1261
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
HTML Controls

HTML Controls
Connection
Input Control
Text Area Button
Reset
Table
SelectCommand
Submit
Image Text
File
Select
InsertCommand
Password
HorizontalRule,Div
DeleteCommand CheckBox
Radio

Input Hidden

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1262
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Server Side Controls

Server Side Controls

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1263
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Features of Server Side Controls
“Web server controls do not necessarily map one-to-one to
HTML server controls”
Server controls offer the following features:
• A rich object model that provides type-safe programming
capabilities.
• Automatic browser detection.
• Ability to define your own layout for the control using Templates.
• The ability to specify whether a control's event causes immediate
posting to
• the server or is instead cached and raised when the page is
submitted.
• Support for themes.
• Ability to pass events from a nested control to the container
control.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1264
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Label Control
Label

The Label control displays text in a set location on the page.

<asp:Label
<asp:Label ID="Label1"
ID="Label1" runat="server"
runat="server" AccessKey="N"
AccessKey="N"
AssociatedControlID="Textbox1">User<u>n</u>ame</asp:Label>
AssociatedControlID="Textbox1">User<u>n</u>ame</asp:Label>

<asp:Textbox ID="TextBox1"
runat="server"></asp:Textbox></p>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1265
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET TextBox Control
TextBox

The TextBox control enables the user to enter text . The display width of TextBox is determined by its Columns property. If TextMode is MutliLine, the display height of TextBox is determined by
the Rows property.

<asp:TextBox
<asp:TextBox id="Text1"
id="Text1" Text="Copy
Text="Copy this
this text
text to
to the
the label"
label"
Width="200px" runat="server"/>
Width="200px" runat="server"/>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1266
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Button Control
Button

The Button control provides a command button-style control that is used to


post a Web Forms page back to the server

<asp:Button
<asp:Button id=Button1
id=Button1 Text="Click
Text="Click Me"
Me"
onclick="Button1_Click"
onclick="Button1_Click" runat="server"
runat="server" />
/> <asp:Label
<asp:Label
id=Label1 runat=server />
id=Label1 runat=server />

void Button1_Click(object Source, EventArgs e)


{
Label1.Text="You clicked the button";
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1267
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET LinkButton Control
LinkButton

LinkButton is used to post a Web Forms page back to the server

<asp:LinkButton
<asp:LinkButton Text="Click
Text="Click Me!"
Me!" Font-Names="Verdana"
Font-Names="Verdana"
Font-Size="14pt"
Font-Size="14pt" onclick="LinkButton1_Click"
onclick="LinkButton1_Click"
runat="server"/>
runat="server"/>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1268
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Image Button Control
ImageButton

ImageButton is used to post back to the server

Image Button as a Image Map

Size:100pixels
Size:100pixels

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1269
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Image Button Control

<table width="100%" border="0">


<tr>
<td width="25%">
<asp:ImageButton id="Button1" ImageUrl="ip.jpg"
BorderWidth="2px" onclick="ImageButton1_OnClick" runat="server"
Width="100" Height="100"/>
</td>
<td>
<asp:Label id="Label1" Text="X:" runat="SERVER"/>
<br/>
<asp:Label id="Label2" Text="Y:" runat="SERVER"/>
</td>
</tr>
</table>
<asp:Label id="Label3" font-bold="true" Text=""
runat="SERVER"/>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1270
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Image Button Control

public void ImageButton1_OnClick(object Source, ImageClickEventArgs e)


{
int x = e.X;
int y = e.Y;
Label1.Text = "X: " + x.ToString();
Label2.Text = "Y: " + y.ToString();
if (x >= 60)
{
Label3.Text = "You clicked on the Right side!";
}
else
{
Label3.Text = "You clicked on Left side!";
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1271
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET HyperLink Control
HyperLink

The HyperLink control is used to navigate from the client to another page

<asp:hyperlink
<asp:hyperlink id=HyperLink1
id=HyperLink1 runat="server">
runat="server">
Go
Go To
To Shopping
Shopping Homepage
Homepage
</asp:hyperlink>
</asp:hyperlink>

protected void Page_Load(object sender, EventArgs e)


{
// Set hyperlink to "~", which indicates
application root.
HyperLink1.NavigateUrl = "~";
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1272
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET DropDownList Control
DropDownList

The DropDownList control provides a single-select drop-down list.

Data binding to a static ArrayList with a DropDownList control.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1273
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET DropDownList Control

protected void Page_Load(object sender, EventArgs e)


{ if (!IsPostBack)
{ ArrayList values = new ArrayList();
values.Add("IN");
values.Add("KS");
values.Add("MD");
DropDown1.DataSource = values;
DropDown1.DataBind();
}
}
public void SubmitBtn_Click(Object sender, EventArgs e)
{ Label1.Text = "You chose: " + DropDown1.SelectedItem.Text;
}

<asp:DropDownList
<asp:DropDownList id="DropDown1"
id="DropDown1" runat="server"
runat="server" />
/>
<asp:button
<asp:button ID="Button1"
ID="Button1" Text="Submit"
Text="Submit" OnClick="SubmitBtn_Click"
OnClick="SubmitBtn_Click"
runat="server"/>
runat="server"/>
<asp:Label
<asp:Label id="Label1"
id="Label1" Font-Names="Verdana"
Font-Names="Verdana" font-size="10pt"
font-size="10pt"
runat="server" />
runat="server" />

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1274
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET ListBox Control
ListBox

The ListBox control provides a single-selection or multiple-selection list. To enable


multiple selection, set the SelectionMode property to Multiple

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1275
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET ListBox Control

public void SubmitBtn_Click(Object Sender, EventArgs e)


{
if (ListBox1.SelectedIndex > -1)
{ Label1.Text = "You chose: " + ListBox1.SelectedItem.Text;

}
}

<asp:ListBox ID="ListBox1" Width="100px" runat="server">


<asp:ListItem>Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem>Item 4</asp:ListItem>
</asp:ListBox>
<asp:Button Text="Submit" ID=submit1 OnClick="SubmitBtn_Click"
runat="server" />
<asp:Label ID="Label1" Font-Names="Verdana" Font-Size="10pt"
runat="server" />

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1276
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET CheckBox Control
CheckBox

The CheckBox server control accepts Boolean (true or false) input.


When selected, its Checked property is true

<asp:CheckBox
<asp:CheckBox id=Check1
id=Check1 Text="CheckBox1"
Text="CheckBox1" runat="server"
runat="server" />
/>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1277
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET CheckBoxList Control
CheckBoxList

The CheckBoxList control provides a multiple-selection checked list

Properties:
RepeatLayout
Table- the list is rendered within a table
Flow- the list is rendered without any table structure
RepeatDirection
Vertical- the list is rendered vertically
Horizontal- the list is rendered horizontally
. <asp:CheckBoxList
<asp:CheckBoxList ID="Check1"
ID="Check1" runat="server">
runat="server"> <asp:ListItem>Item
<asp:ListItem>Item
1</asp:ListItem>
1</asp:ListItem>
<asp:ListItem>Item
<asp:ListItem>Item 2</asp:ListItem>
2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem>Item
<asp:ListItem>Item 4</asp:ListItem>
4</asp:ListItem>
<asp:ListItem>Item 5</asp:ListItem>
<asp:ListItem>Item 5</asp:ListItem>
<asp:ListItem>Item
<asp:ListItem>Item 6</asp:ListItem>
6</asp:ListItem>
</asp:CheckBoxList>
</asp:CheckBoxList>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1278
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET RadioButton Control
RadioButton

The RadioButton control permits to intersperse the radio buttons in a group with other
content in the page.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1279
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Radio Button Control

public void SubmitBtn_Click(Object Sender, EventArgs e)


{
if (Radio1.Checked)
{
Label1.Text = "<b>You selected:</b> " + Radio1.Text;
}
else if (Radio2.Checked)
{
Label1.Text = "<b>You selected:</b> " + Radio2.Text;
}
else if (Radio3.Checked)
{
Label1.Text = "<b>You selected:</b> " + Radio3.Text;
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1280
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Radio Button Control

<h4>Select the type of installation you wish to perform:</h4>


<asp:RadioButton ID="Radio1" Text="Typical" Checked="True"
GroupName="RadioGroup1“
runat="server" />
This option installs the features most typically used. <i>Requires 1.2 MB
disk space.</i><br />
<asp:RadioButton ID="Radio2" Text="Compact" GroupName="RadioGroup1"
runat="server" />
This option installs the minimum files required to run the product.
<i>Requires 350
KB disk space.</i><br />
<asp:RadioButton ID="Radio3" runat="server" Text="Full"
GroupName="RadioGroup1" />
This option installs all features for the product. <i>Requires 4.3 MB
disk space.</i><br />
<asp:Button ID="Button1" Text="Submit" OnClick="SubmitBtn_Click"
runat="server" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1281
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET RadioButtonList Control
RadioButtonList

The RadioButtonList control provides a single-selection checked list

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1282
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET RadioButtonList Control

<asp:RadioButtonList ID="RadioButtonList1" runat="server">


<asp:ListItem>Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem>Item 4</asp:ListItem>
<asp:ListItem>Item 5</asp:ListItem>
<asp:ListItem>Item 6</asp:ListItem>
</asp:RadioButtonList>

<asp:CheckBox ID="chkLayout"
OnCheckedChanged="chkLayout_CheckedChanged"
Text="Display Table Layout"
Checked="true"
utoPostBack="true" runat="server" />
<asp:CheckBox id=chkDirection
OnCheckedChanged="chkDirection_CheckedChanged"
Text="Display Horizontally"
AutoPostBack="true" runat="server" />

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1283
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET RadioButtonList Control

public void chkLayout_CheckedChanged(Object sender, EventArgs e)


{
if (chkLayout.Checked == true)
{ RadioButtonList1.RepeatLayout =
RepeatLayout.Table;
}
else
{ RadioButtonList1.RepeatLayout =
RepeatLayout.Flow;
}
}
public void chkDirection_CheckedChanged(Object sender, EventArgs e)
{
if (chkDirection.Checked == true)
{ RadioButtonList1.RepeatDirection =
RepeatDirection.Horizontal;
}
else
{ RadioButtonList1.RepeatDirection = R
epeatDirection.Vertical;
} }
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1284
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Image Control
Image

The Image control displays the image defined by its ImageUrl property

<asp:Image
<asp:Image ID="Image1"
ID="Image1" ImageUrl="images/cereal1.gif"
ImageUrl="images/cereal1.gif"
AlternateText="Healthy
AlternateText="Healthy Grains" runat="server"
Grains" runat="server" />
/>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1285
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET ImageMap Control
ImageMap

ImageMap control is used to create an image that contains defined hotspot


regions.The control can either generate a post back to the server or navigate to a
specified<asp:imagemap
URL id="Buttons" imageurl="hotspot.jpg"
<asp:imagemap id="Buttons" imageurl="hotspot.jpg"
alternatetext="Navigate
alternatetext="Navigate buttons"
buttons" runat="Server">
runat="Server">
<asp:RectangleHotSpot
<asp:RectangleHotSpot
hotspotmode="Navigate"
hotspotmode="Navigate"
NavigateUrl="navigate1.htm"
NavigateUrl="navigate1.htm"
alternatetext="Button
alternatetext="Button 1"
1"
top="30"
top="30" left="175"
left="175" bottom="110"
bottom="110"
right="355">
right="355">
</asp:RectangleHotSpot>
</asp:RectangleHotSpot>
<asp:RectangleHotSpot
<asp:RectangleHotSpot
hotspotmode="Navigate"
hotspotmode="Navigate"
NavigateUrl="navigate2.htm"
NavigateUrl="navigate2.htm"
alternatetext="Button
alternatetext="Button 2"
2"
top="155"
top="155" left="175"
left="175" bottom="240“
bottom="240“
right="355“
right="355“
</asp:RectangleHotSpot>
</asp:RectangleHotSpot>
</asp:imagemap>
</asp:imagemap>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1286
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET ImageMap Control

Running different server code based on the region of the image that is clicked

void Buttons_Clicked(object sender, ImageMapEventArgs e)


{
label1.Text = e.PostBackValue + " clicked!";
}

<asp:imagemap
<asp:imagemap id="Buttons"
id="Buttons" imageurl="hotspot.jpg"
imageurl="hotspot.jpg"
alternatetext="Navigate
alternatetext="Navigate buttons"
buttons" hotspotmode="Postback"
hotspotmode="Postback"
onclick="Buttons_Clicked" runat="Server">
onclick="Buttons_Clicked" runat="Server">
<asp:RectangleHotSpot
<asp:RectangleHotSpot hotspotmode="Postback"
hotspotmode="Postback" postbackvalue="Button1"
postbackvalue="Button1"
alternatetext="Button
alternatetext="Button 1" top="30" left="175" bottom="110" right="355">
1" top="30" left="175" bottom="110" right="355">
</asp:RectangleHotSpot>
</asp:RectangleHotSpot>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1287
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Table Control
Table
The Table control builds up a table programmatically by adding TableRows to the Rows
collection of the table, and TableCells to the Cells collection of the row.

Creating rows and columns for a table dynamically

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1288
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Table Control

protected void Button1_Click(object sender, EventArgs e)


{ for (int j = 0; j < 3; j++)
{ TableRow r = new TableRow();
for (int i = 0; i < 4; i++)
{ TableCell c = new TableCell();
c.Controls.Add(new LiteralControl("row " +
j.ToString() + ", cell " + i.ToString()));
r.Cells.Add(c);
}
Table1.Rows.Add(r);
} }

<asp:Table
<asp:Table id="Table1"
id="Table1" Font-Names="Verdana"
Font-Names="Verdana" Font-Size="8pt"
Font-Size="8pt"
CellPadding=5
CellPadding=5 CellSpacing=0 BorderColor="black" BorderWidth="1"
CellSpacing=0 BorderColor="black" BorderWidth="1"
Gridlines="Both" runat="server"/>
Gridlines="Both" runat="server"/>
<asp:Button
<asp:Button ID="Button1"
ID="Button1" runat="server"
runat="server" OnClick="Button1_Click"
OnClick="Button1_Click"
Text="Create
Text="Create Table"
Table" />
/>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1289
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET BulletedList Control
BulletedList

The BulletedList control is used to create a list of items formatted with bullets

<asp:BulletedList ID=BulletedList1 BulletStyle="Circle"


runat=server> <asp:ListItem>Item #1</asp:ListItem>
<asp:ListItem>Item #2</asp:ListItem>
<asp:ListItem>Item #3</asp:ListItem>
<asp:ListItem>Item #4</asp:ListItem>
</asp:BulletedList>

The BulletedList control can also render a list of hyperlinks


<asp:BulletedList DisplayMode = HyperLink runat=server>
<asp:ListItem
Value="http://support.Microsoft.com">Support</asp:ListIte
m>
<asp:ListItem
Value="http://www.asp.net">ASP.NET</asp:ListItem>
</asp:BulletedList>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1290
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET HiddenField Control
HiddenField

This control enables a developer to store a non-displayed value

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1291
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET HiddenField Control

public void Button1_Click(object sender, EventArgs e)


{
if (HiddenField1.Value == String.Empty)
HiddenField1.Value = "0";
//Increment the hidden field value by 1
HiddenField1.Value = (Convert.ToInt32(HiddenField1.Value) +
1).ToString();
Label1.Text = HiddenField1.Value;
}

<asp:HiddenField id="HiddenField1" runat="Server" />


<asp:Button id="Button1" Text="Click Me" onclick="Button1_Click"
runat="server" />
Clicked <asp:Label id="Label1" Text="0" runat="server" /> times

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1292
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Literal Control
Literal
A Literal control is used to display text.
Styles can be applied to a literal control This control will pass the content directly to the client browser, unless the Mode property to encode the content is
used.

<asp:Literal
<asp:Literal ID=Literal1
ID=Literal1 Text="I
Text="I am
am aa literal
literal control"
control"
runat=server />
runat=server />

<asp:Literal
<asp:Literal ID=Literal2
ID=Literal2 Mode=Encode
Mode=Encode Text="<Some
Text="<Some encoded
encoded
text>" runat=server />
text>" runat=server />

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1293
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Calendar Control
Calendar
The Calendar control displays a month calendar from which users can select dates

<asp:Calendar id=Calendar1
onselectionchanged="Calendar1_SelectionChanged"
runat="server" />

protected void Calendar1_SelectionChanged(object sender,


EventArgs e)
{
CalLabel.Text = "Selected date is: " +
Calendar1.SelectedDate.ToShortDateString();

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1294
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Calendar Control
Calendar

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1295
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Calendar Control

Choose a Selection Mode:


<asp:DropDownList id="lstSelMode" runat="server"
AutoPostBack="true">
<asp:ListItem Value="None" >None</asp:ListItem>
<asp:ListItem Value="Day" Selected="True">
Day</asp:ListItem>
<asp:ListItem Value="DayWeek" >DayWeek</asp:ListItem>
<asp:ListItem Value="DayWeekMonth" >
DayWeekMonth</asp:ListItem>
</asp:DropDownList>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1296
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Calendar Control

<asp:Calendar id="Calendar1" runat="server"


onselectionchanged="Date_Selected"
Font-Names="Arial" Font-Size="12px"
Height="180px" Width="200px"
SelectorStyle-BackColor="gainsboro“
TodayDayStyle-BackColor="gainsboro"
DayHeaderStyle-BackColor="gainsboro"
OtherMonthDayStyle-ForeColor="gray“
TitleStyle-BackColor="gray“ TitleStyle-Font-Bold="True"

TitleStyle-Font-Size="12px“ SelectedDayStyle-BackColor="Navy“

SelectedDayStyle-Font-Bold="True“ NextPrevFormat="ShortMonth"

NextPrevStyle-ForeColor="white“ NextPrevStyle-Font-Size="10px"

SelectorStyle-ForeColor="navy“
SelectorStyle-Font-Size="9px"
SelectWeekText = "week"
SelectMonthText = "month"
/>
<asp:Label id="Label1" runat="server" />
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1297
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Calendar Control

protected void Page_Load(object sender, EventArgs e)


{
Calendar1.SelectionMode =
(CalendarSelectionMode)lstSelMode.SelectedIndex;
if (Calendar1.SelectionMode == CalendarSelectionMode.None)
Calendar1.SelectedDates.Clear();
}
public void Date_Selected(object s, EventArgs e)
{ switch (Calendar1.SelectedDates.Count)
{ case (0): //None
Label1.Text = "No dates are currently selected";
break;
case (1): //Day
Label1.Text = "The selected date is " +
Calendar1.SelectedDate.ToShortDateString();break;
case (7): //Week
Label1.Text = "The selection is a week beginning " +
Calendar1.SelectedDate.ToShortDateString();break;
default: //Month
Label1.Text = "The selection is a month beginning " +
Calendar1.SelectedDate.ToShortDateString();break;
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1298
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET AdRotator Control
AdRotator

The AdRotator control presents ad images that, when clicked, navigate to a new Web
location.

The rotation schedule for ads is defined in an XML file

<asp:AdRotator
<asp:AdRotator id="ar1"
id="ar1" AdvertisementFile="Ads.xml"
AdvertisementFile="Ads.xml"
BorderWidth="1"
BorderWidth="1" runat=server
runat=server />
/>

<Advertisements>
<Ad> <ImageUrl>images/banner1.gif</ImageUrl>
<NavigateUrl>http://www.microsoft.com</NavigateUrl>
<AlternateText>Microsoft.com</AlternateText>
<Keyword>Computers</Keyword>
<Impressions>80</Impressions>
</Ad>
</Advertisements>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1299
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET AdRotator Control

Attribute Description

ImageUrl An absolute or relative URL to the ad image file.


NavigateUrl The Web location to navigate to when the image
is clicked. If NavigateUrl is not set, the image
is not clickable.
AlternateText The text to render as the ALT attribute of the
image. When the page is viewed with Microsoft
Internet Explorer, this acts as a ToolTip for the
ad.
Keyword Specifies a category for the ad that the page can
filter on.
Impressions A number that indicates the "weight" of the ad
in the schedule of rotation relative to the other
ads in the file. The larger the number, the more
often the ad will be displayed.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1300
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET FileUpload Control
FileUpload

The FileUpLoad control enables to upload file to the server. It displays a text
box control and a browse button to select a file to upload to the server.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1301
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET FileUpload Control

public void Button1_Click(object sender, EventArgs e)


{
if (FileUpLoad1.HasFile)
{
Label1.Text = "Received :" + FileUpLoad1.FileName + "
Content Type :" + FileUpLoad1.PostedFile.ContentType
+ " Length: " + FileUpLoad1.PostedFile.ContentLength;
}
else
{ Label1.Text = "No uploaded file";
}
}

<asp:FileUpLoad id="FileUpLoad1" AlternateText="You cannot upload


files" runat="server" />
<asp:Button id="Button1" Text="Upload" OnClick="Button1_Click"
runat="server" />
<asp:Label id="Label1" runat="server" />

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1302
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Wizard Control
Wizard

The Wizard control provides navigation through a series of steps that collect
information incrementally from a user

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1303
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Wizard Control
The Wizard consists of:
Collection of WizardSteps:
• Each WizardStep contains a discrete piece of content to be displayed
to the user. Only one WizardStep will be displayed at a time.
Navigation Area:
• The navigation area below each WizardStep that contains the
navigation buttons to go the next and pervious steps in the wizard.
SideBar:
• An optional element that contains a list of all WizardSteps and
provides a means to skip around the WizardSteps in a random order.
Header:
• An optional element to provide consistent information at the top of
the WizardStep.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1304
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Wizard Control
The StepType associated with each WizardStep determines
the type of navigation buttons that will be displayed for
that step.
The StepTypes are:
• Start: Displays a Next button.
• Step: Displays Next and Previous buttons.
• Finish: Displays a Finish button.
• Complete: Displays no navigation buttons and hides the SideBar if
it is displayed.
• Auto:One of the step types listed above is selected based on the
order of the step in the collection

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1305
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Wizard Control

<asp:Wizard ID="Wizard1" runat="server"


ActiveStepIndex="0"
OnActiveStepChanged="GetFavoriteNumberOnActiveStepIndex"
BackColor="#FFFBD6"
BorderColor="#FFDFAD"
BorderWidth="1px"
CellPadding="5"
Font-Names="Verdana“
Font-Size="0.8em" Width="322px">
<WizardSteps>
<asp:WizardStep ID="WizardStep1" runat="server" Title="Step 1">
<strong>Wizard Step 1</strong> <br /><br />
Favorite Number:
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
</asp:DropDownList> <br />
</asp:WizardStep>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1306
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Wizard Control

<asp:WizardStep ID="WizardStep2" runat="server" Title="Step 2"


StepType="Complete">
<strong>Wizard Step 2</strong><br /> <br />
<asp:Label ID="Label1" runat="server"/>
</asp:WizardStep>
</WizardSteps>
<SideBarStyle Width="75px" VerticalAlign="Top"/>
</asp:Wizard>

public void GetFavoriteNumberOnActiveStepIndex(Object Sender,


EventArgs e)
{
Label1.Text = "Thank you for telling that your favorite number
is:" + DropDownList1.SelectedItem.Text;
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1307
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET XML Control
XML

The Xml control can be used to write out an XML document or the results of
• Transform
an XSL The DocumentSource specifies the XML document to use.
• This document will be written directly to the output stream unless
TransformSource is also specified.
• TransformSource must be a valid XSL Transform document and will
be used to transform the XML document before its contents are
written to the output stream.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1308
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET MultiView Control
Multiview/View

The MultiView control represents a control that acts as a container for groups
of View controls. It allows you to define a group of View controls, where each
View control contains child controls

Selecting multiple views

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1309
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET MultiView Control

<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">


<asp:View ID="View1" runat="server">
Now showing View #1<br />
<asp:TextBox ID="TextBox1“
runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server“
Text="Button" />
</asp:View>
<asp:View ID="View2" runat="server">
Now showing View #2<br />
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl="http://www.asp.net">
HyperLink</asp:HyperLink>
<asp:HyperLink ID="HyperLink2" runat="server"
NavigateUrl="http://www.asp.net">
HyperLink</asp:HyperLink>
</asp:View>
</asp:MultiView>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1310
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET MultiView Control

<asp:DropDownList ID="DropDownList1" runat="server"


AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Value="0">View 1</asp:ListItem>
<asp:ListItem Value="1">View 2</asp:ListItem>
<asp:ListItem Value="2">View 3</asp:ListItem>
</asp:DropDownList><br />
<hr />

protected void DropDownList1_SelectedIndexChanged(object sender,


EventArgs e)
{
MultiView1.ActiveViewIndex =
Convert.ToInt32(DropDownList1.SelectedValue);
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1311
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Panel Control
Panel

The Panel control is a container for other controls . It is especially useful when you want to
generate controls programmatically or hide or show a group of controls

Adding Controls to panel dynamically

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1312
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Panel Control

protected void Button1_Click(object sender, EventArgs e)


{ if (Check1.Checked)
{ Panel1.Visible = false; }
else
{ Panel1.Visible = true; }
for (int i = 1; i <= 3; i++)
{ System.Web.UI.WebControls.Label l = new
System.Web.UI.WebControls.Label();
l.Text = "Label" + i.ToString();
l.ID = "Label" + i.ToString();
Panel1.Controls.Add(l);
Panel1.Controls.Add(new LiteralControl("<br>"));
} }
<asp:Panel
<asp:Panel id="Panel1"
id="Panel1" runat="server“
runat="server“ BackColor="gainsboro“
BackColor="gainsboro“
Height="200px“
Height="200px“ Width="300px"> Panel1: Here is
Width="300px"> Panel1: Here is some
some static
static content...
content...
<br />
<br />
</asp:Panel>
</asp:Panel>
<asp:CheckBox
<asp:CheckBox id="Check1"
id="Check1" Text="Hide
Text="Hide Panel"
Panel" runat="server"/>
runat="server"/>
<asp:Button ID="Button1"
<asp:Button ID="Button1"
runat="server"
runat="server" OnClick="Button1_Click"
OnClick="Button1_Click" Text="Button"
Text="Button" />
/>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1313
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET PlaceHolder Control
PlaceHolder

The PlaceHolder control can be used as a container control within a


document to dynamically load other controls

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1314
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET PlaceHolder Control

protected void Button1_Click1(object sender, EventArgs e)


{
HtmlButton clicker = new HtmlButton();
clicker.InnerText = "Button 1";
Bullseye.Controls.Add(clicker);
clicker = new HtmlButton();
clicker.InnerText = "Button 2";
Bullseye.Controls.Add(clicker);
clicker = new HtmlButton();
clicker.InnerText = "Button 3";
Bullseye.Controls.Add(clicker);
}

<asp:PlaceHolder
<asp:PlaceHolder id="Bullseye"
id="Bullseye" runat="server"
runat="server" />
/>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click1"
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click1"
Text="Button"
Text="Button" />
/>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1315
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Login Controls

Login Controls

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1316
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Login Controls

LoginStatus
LoginStatus

Login CreateUser-
Login CreateUser-
Wizard
Wizard
Login
Controls
LoginName
LoginName
Password-
Password-
Recovery
Recovery

Change-
Change-
LoginView Password
LoginView Password

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1317
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Types of Login Controls

Name Description
ChangePasswor
UI for changing passwords
d
CreateUserWiza
UI for creating new user accounts
rd
UI for entering and validating user
Login
names and passwords
LoginName Displays authenticated user names
LoginStatus UI for logging in and logging out
Displays different views based on login
LoginView
status and roles
PasswordRecov
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1318
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Login Control

Login

Features of Login Control


• Standard UI for logging in users
• Integrates with Membership service
 Calls ValidateUser automatically
 No-code validation and logins
• Also works without Membership service
• Incorporates RequiredFieldValidators
• Highly customizable UI and behavior

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1319
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Login Control-Customization

Customizing the Login Control

<asp:Login
<asp:Login ID="LoginControl"
ID="LoginControl" RunAt="server"
RunAt="server"
CreateUserText="Create new account"
CreateUserText="Create new account"
CreateUserUrl="CreateUser.aspx"
CreateUserUrl="CreateUser.aspx"
DisplayRememberMe="false"
DisplayRememberMe="false"
PasswordRecoveryText="Forgotten
PasswordRecoveryText="Forgotten your
your password?"
password?"
PasswordRecoveryUrl="RecoverPassword.aspx"
PasswordRecoveryUrl="RecoverPassword.aspx"
LoginButtonText="Do
LoginButtonText="Do It!"
It!"
TitleText="Please
TitleText="Please Log In"
Log In"
/>
/>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1320
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Login Control Events

Name Description

Fired when the user clicks the Log In


button. Purpose: to
LoggingIn Prevalidate login credentials (e.g., make
sure e-mail
address is well-formed)
Fired when the user clicks the Log In
button. Purpose: to authenticate the
Authenticate user by validating his or her
login credentials
LoggedIn Fired following a successful login
LoginError Fired when an attempted login fails

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1321
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET LoginView Control

LoginView

Features of LoginView Control


• Displays content differently to different users depending on:
 Whether user is authenticated
 If user is authenticated, the role memberships he or she is
assigned
• Template-driven
 <AnonymousTemplate>
 <LoggedInTemplate>
 <RoleGroups> and <ContentTemplate>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1322
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET LoginView Control

<asp:LoginView ID="LoginView1" Runat="server">


<AnonymousTemplate>
<!-- Content seen by unauthenticated users -->
</AnonymousTemplate>
<LoggedInTemplate>
<!-- Content seen by authenticated users -->
</LoggedInTemplate>
<RoleGroups>
<asp:RoleGroup Roles="Administrators">
<ContentTemplate>
<!-- Content seen by authenticated users who are
administrators -->
</ContentTemplate>
</asp:RoleGroup>
...
</RoleGroups>
</asp:LoginView>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1323
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Password Recovery Control

PasswordRecovery

Features of Password Recovery Control


• Password recovery usually means sending the end user’s password to
him in an e-mail.
• Set up an SMTP server

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1324
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Password Recovery Control

Configuring
Configuringpasswords
passwordstotobe
besent
sentvia
viaemail
emailininthe
theweb.config
web.configfile
file
<configuration>
<system.web>
<!-- Removed for clarity -->
</system.web>
<system.net>
<mailSettings>
<smtp from="evjen@yahoo.com">
<network host="localhost" port="25"
defaultCredentials="true" />
</smtp>
</mailSettings>
</system.net>
</configuration>

Using
Usingthe
thePasswordRecovery
PasswordRecoverycontrol
control
<asp:PasswordRecovery ID="PasswordRecovery1" Runat="server">
<MailDefinition From="evjen@yahoo.com"> </MailDefinition>
</asp:PasswordRecovery>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1325
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET LoginStatus Control

LoginStatus

Features of LoginStatus Control


• Displays links for logging in and out
 "Login" to unauthenticated users
 "Logout" to authenticated users
• UI and logout behavior are customizable

<asp:LoginStatus
<asp:LoginStatusID="LoginStatus1"
ID="LoginStatus1"Runat="server"
Runat="server"
LogoutAction="Redirect"
LogoutAction="Redirect"LogoutPageUrl="~/Default.aspx"
LogoutPageUrl="~/Default.aspx"/>/>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1326
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
LoginStatus Control

Name Description

Text displayed for login link


LognText
(default="Login")
Text displayed for logout link
LogoutText
(default="Logout")
LoginImageUrl URL of image used for login link
Action to take following logout: Redirect,
LogoutAction RedirectToLoginPage, or Refresh
(default)
URL of page to go to following logout if
LogOutPageUrl
LogoutAction="Redirect"

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1327
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET LoginName Control

LoginName

Features of LoginName Control


• Displays authenticated user names
• Use optional FormatString property to control format of output

<asp:LoginView
<asp:LoginView ID="LoginView1"
ID="LoginView1" Runat="server">
Runat="server">
<AnonymousTemplate>
<AnonymousTemplate>
You
You are
are not
not logged
logged in
in
</AnonymousTemplate>
</AnonymousTemplate>
<LoggedInTemplate>
<LoggedInTemplate>
<asp:LoginName
<asp:LoginName ID="LoginName1"
ID="LoginName1" Runat="server"
Runat="server"
FormatString="You
FormatString="You are logged in as
are logged in as {0}"
{0}" />
/>
</LoggedInTemplate>
</LoggedInTemplate>
</asp:LoginView>
</asp:LoginView>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1328
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET CreateUserWizard Control

CreateUserWizard

Features of CreateUserWizard Control


• The CreateUserWizard server control is one that can be used in
conjunction with the membership service.
• The CreateUserWizard control enables to plug registered users into the
data store for later retrieval.

<asp:CreateUserWizard
<asp:CreateUserWizard ID="CreateUserWizard1"
ID="CreateUserWizard1"
Runat="server"
Runat="server" BorderWidth="1px"
BorderWidth="1px" BorderColor="#FFDFAD"
BorderColor="#FFDFAD"
BorderStyle="Solid"
BorderStyle="Solid" BackColor="#FFFBD6" Font-
BackColor="#FFFBD6" Font-
Names="Verdana">
Names="Verdana">
<TitleTextStyle
<TitleTextStyle Font-Bold="True"
Font-Bold="True" BackColor="#990000"
BackColor="#990000"
ForeColor="White"></TitleTextStyle>
ForeColor="White"></TitleTextStyle>
</asp:CreateUserWizard>
</asp:CreateUserWizard>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1329
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET ChangePassword Control

ChangePassword

The ChangePassword server control enables end users to change their passwords directly in
the browser

<asp:ChangePassword
<asp:ChangePassword ID="ChangePassword1"
ID="ChangePassword1" Runat="server">
Runat="server">
</asp:ChangePassword>
</asp:ChangePassword>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1330
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET ChangePassword Control

ChangePassword

Features of ChangePassword Control


• The ChangePassword control produces a form that asks for the
previous password.
• It also requires the end user to type the new password twice.
• Clicking the Change Password button launches an attempt to change
the password if the user is logged in.
• If the end user isn’t logged into the application yet, he or she is
redirected to the login page.
• Only a logged-in user can change a password. After the password is
changed, the end user is notified

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1331
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Validation Controls

Validation Controls

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1332
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Client Vs. Server side
Validation
ASP.NET can create both client-side and server-side
validation
Client-side validation
User
UserEnters
Enters
• Dependent on browser version
Data
Data Error
• Instant feedback
Message
• Reduces postback cycles
Server-side validation
Valid?
Valid?
• Repeats all client-side validation No
• Can validate against stored data Client Yes
Server
Valid?
Valid?
No
Yes

Web
WebForm
Form
Processed
Processed

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1333
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Types of Validation Controls

Custom RequiredField
Custom RequiredField
Validator Validator
Validator Validator

Validation
Validation Validation Controls
Summary
Summary
RangeValidator
RangeValidator

Regular
Regular
Expression
Compare Expression
Compare Validator
Validator Validator
Validator

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1334
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET RequiredField Validator

RequiredFieldValidator
Ensures that the user does not skip an entry

Name: <asp:TextBox id=Text1 runat="server"/>


<asp:RequiredFieldValidator
id="RequiredFieldValidator1"
ControlToValidate="Text1" Font-Names="Arial" Font-
Size="11" runat="server">
Required field!
</asp:RequiredFieldValidator>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1335
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Range Validator

RangeValidator
Checks that a user's entry is between specified lower and upper boundaries

<asp:RangeValidator ID="RangeValidator1" runat="server"


ControlToValidate="TextBox1"
ErrorMessage="Value must be >1 and <=10"
MaximumValue="10" MinimumValue="1">
</asp:RangeValidator>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1336
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET RegularExpression Validator

RegularExpressionValidator

Checks that the entry matches a pattern defined by a regular expression

Properties
•ControlToValidate contains the value to validate
•ValidationExpression contains the regular expression to match.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1337
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET RegularExpression Validator

<table bgcolor="#eeeeee" cellpadding=10>


<tr> <td align=right><font face=Verdana size=2>Zip Code:</font>
</td>
<td><ASP:TextBox id=TextBox1 runat=server /> </td>
<td>
<asp:RegularExpressionValidator
id="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox1"
ValidationExpression="\d{6}"
Display="Static"
Font-Names="verdana"
Font-Size="10pt">
Zip code must be 6 numeric digits
</asp:RegularExpressionValidator>
</td> </tr>
<tr> <td>
<ASP:Button ID="Button1" text="Validate" OnClick="ValidateBtn_Click" runat=server
/> </td>
<td colspan=3>
<asp:Label ID="lblOutput" Text="Enter a 5 digit zip code" Font-Names="Verdana"
Font-Size="10pt" runat="server"/>
</td>
</tr>
</table>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1338
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET RegularExpression Validator

public void ValidateBtn_Click(Object Src, EventArgs E)


{
if (Page.IsValid)
{
lblOutput.Text = "Page is Valid!";
}
else
{
lblOutput.Text = "Page is InValid! :-(";
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1339
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Compare Validator

CompareValidator
Compares a user's entry with a constant value or a property value of another control

Properties
• ControlToValidate and ControlToCompare contain the values to
compare.
• Operator defines the type of comparison to perform

<asp:CompareValidator ID="CompareValidator1"
runat="server" ControlToCompare="TextBox1“
ControlToValidate="TextBox2"
ErrorMessage="Both values are not equal">
</asp:CompareValidator>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1340
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Custom Validator

CustomValidator
Checks the user's entry using validation logic

<asp:CustomValidator ID="CustomValidator1" runat="server"


ControlToValidate="TextBox1“
ErrorMessage="The number must be even"
OnServerValidate="MyFunction"
ValidateEmptyText="True">Enter a even number
</asp:CustomValidator>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1341
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Custom Validator

Features
• For client-side custom validation, the name of the custom function
must be identified in the ClientValidationFunction property.
 The custom function must have the form function
myvalidator(source, arguments) source is the client-side
CustomValidator object
 arguments is an object with two properties, Value and IsValid.
 The Value property is the value to be validated
 IsValid property is a Boolean used to set the return result of the
validation.
• For server-side custom validation, place your custom validation in the
validator's OnServerValidate delegate.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1342
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET ValidationSummary

ValidationSummary

Displays the validation errors in summary form for all of the validators on a page

<asp:ValidationSummary ID="ValidationSummary1"
runat="server" HeaderText="Errors in the Page:" />

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1343
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Navigation Controls

Navigation Controls

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1344
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Navigation Controls

TreeView
TreeView

SiteMapPath
SiteMapPath

Menu
Menu

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1345
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Navigation Controls-Schema

Controls
SiteMap-
Menu TreeView SiteMapPath
DataSource

Site Map API SiteMap

SiteMapNode SiteMapNode SiteMapNode

Providers
Other
OtherSite
SiteMap
Map
XmlSiteMapProvider Providers
Providers

Site Maps
Other
Web.sitemap
Data Stores

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1346
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET SiteMap
Features of SiteMap
• The new site navigation system includes the capability to define the
web site in an XML file that is called a site map.
• Another addition in ASP.NET 2.0 is a new data provider –
SiteMapDataSource that is specifically developed to work with
site map files and to bind them to a new series of navigation-based
server controls

AAsite
sitemap
mapisisan
anXML
XMLdescription
descriptionofofthe
theweb
website’s
site’sstructure.
structure.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1347
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
SiteMap

<?xml version="1.0" encoding="utf-8" ?>

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-
1.0" >
<siteMapNode title="Home" description="Home Page"
url="Default.aspx">
<siteMapNode title="News" description="The Latest News"
url="News.aspx">
<siteMapNode title="U.S." description="U.S. News"
url="News.aspx?cat=us" />
<siteMapNode title="World" description="World News"
url="News.aspx?cat=world" />
<siteMapNode title="Technology" description="Technology
News"
url="News.aspx?cat=tech" />
<siteMapNode title="Sports" description="Sports News"
url="News.aspx?cat=sport" />
</siteMapNode>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1348
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
SiteMap

<siteMapNode title="Finance"
description="The Latest Financial Information"
url="Finance.aspx">
<siteMapNode title="Quotes" description="Get the Latest
Quotes"
url="Quotes.aspx" />
<siteMapNode title="Markets" description="The Latest Market
Information"
url="Markets.aspx">
<siteMapNode title="U.S. Market Report"
description="Looking at the U.S. Market" url="MarketsUS.aspx" />
<siteMapNode title="NYSE"
description="The New York Stock Exchange" url="NYSE.aspx" />
</siteMapNode>
<siteMapNode title="Funds" description="Mutual Funds"
url="Funds.aspx" />
</siteMapNode>
<siteMapNode title="Weather" description="The Latest Weather"
url="Weather.aspx" />
</siteMapNode></siteMap>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1349
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
SiteMap Properties

Attribute Description
title The title attribute provides a textual description
of the link. The String value used here is the
text used for the link.
descripti The description attribute not only reminds you
on what the link is for, but it is also used for the
ToolTip attribute on the link. The ToolTip
attribute is the yellow box that shows up next to
the link when the end user hovers the cursor
over the link for a couple of seconds.
url The url attribute describes where the file is
located in the solution. If the file is in the root
directory, simply use the file name, such as
“Default.aspx”.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1350
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET SiteMapPath Control

SiteMapPath Control

• The SiteMapPath control creates a breadcrumb navigation. This is a


linear path defining where the end user is in the navigation
structure

<asp:SiteMapPath
<asp:SiteMapPath ID="Sitemappath1"
ID="Sitemappath1" runat="server">
runat="server">
</asp:SiteMapPath>
</asp:SiteMapPath>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1351
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
SiteMapPath Control Properties
The PathSeparator Property
• The SiteMapPath control uses a greater than sign (>) by default to
separate the link elements
• <asp:SiteMapPath ID="Sitemappath1" runat="server" PathSeparator=" |
"> </asp:SiteMapPath>
Or
<asp:SiteMapPath
<asp:SiteMapPath ID="Sitemappath1"
ID="Sitemappath1" runat="server">
runat="server">

<PathSeparatorTemplate>
<PathSeparatorTemplate> || </PathSeparatorTemplate>
</PathSeparatorTemplate>
</asp:SiteMapPath>
</asp:SiteMapPath>
<PathSeparatorTemplate>
<PathSeparatorTemplate>
<asp:Image
<asp:Image ID="Image1"
ID="Image1" runat="server"
runat="server"
ImageUrl="divider.gif"
ImageUrl="divider.gif" />
/>
</PathSeparatorTemplate>
</PathSeparatorTemplate>

The PathDirection Property


• This property changes the direction of the links generated in the output.
Only two settings are possible for this property: RootToCurrent and
CurrentToRoot.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1352
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
SiteMapPath Control Properties
The ParentLevelsDisplayed Property
• This property displays pages only as deep as specified

<asp:SiteMapPath
<asp:SiteMapPath ID="Sitemappath1"
ID="Sitemappath1" runat="server"
runat="server"
ParentLevelsDisplayed="2">
ParentLevelsDisplayed="2">
</asp:SiteMapPath>
</asp:SiteMapPath>

The ShowToolTips Property


• The SiteMapPath control generates tooltips for each link if a
description property is used within the Web.sitemap file.

<asp:SiteMapPath
<asp:SiteMapPath ID="Sitemappath1"
ID="Sitemappath1" runat="server"
runat="server"
ShowToolTips="false">
ShowToolTips="false">
</asp:SiteMapPath>
</asp:SiteMapPath>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1353
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Processing SiteMapPath Control Nodes

Child Element Description


CurrentNodeSt Applies styles to the link in the
yle SiteMapPath navigation for the
currently displayed page.
CurrentNodeTe Applies a template construction to the
mplate link in the SiteMapPath navigation for
the currently displayed page.
NodeStyle Applies styles to all links in the
SiteMapPath navigation. The settings
applied in the CurrentNodeStyle or
RootNodeStyle elements supersede any
settings placed here.
NodeStyleTem Applies a template construction to all
plate links in the SiteMapPath navigation.
The settings applied in the
CurrentNodeStyle or RootNodeStyle
elements supersede any settings placed
here.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1354
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Processing SiteMapPath Control Nodes

Child Element Description


PathSeparatorSt Applies styles to the link dividers in
yle the SiteMapPath navigation.
PathSeparatorTe Applies a template construction to the
mplate link dividers in the SiteMapPath
navigation.
RootNodeStyle Applies styles to the first link (the root
link) in the SiteMapPath navigation.
RootNodeTempla Applies a template construction to the
te first link in the SiteMap-Path
navigation.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1355
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET TreeView Control

TreeView Control

The TreeView server control is a rich server control for


rendering a hierarchy of data, so it is quite ideal for displaying
what is contained in the .sitemap file
• The first step is to create a SiteMapDataSource control on the
page.
• The TreeView control doesn’t just bind to the site map file
automatically as the SiteMapPath control does.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1356
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
TreeView Control

<asp:TreeView
<asp:TreeView ID="TreeView1"
ID="TreeView1" runat="server"
runat="server"
DataSourceID="SiteMapDataSource1">
DataSourceID="SiteMapDataSource1">
</asp:TreeView>
</asp:TreeView> <asp:SiteMapDataSource
<asp:SiteMapDataSource
ID="SiteMapDataSource1"
ID="SiteMapDataSource1" runat="server"
runat="server" />
/>
Node of a Tree View Conrtol
• Every element or entry in the TreeView control is called a node.
• The uppermost node in the hierarchy of nodes is the root node.
• It is possible for a TreeView control to have multiple root nodes.
• Any node, including the root node, is also considered a parent node
if it has any nodes that are directly under it in the hierarchy of
nodes.
• The nodes directly under this parent node are referred to as child
nodes.
• Each parent node can have one or more child nodes.
• If a node contains no child nodes, it is referred to as a leaf node.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1357
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Programming with TreeView Control

Binding the TreeView Control to an XML File


<?xml version="1.0" encoding="utf-8"?>
<Hardware>
<Item Category="Motherboards">
<Option Choice="Asus" /> <Option Choice="Abit" />
</Item>
<Item Category="Memory">
<Option Choice="128mb" /> <Option Choice="256mb" /> <Option Choice="512mb" />
</Item>
</Hardware>

Adding
AddingXmlDataSource
XmlDataSourceand
andassigning
assigningthe
thefilename
filenametoto“DataFile”
“DataFile”Attribute
Attribute

<asp:TreeView ID="Treeview1" runat="server" DataSourceID="Xmldatasource1">


<DataBindings>
<asp:TreeNodeBinding DataMember="Hardware" Text="Computer Hardware" />
<asp:TreeNodeBinding DataMember="Item" TextField="Category" />
<asp:TreeNodeBinding DataMember="Option" TextField="Choice" />
</DataBindings> </asp:TreeView>
<asp:XmlDataSource ID="Xmldatasource1" runat="server" DataFile="Hardware.xml">
</asp:XmlDataSource>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1358
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
TreeView Control-Selecting multiple
options
Valu Description
e
All Applies check boxes to each and every node within
the TreeView control.
Leaf Applies check boxes to only the nodes that have no
additional child elements.
Non Applies no check boxes to any node within the
e TreeView control.
Pare Applies check boxes to only the nodes considered
nt parent nodes within the TreeView control. A parent
node has at least one child node associated with it.
Root Applies a check box to any root node contained
within the TreeView control.

<asp:TreeView
<asp:TreeView ID="Treeview1"
ID="Treeview1" runat="server"
runat="server" Font-Underline="false"
Font-Underline="false"
DataSourceID="Xmldatasource1"
DataSourceID="Xmldatasource1" ShowCheckBoxes="Leaf"> ...
ShowCheckBoxes="Leaf"> ...
</asp:TreeViewTreeView>
</asp:TreeViewTreeView>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1359
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
TreeView Control

protected void Button1_Click(object sender, System.EventArgs e)


{
if (TreeView1.CheckedNodes.Count > 0)
{
Label1.Text = "We are sending you information on:<p>";
foreach (TreeNode node in TreeView1.CheckedNodes)
{
Label1.Text += node.Text + " " +
node.Parent.Text + <br>";
}
}
else
{
Label1.Text = "You didn't select any”;
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1360
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
TreeView Control-Expanding and
Collapsing Nodes
Expanding and Collapsing Nodes Programmatically
protected void Button1_Click(object sender, System.EventArgs e)
{
TreeView1.ExpandAll();
}

protected void Button2_Click(object sender, System.EventArgs e)


{
TreeView1.CollapseAll();
}

<asp:TreeView
<asp:TreeView ID="TreeView1"
ID="TreeView1" runat="server"
runat="server"
DataSourceId="SiteMapDataSource1"
DataSourceId="SiteMapDataSource1" OnDataBound="TreeView1_DataBound">
OnDataBound="TreeView1_DataBound">
</asp:TreeView>
</asp:TreeView>

protected void TreeView1_DataBound(object sender, System.EventArgs e)


{
TreeView1.CollapseAll(); TreeView1.FindNode("Home").Expand();
TreeView1.FindNode("Home/Finance").Expand();
TreeView1.FindNode("Home/Finance/Markets").Expand();
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1361
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
TreeView Control-Adding Nodes

Adding nodes programmatically to the TreeView control

protected
protected void
void Button3_Click(object
Button3_Click(object sender,
sender,
System.EventArgs
System.EventArgs e)e)
{{
TreeNode
TreeNode myNode
myNode == new
new TreeNode();
TreeNode();
myNode.Text = TextBox1.Text;
myNode.Text = TextBox1.Text;
myNode.NavigateUrl
myNode.NavigateUrl == TextBox2.Text;
TextBox2.Text;
TreeView1.FindNode("Home/Finance/Markets").ChildNode
TreeView1.FindNode("Home/Finance/Markets").ChildNode
s.Add(myNode);
s.Add(myNode);
}}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1362
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Menu Control

Menu Control

This control is ideal for allowing the end user to navigate a larger hierarchy of options while utilizing very little
browser space in the process.

<asp:Menu
<asp:Menu ID="Menu1"
ID="Menu1" runat="server"
runat="server"
DataSourceID="SiteMapDataSource1">
DataSourceID="SiteMapDataSource1">
</asp:Menu>
</asp:Menu>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1363
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Menu Control-Styles
Applying Different Styles to the Menu Control
• Using a Predefined Style
• Changing the Style for Static Items
 <StaticHoverStyle>
 <StaticMenuItemStyle>
 <StaticMenuStyle>
 <StaticSelectedStyle>
 <StaticTemplate>

<asp:Menu
<asp:Menu ID="Menu1"
ID="Menu1" runat="server"
runat="server"
DataSourceID="SiteMapDataSource1">
DataSourceID="SiteMapDataSource1">
<StaticHoverStyle
<StaticHoverStyle BackColor="DarkGray"
BackColor="DarkGray" BorderColor="Black"
BorderColor="Black"
BorderStyle="Solid"
BorderStyle="Solid"
BorderWidth="1">
BorderWidth="1">
</StaticHoverStyle>
</StaticHoverStyle>
</asp:Menu>
</asp:Menu>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1364
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Menu Control-Styles

• Adding Styles to Dynamic Items


 <DynamicHoverStyle>
 <DynamicMenuItemStyle>
 <DynamicMenuStyle>
 <DynamicSelectedStyle>
 <DynamicTemplate>

• Changing the Layout of the Menu Items

<asp:Menu
<asp:Menu ID="Menu1"
ID="Menu1" runat="server"
runat="server"
DataSourceID="SiteMapDataSource1“
DataSourceID="SiteMapDataSource1“
Orientation="Horizontal">
Orientation="Horizontal">
</asp:Menu>
</asp:Menu>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1365
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Menu Control-Styles

•Changing the Pop-Out Symbol

<asp:Menu
<asp:Menu ID="Menu1"
ID="Menu1" runat="server"
runat="server"
DataSourceID="SiteMapDataSource1"
DataSourceID="SiteMapDataSource1"
Orientation="Horizontal"
Orientation="Horizontal"
DynamicPopOutImageUrl="myArrow.gif"
DynamicPopOutImageUrl="myArrow.gif"
StaticPopOutImageUrl="myArrow.gif">
StaticPopOutImageUrl="myArrow.gif">
</asp:Menu>
</asp:Menu>
•Separating Menu Items with Images

<asp:Menu
<asp:Menu ID="Menu1"
ID="Menu1" runat="server"
runat="server"
DataSourceID="SiteMapDataSource1"
DataSourceID="SiteMapDataSource1"
DynamicBottomSeparatorImageUrl="myDivider.gif">
DynamicBottomSeparatorImageUrl="myDivider.gif">
</asp:Menu>
</asp:Menu>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1366
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Menu Control-Events
Menu Events
The Menu control exposes events such as the following:
• DataBinding
• DataBound
• Disposed
• Init
• Load
• MenuItemClick
• MenuItemDataBound
• PreRender
• Unload

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1367
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Advanced Controls

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Advanced Controls
Topics for Discussion
• User Controls
• Composite Controls
• Custom Controls
• Web Parts

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1369
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET User Controls

User Controls

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1370
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET User Controls
A user control is the grouping of existing server controls
into a
single container control
• User controls are included in a Web Forms page using a Register
directive:
• <%@ Register TagPrefix=“Ctr" TagName="Message"
Src=“Userctrl.ascx" %>
 The TagPrefix determines a unique namespace for the user
control
 The TagName is the unique name for the user control .
 The Src attribute is the virtual path to the user control
• User controls have a .ascx extension
• User control is of type System.Web.UI.UserControl, which inherits
directly from System.Web.UI.Control .

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1371
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Importing User Controls

A user control imported into another Web Forms page.


The user control in this case is just a simple static file.

<%@ Page Language="C#" %>


<%@ Register TagPrefix=“Ctr" TagName="Message" Src="userctrl_cs.ascx"
%>
<html>
<body style="font: 10pt verdana">
<h3>A Simple User Control</h3>
<Ctr:Message runat="server" id="Message1" />
</body>
</html>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1372
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Exposing User Control Properties
• When a Web Forms page is treated as a control, the public fields
and methods of that Web Form are promoted to public properties
and methods of the control as well

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1373
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Exposing User Control Properties

void SubmitBtn_Click(Object sender, EventArgs E)


{
MyMessage.Text = "Message text changed!";
MyMessage.Color = "red";
}

<%@ Register TagPrefix=“Ctr" TagName="Message" Src=“Userctrl_cs.ascx" %>

<Ctr:Message id="MyMessage" Text="This is a custom message!"


Color="blue" runat="server"/>
<asp:button text="Change Properties" OnClick="SubmitBtn_Click"
runat=server/>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1374
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Exposing User Control Properties

UserCtrl.ascx.cs

public String Color = "blue";


public String Text = "This is a simple message user control!";

<span
<span id="Message"
id="Message" style="color:<%=Color%>"><%=Text%></span>
style="color:<%=Color%>"><%=Text%></span>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1375
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Encapsulating User Control Events
• User controls participate in the complete execution lifecycle of the
request, much the way ordinary server controls do.
• A user control can handle its own events, encapsulating some of
the page logic from the containing Web Forms page.

<%@
<%@ Page
Page Language="C#"
Language="C#" %>%>
<%@
<%@ Register TagPrefix=“Ctr” TagName="BookList"
Register TagPrefix=“Ctr” TagName="BookList"
Src="userctrl_cs.ascx"
Src="userctrl_cs.ascx" %> %>
<html>
<html>
<body
<body style="font:
style="font: 10pt
10pt verdana">
verdana">
<h3>A
<h3>A User
User Control
Control w/
w/ an
an Event</h3>
Event</h3>
<form runat="server">
<form runat="server">
<Ctr:BookList
<Ctr:BookList runat="server"
runat="server" id="BookList1"
id="BookList1" />
/>
</form>
</form>
</body>
</body>
</html>
</html>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1376
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Custom Controls

Custom Controls

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1377
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Custom Controls
Developing and Using a Custom Server Control 
• Create an ASP.NET server control.
• Add metadata to the control and its members to control security
and design-time behavior.
• Use the App_Code directory in an ASP.NET Web site to test your
control without manual compilation steps.
• Specify a tag prefix in a configuration file and in the control's
assembly.
• Compile the control into an assembly and add it to the Bin
directory.
• Embed a bitmap into the control's assembly as the toolbox icon for
a visual designer.
• Use the compiled control in a page.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1378
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating a Custom Control
1.Creating an ASP.NET server control.

• A simple control similar to the standard Label control.


• The WelcomeLabel class derives from WebControl and defines a
Text property that allows a page developer to provide a text string
to welcome a user to a site.
• WelcomeLabel appends the user's name to the text string if the
user's name is present in the header sent by the user's browser

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1379
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating a Custom Control-Adding metadata

2.Add metadata to the control and its members to control


security
and design-time behavior.(Class Level)
• AspNetHostingPermissionAttribute is a code-access security
attribute. It causes the JIT compiler to check that code that links to
WelcomeLabel is granted the AspNetHostingPermission permission.
• DefaultPropertyAttribute is a design-time attribute that specifies
the default property of a control.
• ToolboxDataAttribute specifies the format string for the element.
The string becomes the control's markup when the control is
double-clicked in the toolbox or dragged from the toolbox onto the
[[
design surface. For WelcomeLabel,Level
AspNetHostingPermission(SecurityAction.Demand, the= string creates this element:
AspNetHostingPermission(SecurityAction.Demand, Level =
AspNetHostingPermissionLevel.Minimal),
AspNetHostingPermissionLevel.Minimal),
AspNetHostingPermission(SecurityAction.InheritanceDemand,
AspNetHostingPermission(SecurityAction.InheritanceDemand,
Level=AspNetHostingPermissionLevel.Minimal),
Level=AspNetHostingPermissionLevel.Minimal),DefaultProperty("Text"),
DefaultProperty("Text"),
ToolboxData("<{0}:WelcomeLabel
ToolboxData("<{0}:WelcomeLabelrunat=\"server\">
runat=\"server\"></{0}:WelcomeLabel>")
</{0}:WelcomeLabel>")
]]

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1380
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating a Custom Control-Adding metadata

public class WelcomeLabel : WebControl


{ [ Bindable(true),
Category("Appearance"),
DefaultValue(""),
Description("The welcome message text."),
Localizable(true) ]
public virtual string Text
{
get {
string s = (string)ViewState["Text"]; return (s == null) ?
String.Empty : s;
}
set
{ ViewState["Text"] = value; }
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1381
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating a Custom Control-Adding metadata

protected override void RenderContents(HtmlTextWriter writer)


{
writer.WriteEncodedText(Text);
if (Context != null)
{
string s = Context.User.Identity.Name;
if (s != null && s != String.Empty)
{
string[] split = s.Split('\\');
int n = split.Length - 1;
if (split[n] != String.Empty)
{
writer.Write(", "); writer.Write(split[n]);
} } } writer.Write("!"); } }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1382
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating a Custom Control-Adding metadata

The following attributes applied to the Text property of WelcomeLabel are


standard design-time attributes that you will generally apply to all public
properties of your controls:
• BindableAttribute, specified as true or false, specifies for visual
designers whether it is meaningful to bind the property to data.
• CategoryAttribute specifies how to categorize the property in the visual
designer's property browser.
• DescriptionAttribute specifies a brief description of the property. In
Visual Studio 2005, the property browser displays the description of the
selected property at the bottom of the Properties window.
• DefaultValueAttribute specifies a default value for the property. This
value should be the same as the default value you return from the
property accessor (getter).
• LocalizableAttribute, specified as true or false, specifies for visual
designers whether it is meaningful to localize the property. When a
property is marked Localizable(true), the visual designer includes it when
serializing localized resources.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1383
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating a Custom Control -Using App_Code dir

3.Using the App_Code Directory to Test Controls Without


Compilation

• Use the ASP.NET dynamic compilation feature to test your control


in a page without compiling the control into an assembly.
• ASP.NET dynamically compiles code placed in the App_Code
directory under an ASP.NET Web site's root.
• Classes in source files in App_Code can thus be accessed from
pages without being manually compiled into assemblies.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1384
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating a Custom Control-Creating Tag Prefix

4.Creating a Tag Prefix


• A tag prefix is the prefix, such as "asp" in <asp:Table />, that appears before a
control's type name when the control is created declaratively in a page.
• To enable the control to be used declaratively in a page, ASP.NET needs a tag
prefix that is mapped to your control's namespace.
• A page developer can provide a tag prefix/namespace mapping by adding a @
Register directive on each page that uses the custom control
<%@ Register TagPrefix="aspSample"
Namespace="Samples.AspNet.VB.Controls"%>
• A page developer can specify the tag prefix/namespace mapping in the
Web.config file
<configuration>
<system.web>
<pages> <controls>
<add tagPrefix="aspSample" namespace="Samples.AspNet.CS.Controls"> </add>
</controls> </pages>
</system.web>
</configuration>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1385
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating a Custom Control-Compiling the control

5.To compile the control into an assembly


• Set the Windows environment PATH variable of your computer to
include the path to your .NET Framework installation by following
these steps:
 In Windows, right-click My Computer, select Properties, click the
Advanced tab, and click the Environment Variables button.
 In the System variables list, double-click the Path variable.
 In the Variable value text box, add a semicolon (;) to the end of
the existing values in the text box, and then type the path of
your .NET Framework installation. The .NET Framework is
generally installed in the Windows installation directory at
\Microsoft.NET\Framework\versionNumber.
 Click OK to close each dialog box.
• Run the following command from the directory you created for source
files in the first procedure of this walkthrough
csc /t:library /out:Samples.AspNet.CS.Controls.dll /r:System.dll
/r:System.Web.dll *.cs

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1386
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating a Custom Control-Embedding Icon
6.Embed a bitmap into the control's assembly as the toolbox icon
for a visual designer
To embed an icon in the control's assembly
• Create or obtain a 16-by-16-pixel bitmap as the toolbox icon for your control.
• Name the bitmap WelcomeLabel.bmp.
• Add the bitmap file to the directory (CustomControlsCS or CustomControlsVB) where
you have the source files for the WelcomeLabel control.
• Run the following command from the directory that contains the source files:
csc /res:WelcomeLabel.bmp,MyControl.WelcomeLabel.bmp /t:library /out:MyControl.dll
/r:System.dll /r:System.Web.dll *.cs

7.To add a namespace/tag prefix mapping using the


TagPrefixAttribute
• Create a file named AssemblyInfo.cs or AssemblyInfo.vb in your source code directory
and add the following code to the file.
using System;
using System.Web.UI;
[assembly: TagPrefix("Samples.AspNet.CS.Controls", "aspSample")]

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1387
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Using Custom Control
8.Using the Compiled Custom Control in an ASP.NET Page
To test the compiled version of the custom control, make the control's
assembly accessible to pages in the Web site.
• To make the control's assembly accessible to the Web site
 Create a Bin directory under the root of the Web site.
 Copy the control assembly to the Bin directory.
 Delete the control's source file from the App_Code directory.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1388
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Web Parts

Web Parts

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1389
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Web Parts
“Web parts provides an infrastructure to create customizable
web pages”
Topics for discussion:
• Web Part Basics
• Building Web Parts
 Creating Web Part Manganer
 Creating Web PartZone
• Changing Layout Orientation and disabling changes
• Zone Templates
• Changing the mode of the Web page
 Browse (Minimize/Maximize/Restore)
 Design (Drag and Drop)
 Catalog (Add webparts/ Add to webparts)
 Edit (Apperance/ Layout/ Behaviour)
• Web Part Verbs
• Connecting Web Parts

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1390
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Parts-Basics
Web Part Basics
• Web parts , part of the larger Portal Framework , provides an
outstanding way to build modular web site that can be customized
with dynamically reapplied settings on a per-user basis.
• Web parts are objects in the Portal framework which the end user
can open, close, minimize, maximize, or move from one part of the
page to another.
• The portal framework enables in the building of web pages that
contain multiple web parts – which are part of the ASP.NET server
control framework and are used like any other ASP.NET server
controls

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1391
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Parts-Key Components
The key components of the Web Part framework are:
• The System.Web.UI.WebControls.WebParts.WebPart class—The
WebPart is the base class outlining configuration properties that
allow sub classes to be members of Web Part Zones.
• The System.Web.UI.WebControls.WebParts.WebPartZone control—
The WebPartZone control is a wrapper around a collection of Web
Parts.
• The System.Web.UI.WebControls.WebParts.WebPartManager
control—One WebPartManager is linked to each page that uses Web
Parts.
• These three controls combine together to create Web pages that
are visually and functionally similar to complex desktop
applications.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1392
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Parts-Creating Web Part
Manager
Creating Web Part Manager
• The Portal framework defines everyhting in zones.There are zones
for laying out and editing content.
• The zones that a page are incorporates are managed by a Portal
Framework Manager-Web Part Manager
• The WebPartManager control is an ASP.NET control that completely
managfes the state and content of zones on per-user basis.
• A single WebPartManager manages only one page in the application
that works with the Portal framework
• Drag and drop a WebPartManager control from ToolBox to the Web
page yet to contain Webparts

<asp:WebPartManager
<asp:WebPartManager ID="WebPartManager1"
ID="WebPartManager1"
runat="Server"
runat="Server" />
/>
</asp:WebPartManager>
</asp:WebPartManager>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1393
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Parts-Creating Web Part Zones
Creating Web PartZone

• Web pages are constructed in al linear fashion either horizontally or


vertically.
• Web zones define specific rows or columns as individual content
areas managed by the WebPart Manager
• Drag and drop a WebPartZone control to each area in a table
wherever webparts are necessary

<asp:WebPartZone
<asp:WebPartZone ID="WebPartZone1"
ID="WebPartZone1" runat="server“>
runat="server“>
</asp:WebPartZone>
</asp:WebPartZone>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1394
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Parts-Web Part Zones
Properties
Changing Layout Orientation and disabling changes
• The Web Parts within a WebPartZone control can be displayed
either horizontally or vertically using the LayoutOrientaton attribute

<asp:WebPartZone
<asp:WebPartZone ID="WebPartZone1"
ID="WebPartZone1" runat="server“
runat="server“
LayoutOrientation=“Horizontal”></asp:WebPartZone>
LayoutOrientation=“Horizontal”></asp:WebPartZone>
• The Web Parts can be prevented from user modification like drag
and drop by setting the AllowLayoutChange attribute

<asp:WebPartZone
<asp:WebPartZone ID="WebPartZone1"
ID="WebPartZone1" runat="server“
runat="server“
AllowLayoutChange=“false”>
AllowLayoutChange=“false”>
</asp:WebPartZone>
</asp:WebPartZone>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1395
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Building Web Parts

• When using VS2005, by default the IDE creates a Microsoft SQL


Server Express Edition file called ASPNETDB.MDF and stores it in
the App_Data folder of web Projects.
• This database file is where the Portal Framework stores all the
customization points

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1396
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Parts-Changing mode of web page

Changing the mode of the Web page


• Browse (Minimize/Maximize/Restore)
 End user cannot edit or move sections of the page
• Design (Drag and Drop)
 Enables end user to rearrange the order of the page’s modular
 components,delete items from a zone, or move items from one
 page zone to another
• Catalog (Add webparts/ Add to webparts)
 Displays a list of available webparts that can be placed in a
page.
• Edit (Apperance/ Layout/ Behaviour)
 Enables end user to select particular sections on the page for
 editing like changing part’s title,color or even setting custom
 properties

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1397
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Parts-Changing mode of web page

Changing the mode of the Web page


protected void Page_Init(object sender, EventArgs e)
{
foreach (WebPartDisplayMode wp1 in
WebPartManager1.SupportedDisplayModes)
{
string modeName = wp1.Name;
ListItem dd = new ListItem(modeName, modeName);
DropDownList1.Items.Add(dd);
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.Items.Clear();
DropDownList1.Items.Add("Design");
DropDownList1.Items.Add("Browse");
DropDownList1.Items.Add("Catalog");
DropDownList1.Items.Add("Edit");
} }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1398
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Parts-Changing mode of web page

protected void DropDownList1_SelectedIndexChanged1(object sender,


EventArgs e)
{
if (DropDownList1.SelectedValue == "Design")
{
WebPartManager1.DisplayMode =
WebPartManager.DesignDisplayMode;
}
else if (DropDownList1.SelectedValue == "Browse")
{
WebPartManager1.DisplayMode =
WebPartManager.BrowseDisplayMode;
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1399
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Parts-Changing mode of web page

else if (DropDownList1.SelectedValue == "Catalog")


{ WebPartManager1.DisplayMode =
WebPartManager.CatalogDisplayMode;
}
else if (DropDownList1.SelectedValue == "Edit")
{ WebPartManager1.DisplayMode =
WebPartManager.EditDisplayMode;
}
else if (DropDownList1.SelectedValue == "Connect")
{ WebPartManager1.DisplayMode =
WebPartManager.ConnectDisplayMode;
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1400
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Parts-Catalog Zone
Adding web parts to a page
Catalog zone is further divided into three types:
• Page
• Declarative
• Import.

<asp:PageCatalogPart>
Page catalog displays the number of web parts that are closed by
using this option.
• The ASP.NET 2.0 Portal framework enables an end user to add Web
parts to a page provided the user has a list of items to add.
• Includes Webparts not displayed on the page by default and web
capabilities of the Portal Framework

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1401
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Parts-Page Catalog Part
PageCatalogPart
• Add a CatalogZone to the web page.
• Add a PageCatalogPart within a ZoneTemplate.
• To get some items in the Catalog delete, some webparts.
• Select a webpart and a zone and click “Add” to add a particular
webpart to a zone.

<asp:CatalogZone
<asp:CatalogZone ID="CatalogZone1"
ID="CatalogZone1" runat="server"
runat="server" >>
<ZoneTemplate>
<ZoneTemplate>
<asp:PageCatalogPart
<asp:PageCatalogPart ID="PageCatalogPart1"
ID="PageCatalogPart1"
runat="server“/>
runat="server“/>
</ZoneTemplate>
</ZoneTemplate>
</asp:CatalogZone>
</asp:CatalogZone>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1402
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Parts-Declarative Catalog Part
Moving Web parts
<asp:DeclarativeCatalogPart>
Declarative catalog displays the number of elements that are
added in design
mode in catalog zone.
 To enable the end user to add more than one of any particular
Web part to a page
 Place the <asp:DeclarativeCatalogPart> control within the
<ZoneTemplate> element of <asp:CatalogZone.>

<ZoneTemplate><asp:DeclarativeCatalogPart
<ZoneTemplate><asp:DeclarativeCatalogPart
ID="DeclarativeCatalogPart1"
ID="DeclarativeCatalogPart1" runat="server">
runat="server">
<WebPartsTemplate>
<WebPartsTemplate> <asp:Button
<asp:Button ID="Button1"
ID="Button1"
runat="server"
runat="server" Text="AnnButton"
Text="AnnButton" />
/>
</WebPartsTemplate>
</WebPartsTemplate>
</asp:DeclarativeCatalogPart></ZoneTemplate>
</asp:DeclarativeCatalogPart></ZoneTemplate>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1403
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Parts-Declarative Catalog Part
• The templated <asp:DeclarativeCatalogPart> control needs a
<WebPartsTemplate> to place the controls that needs to be
available to the ened user as options.
• The controls appear in a check box list in the same order in which it
is declared in the <WebPartsTemplate> section.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1404
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Parts-Import Catalog Part
Importing Web Parts
<asp:ImportCatalogPart>
Import Catalog displays the number of elements that are
selected to import. You can
import files that have the ".WebPart" extension.
• To export a file as a .WebPart type file, add the following line to
web.config.
<webParts enableExport="true"></webParts>
• Set the ExportMode property of the control to all.
• If the control is derived from WebPart, do the following
<aspSample:CustomWebPart id="Sample" runat="server"
ExportMode="All" />
Or, you can write the following code on page load.
GenericWebPart qwp=new GenericWebPart();
gwp = WebUserControl2_1.Parent
gwp.ExportMode = WebPartExportMode.All

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1405
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Parts-Modifying Settings using EditorZone

<asp:EditorZone>
• In edit mode, web parts can be edited at runtime as well.
Editing a web part is further divided into four types:
Appearance, Behavior, Property, and Layout.
 Place editor zone on the page.
 Place AppearanceEditorPart and LayoutEditorPart in theeditor
zone.
 Run the application and select edit mode from the option box.
 Click edit from the menu available for web parts.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1406
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Parts-Modifying Settings using EditorZone

<asp:EditorZone
<asp:EditorZone ID="EditorZone1"
ID="EditorZone1" runat="server">
runat="server">
<ZoneTemplate>
<ZoneTemplate>
<asp:AppearanceEditorPart
<asp:AppearanceEditorPart ID="AppearanceEditorPart1"
ID="AppearanceEditorPart1"
runat="server"
runat="server" />
/>
<asp:BehaviorEditorPart
<asp:BehaviorEditorPart ID="BehaviorEditorPart1"
ID="BehaviorEditorPart1"
runat="server" />
runat="server" />
<asp:LayoutEditorPart
<asp:LayoutEditorPart ID="LayoutEditorPart1"
ID="LayoutEditorPart1"
runat="server" />
runat="server" />
<asp:PropertyGridEditorPart
<asp:PropertyGridEditorPart ID="PropertyGridEditorPart1"
ID="PropertyGridEditorPart1"
runat="server"
runat="server" />
/>
</ZoneTemplate>
</ZoneTemplate>
</asp:EditorZone>
</asp:EditorZone>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1407
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Parts-Modifying Settings using EditorZone

Modifying The Web Part Settings


<asp:EditorZone>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1408
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Parts-Verbs
Web Part Verbs
• Web part verbs declare the actions of the items that
appear in the title.
• The <asp:WebPartZone> control allows to control these
verbs by nesting the appropriate verb elements within the
<asp:WebPartZone> element
<CloseVerb
 <CloseVerb/><CloseVerb Enabled="false"
Enabled="false" />
/>
<CloseVerb
<CloseVerb Visible="true"
Visible="true" />
/>
<CloseVerb
<CloseVerb ImageUrl="bullet.gif" />
ImageUrl="bullet.gif" />

 <ConnectVerb />
 <EditVerb />
 <ExportVerb />
 <HelpVerb />
 <MinimizeVerb />
 <RestoreVerb />

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1409
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Connecting Web parts
Connecting Web Parts

• The <asp:ConnectionsZone> control allows to make


property connections between two Web parts on the same
page.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1410
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Server Side Data Access

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Server Side Data Access

Data Binding

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1412
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Binding Model

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1413
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Data Controls

Data Controls

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1414
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Data Controls
Topics for discussion:
• Data Source Controls
 SqlDataSource
 ObjectDataSource
 AccessDataSource
 SiteMapDataSource
 XMLDataSource
• Data Bound Controls
 DataGrid
 GridView
 DataList
 DetailsView
 FormView
 Repeater

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1415
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Data Controls
Data
DataControls
Controls

Repeater
Repeater DataList
DataList

ReportViewer
ReportViewer DetailsView
DetailsView

Data Bound Data


GridView Data FormView
GridView FormView

Data Source XMLDataSource


XMLDataSource SqlDataSource
SqlDataSource

ObjectDataSource
ObjectDataSource AccessDataSource
AccessDataSource

SiteMapDataSource
SiteMapDataSource

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1416
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Data Source Controls

Data Source Controls

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1417
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Data Source Controls
Data Source Controls

• Data source controls have no rendering, but instead


represent a particular backend data store, for example a
database, business object, XML file, or XML Web Service

• Data source controls also enable rich capabilities over data -


such as sorting, paging, filtering, updating, deleting, and
inserting - that data-bound UI controls can automatically
use.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1418
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Data Source Controls

Name Description
Enables binding to a SQL database
SqlDataSourc represented by an ADO.NET provider, such
e as Microsoft™ SQL Server, OLEDB, ODBC,
or Oracle.
Enables binding to a middle-tier object
ObjectDataSo
such as a data access layer or business
urce
component.
AccessDataSo Enables binding to a Microsoft™ Access
urce (Jet) database.
SiteMapDataS Enables binding to the hierarchy exposed
ource by an ASP.NET 2.0 site navigation provider.
XmlDataSour Enables binding to an XML file or
ce document.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1419
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET SqlDataSource Control
SqlDataSource

Enables binding to a SQL database represented by an ADO.NET provider, such as Microsoft™ SQL Server,
OLEDB, ODBC, or Oracle.
• Data binding to SQL Database
 Microsoft SQL Server, Oracle, DB2, etc.
• Two-way data binding supported
 SelectCommand
 InsertCommand, UpdateCommand, and DeleteCommand
• Optional caching of query results
• Parameterized operation

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1420
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
SqlDataSource Control

<asp:SqlDataSource
<asp:SqlDataSource
ID="Titles"
ID="Titles"
ConnectionString="<%$
ConnectionString="<%$ connectionStrings:pubs
connectionStrings:pubs %>"
%>"
RunAt="server“
RunAt="server“
SelectCommand="select
SelectCommand="select title_id,
title_id, title,
title, price
price
from titles"
from titles"
/>
/>
<asp:DataGrid
<asp:DataGrid
DataSourceID="Titles"
DataSourceID="Titles"
RunAt="server"
RunAt="server" />
/>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1421
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
SqlDataSource Control Properties

Name Description

ConnectionString Connection string used to connect to data source

SelectCommand Command used to perform queries

InsertCommand Command used to perform inserts

UpdateCommand Command used to perform updates

DeleteCommand Command used to perform deletes

DataSourceMode Specifies whether DataSet or DataReader is used


(default = DataSet)

ProviderName Specifies provider (default = SQL Server .NET provider)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1422
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET ObjectDataSource Control

ObjectDataSource

Enables binding to a middle-tier object such as a data access layer or


business component.
• Most applications encapsulate data logic
 Best practice and simplifies maintenance
 Embedding SQL code is not recommended
• ObjectDataSource
 Bind to custom business objects
 Visual Studio data components
 Parallels SqlDataSource in object model

<asp:ObjectDataSource
<asp:ObjectDataSource ID=“MySource”
ID=“MySource” TypeName=“CustomersDB”
TypeName=“CustomersDB”
SelectMethod=“GetCustomersByRegion”
SelectMethod=“GetCustomersByRegion”
UpdateMethod=“UpdateCustomer”
UpdateMethod=“UpdateCustomer” runat=“server”/>
runat=“server”/>
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1423
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ObjectDataSource Control
• The ObjectDataSource control allows developers to structure their
applications using the traditional three-tiered architecture and still
take advantage of the ease-of-use benefits of the declarative
databinding model in ASP.NET.

• Instead of a ConnectionString property, ObjectDataSource exposes


a TypeName property that specifies an object type (class name) to
instantiate for performing data operations.

• The ObjectDataSource control supports properties such as


SelectMethod, UpdateMethod, InsertMethod, and DeleteMethod for
specifying methods of the associated type to call to perform these
data operations.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1424
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ObjectDataSource Control

ObjectDataSource
ObjectDataSource Web Page

DataSourceID = ObjectDataSource1 <asp:ObjectDataSource


ID = ObjectDataSource1
Returns IEnumerable of Orders TypeName = OrdersComponent
• Order.OrderID SelectMethod = GetOrders
• Order.OrderName UpdateMethod = UpdateOrder
• Order.OrderDate DeleteMethod = DeleteOrder

OrderItemsComponent

OrdersComponent CompaniesComponent
Northwind
Database
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1425
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET AccessDataSource Control
AccessDataSource

Enables binding to a Microsoft™ Access


(Jet) database
• The AccessDataSource control is a data source control that
represents a connection to a Microsoft™ Access database.
• The AccessDataSource control derives from SqlDataSource, but
exposes a simple DataFile property for specifying the path to an
MDB file, instead of the complete connection string.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1426
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET SiteMapDataSource Control
SiteMapDataSource

Enables binding to the hierarchy exposed by an ASP.NET 2.0 site


navigation provider.

• The SiteMapDataSource enables to work with data stored in the


Web site’s SiteMap configuration file.
• The control does not support any of the data caching options that
exist in the other data source controls provided.
• The SiteMapDataSource control does not have any configuration
wizards like the other data source controls.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1427
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET XMLDataSource Control
XMLDataSource

Enables binding to an XML file or


document

The XmlDataSource control belongs to the family of data source


controls in ASP.NET, which enables a declarative databinding model
against a variety of underlying data stores.
The XMLDataSource control supports declarative databinding to XML
files
. XmlDataSource is an example of a hierarchical data source, which
supports the required interfaces to allow hierarchical data-bound
controls, such as TreeView and Menu, to traverse the hierarchy of
nodes to produce their rendering.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1428
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
XMLDataSource Control

XmlDataSource supports a
• DataFile property for specifying the path to an XML data file to be
used as input.
• TranformFile property to apply an XSLT transformation to the data
• XPath property for specifying a subset of nodes to expose from the
data source.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1429
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Data Bound Controls

Data Bound Controls

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1430
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Data Bound Controls
Data-bound controls are UI controls that render data as
markup
to the requesting client device or browser.
• A data-bound control can auto-bind to data exposed from a data
source and will fetch data at the appropriate time in the page
request lifecycle.
• These controls can optionally take advantage of data source
capabilities such as sorting, paging, filtering, updating, deleting,
and inserting.
• A data-bound control connects to a data source control through its
DataSourceID property

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1431
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Data Bound Controls

Name Description

Renders data in a grid format. This control is an


GridVie evolution of the DataGrid control, and can
w automatically take advantage of data source
capabilities.
Renders a single data item in a table of
label/value pairs, similar to the form view in
DetailsV
Microsoft™ Access. This control can also
iew
automatically take advantage of data source
capabilities.
Renders a single data item at a time in a form
defined by a custom template. Renders a single
FormVie data item in a table of label/value pairs, similar
w to the form view in Microsoft™ Access. This
control can also automatically take advantage of
data source capabilities.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1432
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Data Grid Control
• One of the most powerful server controls in ASP.NET is no doubt
the DataGrid control. The DataGrid control is a multi-column, data-
bound ASP.NET server control.

• Using the DataGrid control, you can display records from a


database using a variety of formats.

• You can also edit, update, and delete records from the database
using the DataGrid control. In this first part of the ASP.NET server
controls series, I will show you how to use the DataGrid control to
develop compelling Web applications.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1433
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Grid Control-Auto Format
In the default Web form, add a DataGrid control.
To change the format of the DataGrid control, right-click on it and select
Auto-Format....
Choose any scheme

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1434
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Grid Control-Configuration
There are two ways in which you can configure the
DataGrid control:
Using the Property Builder
• Modifying the HTML codes manually
• To modify the HTML codes behind the DataGrid control, switch to
code
view.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1435
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Grid Control-Displaying Data

<ASP:DataGrid id="MyDataGrid" runat="server"


Width="700px"
CellPadding=4
Font-Name="Verdana"
Font-Size="8pt"
HeaderStyle-BackColor="#aaaadd"
EnableViewState="False" Font-Names="Verdana" ForeColor="#333333" GridLines="None"
>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditItemStyle BackColor="#2461BF" />
<SelectedItemStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<AlternatingItemStyle BackColor="White" />
<ItemStyle BackColor="#EFF3FB" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
</ASP:DataGrid>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1436
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Grid Control-Displaying Data

SqlConnection myConnection = new


SqlConnection("server=p3c20014;database=pubs;user id =sa; pwd=sa");
SqlDataAdapter myCommand =
new SqlDataAdapter("select * from Authors", myConnection);

DataSet ds = new DataSet();


try {
myCommand.Fill(ds, "Authors");

MyDataGrid.DataSource=ds.Tables["Authors"].DefaultView;
MyDataGrid.DataBind();
}
catch (Exception ex){
throw (ex);
}
finally{
myConnection.Close();
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1437
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Grid Control-Parameterized
Select

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1438
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Grid Control-Parameterized Select

public void GetAuthors_Click(Object sender, EventArgs E)


{
String selectCmd = "select * from Authors where state = @State";
SqlConnection myConnection = new
SqlConnection("server=p3c20037;database=pubs;uid=sa;pwd=sa");
SqlDataAdapter myCommand = new SqlDataAdapter(selectCmd, myConnection);
myCommand.SelectCommand.Parameters.Add(new SqlParameter("@State", SqlDbType.NVarChar, 2));
myCommand.SelectCommand.Parameters["@State"].Value = MySelect.Value;
DataSet ds = new DataSet();
try {
myCommand.Fill(ds, "Authors");
MyDataGrid.DataSource= ds.Tables["Authors"].DefaultView;
MyDataGrid.DataBind();
}
catch (Exception ex){ throw (ex);
}
finally{ myConnection.Close(); }
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1439
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Grid Control-Edit/Update/Cancel

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1440
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Grid Control-Edit/Update/Cancel

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1441
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Grid Control-Edit/Update/Cancel

protected void MyDataGrid_Edit(Object sender,


DataGridCommandEventArgs e)
{
MyDataGrid.EditItemIndex = (int)e.Item.ItemIndex;
BindGrid();
}

protected void MyDataGrid_Cancel(Object sender, m


DataGridCommandEventArgs e)
{
MyDataGrid.EditItemIndex = -1;
BindGrid();
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1442
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Grid Control-Edit/Update/Cancel

protected void BindGrid()


{
SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors",
myConnection);
DataSet ds = new DataSet();
myCommand.Fill(ds, "Authors");
MyDataGrid.DataSource=ds.Tables["Authors"].DefaultView;
MyDataGrid.DataBind();
}
protected void Page_Load(object sender, System.EventArgs e)
{
myConnection = new
SqlConnection("server=p3c20037;database=Roy;uid=sa;pwd=sa");

if (!IsPostBack)
BindGrid();
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1443
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Grid Control-Edit/Update/Cancel

String updateCmd = "UPDATE Authors SET au_id = @Id, au_lname = @LName,


au_fname = @FName, phone = @Phone, "+ "address = @Address, city = @City,
state = @State, zip = @Zip, contract = @Contract where au_id = @Id";
SqlCommand myCommand = new SqlCommand(updateCmd, myConnection);
myCommand.Parameters.Add(new SqlParameter("@Id",
SqlDbType.NVarChar, 11));
myCommand.Parameters.Add(new SqlParameter("@LName", SqlDbType.NVarChar, 40));
myCommand.Parameters.Add(new SqlParameter("@FName", SqlDbType.NVarChar, 20));
myCommand.Parameters.Add(new SqlParameter("@Phone", SqlDbType.NChar, 12));
myCommand.Parameters.Add(new SqlParameter("@Address", SqlDbType.NVarChar, 40));
myCommand.Parameters.Add(new SqlParameter("@City", SqlDbType.NVarChar, 20));
myCommand.Parameters.Add(new SqlParameter("@State", SqlDbType.NChar, 2));
myCommand.Parameters.Add(new SqlParameter("@Zip", SqlDbType.NChar, 5));
myCommand.Parameters.Add(new SqlParameter("@Contract", SqlDbType.NVarChar,1));
myCommand.Parameters["@Id"].Value = MyDataGrid.DataKeys[(int)e.Item.ItemIndex];

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1444
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Grid Control-Edit/Update/Cancel

String[] cols =
{"@Id","@LName","@FName","@Phone","@Address","@City","@State","@Zip","@Cont
ract"};
Message.InnerHtml = "";
int numCols = e.Item.Cells.Count;
for (int i=2; i<numCols-1; i++) and last column
{
String colvalue =((System.Web.UI.WebControls.TextBox)
e.Item.Cells[i].Controls[0]).Text;
myCommand.Parameters[cols[i-1]].Value = colvalue;
}
if (String.Compare(((TextBox)e.Item.Cells[numCols-1].Controls[0]).Text,
"true", true, CultureInfo.InvariantCulture)==0)
myCommand.Parameters["@Contract"].Value = "1";
else
myCommand.Parameters["@Contract"].Value = "0";

myCommand.Connection.Open();

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1445
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Grid Control-Edit/Update/Cancel

try
{
myCommand.ExecuteNonQuery();
Message.InnerHtml = "<b>Record Updated</b><br>";
MyDataGrid.EditItemIndex = -1;
}
catch (SqlException exc)
{
if (exc.Number == 2627)
Response.Write("ERROR: A record already exists with the same
primary key");
else
Response.Write("ERROR: Could not update record, please
ensure the fields are correctly filled out");
}
myCommand.Connection.Close();
BindGrid(); }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1446
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Grid Control-Mapping Events

IfIfauto
autoevent
eventwireup
wireupisisset
settotofalse
false--
Map
Mapthe
therespective
respectiveevents.
events.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1447
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data Grid Control-Template Columns

You can add


controls to Item
and Edit item
template

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1448
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET GridView Control

GridView

The ASP.NET GridView control is the successor to the v1.x


DataGrid, adding the ability to take advantage of specific
capabilities of ASP.NET data source controls.
The GridView offers
• Functionality improvements over the DataGrid, such as
• The ability to define multiple primary key fields,
• New field types and templating options.
• Exposes a new model for page developers to handle or cancel
events.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1449
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
GridView Control
• Enhanced DataGrid control

 Renders sets of records as HTML tables

• Built-in sorting, paging, selecting, updating, and deleting support

• Supports rich assortment of field types, including CheckBoxFields

 Declared in <Columns> element

• Highly customizable UI

<asp:GridView
<asp:GridView DataSourceID="Employees"
DataSourceID="Employees" Width="100%"
Width="100%"
RunAt="server" />
RunAt="server" />

<asp:SqlDataSource ID="Employees" RunAt="server“


ConnectionString= "Provider=SQLOLEDB;Data
Source=localhost;Password=sa;User ID=sa;Initial
Catalog=Northwind“ SelectCommand="SELECT * FROM Employee"
./>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1450
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
GridView Control-Field Types

Name Description

BoundField Renders columns of text from fields in data source

ButtonField Renders columns of buttons (push button, image, or link)

CheckBoxField Renders Booleans as check boxes

CommandField Renders controls for selecting and editing GridView data

HyperLinkField Renders columns of hyperlinks

ImageField Renders columns of images from URL text

TemplateField Renders columns using HTML templates

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1451
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
GridView Control-Displaying Fields

Displaying Fields with a GridView


<asp:GridView DataSourceID="ProductsSource" AutoGenerateColumns="false"
Runat="Server">
<Columns>
<asp:BoundField HeaderText="Last Name"
DataField="LastName"
NullDisplayText="no value" />
<asp:BoundField HeaderText="First Name"
DataField="FirstName"
NullDisplayText="no value" /></Columns>
</asp:GridView>
<asp:SqlDataSource ID="ProductsSource"
ConnectionString= "Provider=SQLOLEDB;Data
Source=localhost;Password=sa;User ID=sa;Initial Catalog=Northwind“
SelectCommand="SELECT * FROM Employees" Runat="Server" />

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1452
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
GridView Control-Displaying Fields

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1453
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
GridView Control -Sorting and Paging
Sorting and Paging Records with the GridView Control
• When the GridView control's AllowSorting property has the value
true- sort the columns in a GridView by clicking the header
columns.
• When the AllowPaging property has the value true- page through
sets of records in a GridView

<asp:GridView
<asp:GridView DataSourceID="TitlesSource"
DataSourceID="TitlesSource"
AllowSorting="true"
AllowSorting="true"
AllowPaging="true"
AllowPaging="true"
Runat="Server"
Runat="Server" />
/>
<asp:SqlDataSource
<asp:SqlDataSource ID="TitlesSource"
ID="TitlesSource"
ConnectionString= "Provider=SQLOLEDB;Data
ConnectionString= "Provider=SQLOLEDB;Data
Source=localhost;Password=sa;User
Source=localhost;Password=sa;User ID=sa;Initial
ID=sa;Initial
Catalog=Northwind“
Catalog=Northwind“ SelectCommand="SELECT
SelectCommand="SELECT ** FROM
FROM Titles"
Titles"
Runat="Server" />
Runat="Server" />

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1454
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
GridView Control -Sorting and Paging

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1455
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
GridView Control -Interfaces
The GridView control supports the following interfaces:
• NextPrevious—Displays a next and previous link.
• NextPreviousFirstLast—Displays a next and previous link and a
link to the first and last page.
• Numeric—Displays page number links.
• NumericFirstLast—Displays page number links and a link to
the first and last page.

<asp:GridView
<asp:GridView DataSourceID="TitlesSource"
DataSourceID="TitlesSource"
AllowPaging="true"
AllowPaging="true" PageSize="4"
PageSize="4" Runat="Server">
Runat="Server">
<PagerSettings Mode="NextPreviousFirstLast"
<PagerSettings Mode="NextPreviousFirstLast"
FirstPageImageUrl="First.gif"
FirstPageImageUrl="First.gif"
PreviousPageImageUrl="Prev.gif"
PreviousPageImageUrl="Prev.gif"
NextPageImageUrl="Next.gif"
NextPageImageUrl="Next.gif"
LastPageImageUrl="Last.gif"
LastPageImageUrl="Last.gif" />
/>
</asp:GridView>
</asp:GridView>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1456
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
GridView Control -Editing
Editing with the GridView Control
• Edit the data displayed by a GridView by setting the
AutoGenerateEditButton property.
• When the SqlDataSource control associated with the GridView has
its UpdateCommand property set to a valid SQL UPDATE command,
the database will be automatically updated.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1457
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
GridView Control -Editing

Editing
Editingwith
withthe
theGridView
GridViewControl
Control

<asp:GridView DataSourceID="ProductsSource"
AutoGenerateEditButton="true" DataKeyNames="ProductID" Runat="Server" />
<asp:SqlDataSource ID="ProductsSource"
ConnectionString= "Provider=SQLOLEDB;Data
Source=localhost;Password=sa;User ID=sa;Initial Catalog=Northwind“
SelectCommand= "SELECT ProductID,ProductName,Discontinued FROM Products"
UpdateCommand="Update Products SET
ProductName=@ProductName,Discontinued=@Discontinued
WHERE ProductID=@ProductID"
Runat="Server" />

The
TheGridViewUpdated
GridViewUpdatedmethod
methodexecutes
executeswhenever
wheneveraaGridView
GridViewrow
rowisisfinished
finishedbeing
beingupdated
updated

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1458
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
GridView Control -Editing

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1459
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Data List Control

DataList

The DataList control displays a template-defined data


bound list.
• The DataList control supports selecting and editing.
• The contents of the DataList control can be manipulated by using
templates

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1460
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data List Control Templates
Template Name Description
AlternatingItemTe If defined, provides the content and layout for
mplate alternating items in the DataList. If not defined,
ItemTemplate is used.
EditItemTemplate If defined, provides the content and layout for the
item currently being edited in the DataList. If not
defined, ItemTemplate is used.
FooterTemplate If defined, provides the content and layout for the
footer section of the DataList. If not defined, a
footer section will not be displayed.
HeaderTemplate If defined, provides the content and layout for the
header section of the DataList. If not defined, a
header section will not be displayed.
ItemTemplate Required template that provides the content and
layout for items in the DataList.
SelectedItemTemp If defined, provides the content and layout for the
late currently selected item in the DataList. If not
defined, ItemTemplate is used.
SeparatorTemplat If defined, provides the content and layout for the
e separator between items in the DataList. If not
defined, a separator will not be displayed.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1461
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data List Control Styles
Style Property Description
AlternatingIte Specifies the style for alternating items in
mStyle the DataList control.

EditItemStyle Specifies the style for the item being


edited in the DataList control.

FooterStyle Specifies the style for the footer in the


DataList control.
HeaderStyle Specifies the style for the header in the
DataList control.
ItemStyle Specifies the style for the items in the
DataList control.
SelectedItemS Specifies the style for the selected item in
tyle the DataList control.

SeparatorStyle Specifies the style for the separator


between the items in the DataList control

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1462
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data List Control Properties

The properties that control which parts are shown or hidden.

Property Description
ShowFooter Shows or hides the footer section of the
DataList control.

ShowHeader Shows or hides the header section of the


DataList control.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1463
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data List Control-Displaying Content

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1464
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data List Control-Displaying Content

<asp:DataList id="ItemsList"
BorderColor="black“
CellPadding="5“ CellSpacing="5"
RepeatDirection="Vertical" RepeatLayout="Table"
RepeatColumns="3“ runat="server">
<HeaderStyle BackColor="#aaaadd">
</HeaderStyle>
<AlternatingItemStyle BackColor="Gainsboro">
</AlternatingItemStyle>
<HeaderTemplate> List of items
</HeaderTemplate>
<ItemTemplate>
Description: <br />
<%# DataBinder.Eval(Container.DataItem, "StringValue") %>
<br />
Price: <%# DataBinder.Eval(Container.DataItem,
"CurrencyValue", "{0:c}") %>
<br />
</ItemTemplate>
</asp:DataList>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1465
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data List Control-Displaying Content

protected void Page_Load(object sender, EventArgs e)


{ if (!IsPostBack)
{ ItemsList.DataSource = CreateDataSource();
ItemsList.DataBind();
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1466
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Data List Control-Displaying Content

public DataView CreateDataSource()


{ DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
dt.Columns.Add(new DataColumn("StringValue", typeof(String)));
dt.Columns.Add(new DataColumn("CurrencyValue",
typeof(double)));
for (int i = 0; i < 9; i++)
{ dr = dt.NewRow();
dr[0] = i;
dr[1] = "Description for item " + i.ToString();
dr[2] = 1.23 * (i + 1);
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
return dv;
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1467
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET DetailsView Control

DetailsView

Renders individual records


• Pair with GridView for master-detail views
• Or use without GridView to display individual records
Built-in paging, inserting, updating, deleting
Uses same field types as GridView
• Declared in <Fields> element
Highly customizable UI

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1468
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DetailsView Control
DetailsView is a data-bound user interface control that renders a single
record at a time from its associated data source, optionally providing
paging buttons to navigate between records.

It is similar to the Form View of an Access database, and is typically


used for updating and/or inserting new records.

It is often used in a master-details scenario where the selected record


of the master control (GridView, for example) determines the
DetailsView display record.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1469
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DetailsView Control
Displaying Database Records with the DetailsView Control
• The simplest thing to do with the DetailsView control is to display a
single database record.
• The DetailsView control automatically displays labels and values for
every column selected.
<asp:DetailsView
<asp:DetailsView DataSourceID="AuthorsSource"
DataSourceID="AuthorsSource"
Runat="Server"
Runat="Server" /> <asp:SqlDataSource
/> <asp:SqlDataSource ID="AuthorsSource"
ID="AuthorsSource"
ConnectionString= "Provider=SQLOLEDB;Data
ConnectionString= "Provider=SQLOLEDB;Data
Source=localhost;Password=sa;User
Source=localhost;Password=sa;User ID=sa;Initial
ID=sa;Initial
Catalog=Northwind“
Catalog=Northwind“
SelectCommand=
SelectCommand= "SELECT
"SELECT ** FROM
FROM Authors
Authors WHERE
WHERE au_id='172-32-
au_id='172-32-
1176'" Runat="Server" />
1176'" Runat="Server" />

• By default, the DetailsView control renders page numbers for


navigating through the records

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1470
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DetailsView Control-Listing Fields
Explicitly Listing Fields with the DetailsView Control
• To explicitly list the fields
that the control must display
set the control's AutoGenerateRows
property to false and adding
a <Fields> tag.

<asp:DetailsView
<asp:DetailsView ID="DetailsView1"
ID="DetailsView1"
DataSourceID="AuthorsSource"
DataSourceID="AuthorsSource" AutoGenerateRows="false"
AutoGenerateRows="false"
Runat="Server">
Runat="Server">
<Fields>
<Fields>
<asp:BoundField
<asp:BoundField DataField="au_id"
DataField="au_id" HeaderText="SS#:"
HeaderText="SS#:"
ReadOnly="true"
ReadOnly="true" /> <asp:BoundField DataField="au_lname"
/> <asp:BoundField DataField="au_lname"
HeaderText="Last Name:" /> <asp:BoundField
HeaderText="Last Name:" /> <asp:BoundField
DataField="au_fname"
DataField="au_fname" HeaderText="Last
HeaderText="Last Name:"
Name:" />
/>
</Fields>
</Fields> </asp:DetailsView>
</asp:DetailsView>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1471
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DetailsView Control-Editing Records
Editing Database Records with the DetailsView Control

• The AutoGenerateEditButton, AutoGenerateDeleteButton, and


AutoGenerateInsertButton properties are used to create the user
interface for editing records.
• When using the DetailsView control for editing, an
UpdateCommand, InsertCommand, and DeleteCommand must be
supplied for the DataSource control associated with the
DetailsView.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1472
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DetailsView Control-Editing Records

Editing Database Records with the DetailsView Control

<asp:DetailsView DataSourceID="AuthorsSource"
AllowPaging="true"
AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true"
AutoGenerateInsertButton="true"
DataKeyNames="au_id" Runat="Server" />

<asp:SqlDataSource ID="AuthorsSource" ConnectionString=


"Provider=SQLOLEDB;Data Source=localhost;Password=sa;User ID=sa;Initial
Catalog=Northwind“
SelectCommand= "SELECT au_id,au_lname,au_fname,contract FROM Authors"
UpdateCommand= "UPDATE Authors SET au_lname=@au_lname,
au_fname=@au_fname, contract=@contract WHERE au_id=@au_id"
DeleteCommand="DELETE Authors WHERE au_id=@au_id"
InsertCommand= "INSERT Authors (au_id,au_lname,au_fname,contract)
VALUES (@au_id,@au_lname,@au_fname,@contract)" Runat="Server" />

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1473
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DetailsView Control -Master/Detail
Form
Creating a Master/Detail Form with the DetailsView Control
• GridView control to display a list of employees. When an
employee's name is clicked, the DetailsView control will display the
employee's last name, and first name

Details View

GridView

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1474
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DetailsView Control -Master/Detail
Form
Creating
CreatingaaMaster/Detail
Master/DetailForm
Formwith
withthe
theDetailsView
DetailsViewControl
Control

<asp:DetailsView DataSourceID="DetailsSource"
AutoGenerateRows="false"
CellPadding="5"
FieldHeaderStyle-Font-Bold="true"
FieldHeaderStyle-HorizontalAlign="Right"
Runat="Server">
<Fields>
<asp:BoundField DataField="LastName" HeaderText="Last Name:" />
<asp:BoundField DataField="FirstName" HeaderText="First Name:" />
<asp:BoundField DataField="Extension" HeaderText="Extension:" />
</Fields> </asp:DetailsView>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1475
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DetailsView Control -Master/Detail
Form
Creating
CreatingaaMaster/Detail
Master/DetailForm
Formwith
withthe
theDetailsView
DetailsViewControl
Control

<asp:GridView ID="MasterGridView" DataSourceID="MasterSource"


AutoGenerateColumns="false"
DataKeyNames="EmployeeID"
CellPadding="5"
SelectedRowStyle-BackColor="#eeeeee"
Runat="Server">
<Columns>
<asp:TemplateField HeaderText="Employee">
<ItemTemplate>
<asp:LinkButton CommandName="Select" Runat="Server">
<%# Eval("LastName") %>, <%# Eval("FirstName") %>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1476
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DetailsView Control -Master/Detail
Form
Creating
CreatingaaMaster/Detail
Master/DetailForm
Formwith
withthe
theDetailsView
DetailsViewControl
Control

<asp:SqlDataSource ID="MasterSource"
EnableCaching="true" CacheDuration="600"
ConnectionString=
"Server=localhost;database=Northwind;Trusted_Connection=true"
SelectCommand="SELECT * FROM Employees" Runat="Server" />
<asp:SqlDataSource ID="DetailsSource"
EnableCaching="true" CacheDuration="600"
ConnectionString= "Provider=SQLOLEDB;Data
Source=localhost;Password=sa;User ID=sa;Initial Catalog=Northwind“
SelectCommand="SELECT * FROM Employees"
FilterExpression="EmployeeID=@EmployeeID" Runat="Server">
<FilterParameters>
<asp:ControlParameter Name="EmployeeID" ControlID="MasterGridView"
PropertyName="SelectedValue" />
</FilterParameters>
</asp:SqlDataSource>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1477
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DetailsView Control -Master/Detail Form

Creating a Master/Detail Form with the DetailsView Control


The GridView control contains a single TemplateField.
• The TemplateField displays the employee's first and last name with
a LinkButton control.
• The LinkButton control's CommandName property is set to the
value Select.
• When the LinkButton is clicked, the selected row is formatted with
the value of the SelectedRowStyle property.
• The DetailsView control displays information on the employee
currently selected in the GridView.
• The correct employee is selected by the FilterParameter defined in
the SqlDataSource that is associated with the DetailsView control.
• One SqlDataSource is associated with the GridView control, and the
other SqlDataSource is associated with the DetailsView control.
• Both SqlDataSource controls have the same SELECT command
declared for their SelectCommand property.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1478
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET FormView Control

FormView

The FormView control is used to display a single record from a


data source. It displays user-defined templates instead of row
fields.
The FormView control supports the following features:
• Binding to data source controls, such as SqlDataSource and
ObjectDataSource.
• Built-in inserting capabilities.
• Built-in updating and deleting capabilities.
• Built-in paging capabilities.
• Programmatic access to the FormView object model to dynamically
set properties, handle events.
• Customizable appearance through user-defined templates, themes,
and styles.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1479
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FormView Control Templates
Template type Description
EditItemTempl Defines the content for the data row
ate when the FormView control is in edit
mode. This template usually contains
input controls and command buttons
with which the user can edit an existing
record.
EmptyDataTem Defines the content for the empty data
plate row displayed when the FormView
control is bound to a data source that
does not contain any records. This
template usually contains content to
alert the user that the data source does
not contain any records.
FooterTemplate Defines the content for the footer row.
This template usually contains any
additional content you would like to
display in the footer row.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1480
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FormView Control Templates
Template type Description
HeaderTemplat Defines the content for the header row.
e This template usually contains any
additional content you would like to
display in the header row.
ItemTemplate Defines the content for the data row
when the FormView control is in read-
only mode. This template usually
contains content to display the values of
an existing record.
InsertItemTem Defines the content for the data row
plate when the FormView control is in insert
mode. This template usually contains
input controls and command buttons
with which the user can add a new
record.
PagerTemplate Defines the content for the pager row
displayed when the paging feature is
enabled (when the AllowPaging property
is inset
Duplication, reproduction or disclosure of information to true).
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
this document without the expressed written permission of Keane is prohibited.
1481
FormView Control –Binding to Data
Binding to Data
• The FormView control can be bound to a data source control (such
as SqlDataSource, AccessDataSource, ObjectDataSource and so
on), or to any data source that implements the
System.Collections.IEnumerable interface
• The FormView control can take advantage of the data source
control's capabilities and provide automatic updating, deleting,
inserting, and paging functionality.
• The FormView control recognizes certain buttons that have their
CommandName properties set to specific values to generate
command buttons to perform updating, deleting, or inserting
operations
 Include these command buttons in the appropriate template
• The FormView control provides a paging feature, which allows the
user to navigate to other records in the data source.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1482
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FormView Control User Interface

Style
property Description
EditRowStyle The style settings for the data row when the
FormView control is in edit mode.
EmptyDataRow The style settings for the empty data row
Style displayed in the FormView control when the
data source does not contain any records.
FooterStyle The style settings for the footer row of the
FormView control.
HeaderStyle The style settings for the header row of the
FormView control.
InsertRowStyle The style settings for the data row when the
FormView control is in insert mode.
PagerStyle The style settings for the pager row displayed in
the FormView control when the paging feature
is enabled.
RowStyle The style settings for the data row when the
FormView control is in read-only mode.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1483
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FormView Control- Events

Event Description
ItemComma Occurs when a button within a FormView control
nd is clicked. This event is often used to perform a
task when a button is clicked in the control.
ItemCreated Occurs after all FormViewRow objects are created
in the FormView control. This event is often used
to modify the values of a record before it is
displayed.
ItemDeleted Occurs when a Delete button (a button with its
CommandName property set to "Delete") is
clicked, but after the FormView control deletes
the record from the data source. This event is
often used to check the results of the delete
operation.
ItemDeletin Occurs when a Delete button is clicked, but before
g the FormView control deletes the record from
the data source. This event is often used to cancel
the delete operation.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1484
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FormView Control- Events

Event Description
ItemInserte Occurs when an Insert button (a button with its
d CommandName property set to "Insert") is
clicked, but after the FormView control inserts the
record. This event is often used to check the
results of the insert operation.
ItemInsertin Occurs when an Insert button is clicked, but before
g the FormView control inserts the record. This
event is often used to cancel the insert operation.

ItemUpdate Occurs when an Update button (a button with its


d CommandName property set to "Update") is
clicked, but after the FormView control updates
the row. This event is often used to check the
results of the update operation.
ItemUpdatin Occurs when an Update button is clicked, but
g before the FormView control updates the record.
This event is often used to cancel the update
operation.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1485
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FormView Control- Events

Event Description
ModeChanged Occurs after the FormView control changes
modes (to edit, insert, or read-only mode).
This event is often used to perform a task
when the FormView control changes modes.
ModeChanging Occurs before the FormView control changes
modes (to edit, insert, or read-only mode).
This event is often used to cancel a mode
change.
PageIndexChan Occurs when one of the pager buttons is
ged clicked, but after the FormView control
handles the paging operation. This event is
commonly used when you need to perform a
task after the user navigates to a different
record in the control.
PageIndexChan Occurs when one of the pager buttons is
ging clicked, but before the FormView control
handles the paging operation.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1486
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FormView Control

<asp:formview id="EmployeeFormView" datasourceid="EmployeeSource"


allowpaging="true"
datakeynames="EmployeeID"
runat="server">
<itemtemplate>
<asp:image id="EmployeeImage" imageurl='<%# Eval("PhotoPath") %>'
alternatetext='<%# Eval("LastName") %>' runat="server"/>
<h3>
<%# Eval("FirstName") %>
<%# Eval("LastName") %>
</h3>
<%# Eval("Title") %>
</itemtemplate>
<pagersettings position="Bottom" mode="NextPrevious"/>
</asp:formview>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1487
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FormView Control

<asp:sqldatasource id="EmployeeSource"
selectcommand="Select [EmployeeID], [LastName], [FirstName], [Title],
[PhotoPath] From [Employees]"
ConnectionString= "Provider=SQLOLEDB;Data
Source=localhost;Password=sa;User ID=sa;Initial Catalog=Northwind“
runat="server"/>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1488
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Repeater Control

Repeater

The Repeater control is a basic templated data-bound list.


• It has no built-in layout or styles, so you must explicitly declare all
layout, formatting, and style tags within the control's templates.
• The Repeater control is the only Web control that allows you to split
markup tags across the templates
• The Repeater control has no built-in selection capabilities or editing
support

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1489
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Repeater Control
• A Repeater control binds its ItemTemplate and
AlternatingItemTemplate to either the data model declared
and referenced by its DataSource property or the data
source control specified by its DataSourceID property.
 The HeaderTemplate, FooterTemplate, and SeparatorTemplate
are not data-bound.
 If the Repeater control's data source is set but no data is
returned, the control renders the HeaderTemplate and
FooterTemplate with no items.
 If the data source is a null reference (Nothing in Visual Basic),
the Repeater is not rendered.
 At a minimum, every Repeater control must define an
ItemTemplate

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1490
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Repeater Control

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1491
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Repeater Control

<asp:repeater id="Repeater1" datasourceid="SqlDataSource1“


runat="server">
<headertemplate>
<table border="1">
<tr>
<td><b>Product ID</b></td>
<td><b>Product Name</b></td>
</tr>
</headertemplate>
<itemtemplate>
<tr><td> <%# Eval("ProductID") %> </td><td> <%#
Eval("ProductName") %> </td></tr></itemtemplate>
<footertemplate> </table> </footertemplate>
</asp:repeater>
<asp:sqldatasource id="SqlDataSource1"
connectionstring="Provider=SQLOLEDB;Data
Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind"
selectcommand="SELECT ProductID, ProductName FROM [Products]
Where ProductID <= 10“ runat="server"
ProviderName="System.Data.OleDb">
</asp:sqldatasource>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1492
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Application Management

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Web Application
Management
• State Management
 Client Side state Management
 Server Side state Management
• Caching Techniques
 OutputCaching
 FragmentCaching
 DataCaching
 PostCacheSubstitution
• Tracing and Logging
• Exception Handing
 ErrorPages
 CustomExceptions

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1494
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET State Management

State Management

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1495
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET State Management

“The
“TheWeb
Webisisinherently
inherentlystateless;
stateless;each
eachrequest
requestfor
foraapage
page
isistreated
treatedas
asaanew
newrequest,
request,and
andinformation
informationfrom
fromone
onerequest
requestisisnot
not
available
availableby
bydefault
defaulttotothe
thenext
nextrequest”
request”
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1496
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
State Management Server side vs.
Client side

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1497
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
State Management-Architecture

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1498
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Client Side State
Management

View State
View State

Control State
Control State

Client Side
State Management
Query String
Query String

Hidden Field
Hidden Field

Cookies
Cookies

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1499
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Hidden Field

Hidden Fields
ASP.NET allows stores information in a HiddenField control, which
renders as a standard HTML hidden field.
• A hidden field does not render visibly in the browser, but its
properties can be set just as a standard control.
• When a page is submitted to the server, the content of a hidden
field is sent in the HTTP form collection along with the values of
other controls.
• A HiddenField control stores a single variable in its Value property
and must be explicitly added to the page.
• In order for hidden-field values to be available during page
processing, submit the page using an HTTP POST command

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1500
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET View State

View state
The ViewState property provides a dictionary object for retaining values
between multiple requests for the same page. This is the default method
that
the page uses to preserve page and control property values between round
trips.
• When the page is processed, the current state of the page and controls is
hashed into a string and saved in the page as a hidden field, or multiple
hidden fields if the amount of data stored in the ViewState property
exceeds the specified value in the MaxPageStateFieldLength property.
• When the page is posted back to the server, the page parses the view-
state string at page initialization and restores property information in the
page.
• Any objects put into the ViewState must be marked Serializable. ViewState
serializes the objects with a special binary formatter called the
LosFormatter. LOS stands for limited object serialization. It serializes any
kind of object, but it is optimized to contain strings, arrays, and
hashtables.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1501
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
View State

<asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>


<asp:Button ID="Button1" Runat="server" Text="Button" />
<asp:HiddenField ID="HiddenField1" Runat="server" />

[Serializable]
public class Person
{
public string firstName;
public string lastName;
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1502
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
View State

public partial class _Default : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
HiddenField1.Value = "foo";
ViewState["AnotherHiddenValue"] = "bar";
Person p = new Person();
p.firstName = "Scott";
p.lastName = "Hanselman";
ViewState["HiddenPerson"] = p;
}
} }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1503
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Control State

Control state

The ControlState property allows you to persist property


information that is specific to a control and cannot be turned
off like the ViewState property.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1504
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Cookies

Cookies
A cookie is a small amount of data that is stored either in a text
file on the client file system or in-memory in the client browser
session.
• It contains site-specific information that the server sends to the
client along with page output. Cookies can be temporary (with
specific expiration times and dates) or persistent.
• Cookies can store information about a particular client, session, or
application.
• The cookies are saved on the client device, and when the browser
requests a page, the client sends the information in the cookie
along with the request information. The server can read the cookie
and extract its value.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1505
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Cookies-Limitations
Limitations:
Despite being a useful tool in identifying users across web requests, cookies
also have certain limitations.
• Most browsers support cookies of up to 4096 bytes. Because of this
small limit, cookies are best used to store small amounts of data, or
better yet, an identifier such as a user ID. The user ID can then be
used to identify the user and read user information from a database or
other data store.
• Browsers also impose limitations on how many cookies your site can
store on the user's computer. Most browsers allow only 20 cookies per
site
• Some browsers also put an absolute limit, usually 300, on the number
of cookies they will accept from all sites combined.
• A cookie limitation that users can set their browser to refuse cookies. If
a P3P privacy policy is defined and placed in the root of the Web site,
more browsers will accept cookies from the site.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1506
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Cookies
• The browser is responsible for managing cookies on a user system.
• Cookies are sent to the browser via the HttpResponse object that exposes a
collection called Cookies .
• Cookies can be created by instantiating the HttpCookie class.Collection of
cookies belong to the HttpCookieCollection class.
• When creating a cookie,specify a Name and Value.
• Each cookie must have a unique name so that it can be identified later when
reading it from the browser.
• Since cookies are stored by name, naming two cookies the same will cause
one to be overwritten.
• Also set a cookie's date and time expiration. Expired cookies are deleted by
the browser when a user visits the site that wrote the cookies.
• If cookie's expiration is not set, the cookie is created but it is not stored on
the user's hard disk. Instead, the cookie is maintained as part of the user's
session information. When the user closes the browser, the cookie is
discarded.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1507
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Writing Cookies
Writing Cookies:

Response.Cookies["userName"].Value
Response.Cookies["userName"].Value == “Peter";
“Peter";
Response.Cookies["userName"].Expires
Response.Cookies["userName"].Expires ==
DateTime.Now.AddDays(1);
DateTime.Now.AddDays(1);
HttpCookie
HttpCookie aCookie
aCookie == new
new HttpCookie(“OurCookie");
HttpCookie(“OurCookie");
aCookie.Value = DateTime.Now.ToString();
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires
aCookie.Expires == DateTime.Now.AddDays(10);
DateTime.Now.AddDays(10);
Response.Cookies.Add(aCookie);
Response.Cookies.Add(aCookie);

In the above example 2 cookies are created namely userName and OurCookie.
Cookies can be created either of the 2 ways. For the first Cookie the values are
added directly to the Collection. This is possible because Cookies derive from
specialized collection of type NameObjectCollectionBase.

For the second cookie, the code creates an instance of an object of type
HttpCookie, sets its properties, and then adds it to the Cookies collection via the
Add method. When you instantiate an HttpCookie object, you must pass the
cookie name as part of the constructor.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1508
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Cookies-Storing Multiple Values
Response.Cookies["userInfo"]["userName"]
Response.Cookies["userInfo"]["userName"] =“Peter";
=“Peter";
Response.Cookies["userInfo"]["lastVisit"]
Response.Cookies["userInfo"]["lastVisit"] ==
DateTime.Now.ToString();
DateTime.Now.ToString();
Response.Cookies["userInfo"].Expires
Response.Cookies["userInfo"].Expires ==
DateTime.Now.AddDays(10);
DateTime.Now.AddDays(10);
HttpCookie
HttpCookie aCookie
aCookie == new
new HttpCookie("userInfo");
HttpCookie("userInfo");
aCookie.Values["userName"]
aCookie.Values["userName"] == “Peter";
“Peter";
aCookie.Values["lastVisit"]
aCookie.Values["lastVisit"] = DateTime.Now.ToString();
= DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(10);
aCookie.Expires = DateTime.Now.AddDays(10);
Response.Cookies.Add(aCookie);
Response.Cookies.Add(aCookie);

More than one name-value pairs can be stored in a Cookie. Such name-value pairs in
a single cookie are referred to as subkeys. Reasons.
• First, it is convenient to put related or similar information into a single cookie.
• In addition, because all the information is in a single cookie, cookie attributes
such as expiration apply to all the information.
• A cookie with subkeys also helps you limit the size of cookie files on the client
.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1509
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Reading Cookies

if(Request.Cookies["userName"]
if(Request.Cookies["userName"] !=!= null)
null)
Label1.Text=Server.HtmlEncode(Request.Cookies["userName“]
Label1.Text=Server.HtmlEncode(Request.Cookies["userName“]
.Value;
.Value;
if(Request.Cookies["userName"]
if(Request.Cookies["userName"] !=!= null)
null)
{{ HttpCookie aCookie = Request.Cookies["userName"];
HttpCookie aCookie = Request.Cookies["userName"];
Label1.Text
Label1.Text == Server.HtmlEncode(aCookie.Value);
Server.HtmlEncode(aCookie.Value); }}

When a browser makes a request to the server, it sends the


cookies for that server along with the request.
• In the ASP.NET applications,read the cookies using the HttpRequest object,
which is available as the Request property of the Page class.
• Before trying to get the value of a cookie, make sure that the cookie exists;
if the cookie does not exist, a NullReferenceException exception is thrown.
• HtmlEncode method was called to encode the contents of a cookie before
displaying it in the page

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1510
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Query String

Query String
• A query string is information that is appended to the end of a page
URL .
• Query String is used to pass information from one web page to the
another. The part after the “?” in the page URL is the query string.
It contains the information to be transferred to another page in
name-value pairs for processing.
• A typical query string might look like the following example:
http://www.caritor.com/listwidgets.aspx?
category=basic&price=100
• However, some browsers and client devices impose a 2083-
character limit on the length of the URL.
• Information that is passed in a query string can be tampered with
by a malicious user. Do not rely on query strings to convey
important or sensitive data.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1511
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Query String
• Create a web form with a label and a TextBox. Change the label
text to Enter name.
• Add another label and change the id to lblMessage.
• Drag a button on the same form.
• In the button click event type the following

if
if (TextBox1.Text.Equals(""))
(TextBox1.Text.Equals(""))
{{
lblMessage.Text
lblMessage.Text == "Please
"Please enter
enter your
your name";
name";
}}
else
else
{{
Response.Redirect("Default3.aspx?name="
Response.Redirect("Default3.aspx?name=" ++
HttpUtility.UrlEncode(TextBox1.Text));
HttpUtility.UrlEncode(TextBox1.Text));
}}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1512
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Client Side State Management-Pros and
Cons

Client- Pros Cons


Side
Option
Cookie Simple Can be rejected by browser. Not
appropriate for large amounts of
data. Inappropriate for sensitive
data.
Hidden Simple for page- Not appropriate for large amounts
Field scoped data of data. Inappropriate for
sensitive data.
ViewStat Simple for page- Encoding of serialized object as
e scoped data binary Base64-encoded data adds
approximately 30 percent
overhead.
ControlSt Simple for page- Like ViewState, but used for
ate scoped control- controls that require ViewState
specific data even if the developer has turned it
off.
QueryStri Incredibly Comparatively complex. Can’t
ng (URL) simple hold a lot of information.
Inappropriate for sensitive data.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
Easily
Duplication, reproduction or disclosure of information in this document without themodified by
expressed written the ofend
permission Keane user.
is prohibited.
1513
ASP.NET Server Side State Management

Session State
Session State

Application State
Application State Server Side
State Management

Profiler Properties
Profiler Properties

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1514
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Application State

Application State
Application state is a data repository available to all classes in
an ASP.NET application.
• All web pages within a specific web application share the data
stored in the application state variables.
• Unlike session state, which is specific to a single user session,
application state applies to all users and sessions.
• Application state is a useful place to store small amounts of often-
used data that does not change from one user to another.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1515
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Application State-Considerations
Resources
• Although storing data in Application state variables is faster as
compared to storing data in database, storing large amount of data
in Application variables can fill up the server memory and cause the
application to slow down.
• Unless necessay, Application variables should not be created as
they are a memory overhead. Application variable created can be
destroyed by the following ways.
 Either the Web Application is closed or the server is shut down.
 Explicity by using the Application.Remove(),
Application.RemoveAll() or Application.RemoveAt() methods.
 By modifying the Global.asax file.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1516
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Application State-Considerations
Volatility
• Because application state is stored in server memory, it is lost whenever the
application is stopped or restarted.
• For example, if the Web.config file is changed, the application is restarted
and all application state is lost unless application state values have been
written to a non-volatile storage medium such as a database.
Scalability
• Application state is not shared among multiple servers serving the same
application, Web farm, or among multiple worker processes serving the
same application on the same server, as in a Web garden.
Concurrency
• Application state is free-threaded, which means that application state data
can be accessed simultaneously by many threads.
• To ensure that when to update application state data,do so in a thread-safe
manner by including built-in synchronization support.
• Use the Lock and UnLock methods to ensure data integrity by locking the
data for writing by only one source at a time.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1517
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Application State-Creation
• Application state is stored in an instance of the
HttpApplicationState class.
• Application variables can be created by prefixing the Application
keywordbefore the variable name.
Application[“UserName”]=“Peter”;
• To read values from the Application variables in the page load
event
protected
protected void
void Page_Load(object
Page_Load(object sender,
sender, EventArgs
EventArgs e)
e)
{{
Application["AppStartTime"]
Application["AppStartTime"] ==
System.Convert.ToString(System.DateTime.Now);
System.Convert.ToString(System.DateTime.Now);
if
if (Application["AppStartTime"]
(Application["AppStartTime"] !=!= null)
null)
{{
Response.Write("Server
Response.Write("Server start
start time
time is
is
+Application["AppStartTime"].ToString());
+Application["AppStartTime"].ToString());
}}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1518
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Application State-Concurrency
• Since Application state variables are accessible to all the users
accessing the application, there has to be an explicit
synchronization mechanism to restrict concurrent users from
updating the application variable.
• In the load event of the Web form

if
if (!Page.IsPostBack)
(!Page.IsPostBack)
{{ Application.Lock();
Application.Lock();
if(Application["AppCounter"]==null)
if(Application["AppCounter"]==null)
Application["AppCounter"]
Application["AppCounter"] == 0;
0;
Application["AppCounter"]
Application["AppCounter"]
=(int)Application["AppCounter"]
=(int)Application["AppCounter"] ++ 1;1;
Response.Write("Value
Response.Write("Value of
of Application
Application Counter
Counter is
is ""
++ Application["AppCounter"].ToString());
Application["AppCounter"].ToString());
Application.UnLock();
Application.UnLock();
}}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1519
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Session State

Session State

• ASP.NET session state identifies requests received from the same


browser during a limited period of time as a session, and provides
the ability to persist variable values for the duration of that session.
• Unlike the Application state, Session state is not specific to the
Application but to the browser session.
• Each user opening a new browser session is allocated a SessionID
which is stored in a 120 bit value stored in a cookie
ASPNET_SessionID. In cookieless session it is transmitted via the
URL.
• When the user closes the browser or logs out and re-returns
access the same application he might get a different SessionID.
• The SessionID can be accessed by the SessionID property of
Session object. Response.Write(Session.SessionID);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1520
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Session State Considerations
Session State Considerations
• Session variables can be created in a similar manner like
Application variables.

Session[“SesCounter”]
Session[“SesCounter”] == 0;
0;
Session["FirstName"] = FirstNameTextBox.Text;
Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"]
Session["LastName"] == LastNameTextBox.Text;
LastNameTextBox.Text;
• Session variables can be used to transfer values across multiple
pages of a Web application.
• The life of a session variable exists until
 The browser is closed thereby terminating the session.
 The value of session variable is set to 0 in Global.asax.
 Explicit method of the Session object is used such as
Session.Abandon() .
 The default time for a session i.e 20 minutes expires. This can
be modified in the web.config file.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1521
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Session State Identifiers
Session State Identifiers
• Sessions are identified by a unique session identifier that can be
read using the SessionID property.
• When session state is enabled for an ASP.NET application, each
request for a page in the application is examined for a SessionID
value sent from the browser.
• If no SessionID value is supplied, ASP.NET starts a new session
and the SessionID for that session is sent to the browser with the
response.
• The SessionID is stored in a non-expiring session cookie in the
browser by default.
• You can specify that session identifiers not be stored in a cookie by
setting the cookieless attribute to true in the sessionState section
of the Web.config file.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1522
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Session State Events and Modes
Session State Events and Modes
• ASP.NET provides two events in the Global.asax file that help you
manage user sessions: the Session_OnStart event, which is raised
when a new session begins, and the Session_OnEnd event, which is
raised when a session is abandoned or expires.
• ASP.NET session state supports several different storage options
for session data. Each option is identified by a value in the
SessionStateMode enumeration. The following list describes the
available session state modes in the web.config file:
 InProc mode, which stores session state in memory on the Web
server. This is the default.
 StateServer mode, which stores session state in a separate
process called the ASP.NET state service.
 SQLServer mode stores session state in a SQL Server database.
 Custom mode, which enables you to specify a custom storage
provider
 Off mode, which disables session state.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1523
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Session State

In the Application_Start
Application[“AppCtr]=0;
In the Session_Start type
Session[“SessCtr”]=0;
Session[“SessCtr”]=(int) Session[“SessCtr”]+1;
Application[“AppCtr”]=(int) Application[“AppCtr”]+1
In the Session_End type
Session[“SessCtr”]=(int) Session[“SessCtr”]-1;
Application[“AppCtr”]=(int) Application[“AppCtr”]-1
In the page load event type
Response.Write(“The Application counter value is
“+Application[“AppCtr”].toString();
Response.Write(“The Session counter value is
“+Session[“SessCtr”].toString();

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1524
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Server Side State Management-Pros and
Cons
Server- Pros Cons
Side
Option

Applicatio Fast. Shared among State is stored once per


n State all users. server in multiple server
configurations.
Cache Like the Application State is stored once per
Object but includes server in multiple server
(Applicati expiration via configurations.
on Scope) Dependencies
Session Three choices: in Can be abused.In process
State process, out of requires Web Server affinity.
process, DB-backed. Cookieless configuration
Can be configured as makes it easier to hijack.
cookieless.

Database State can be accessed Pay a serialization and


by any server in a persistence cost when
Web farm. objects leave the process.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1525
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Caching Techniques

Web Application Caching Techniques

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1526
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Caching Techniques

“Caching is a technique widely used in computing to


increase performance by keeping frequently accessed or
expensive data in memory. In the context of a Web
application, caching is used to retain pages or data
across HTTP requests and reuse them without the
expense of recreating them”

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1527
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Caching Techniques
Type Description

Output Caching Output caching is useful when the contents of


an entire page can be cached

Fragment Identify objects or data that are expensive to


Caching construct and are eligible for caching.
Fragment caching can be used to cache
regions of a page's output.
Data Caching the cache items can be given an expiration
policy that causes them to be removed from
the cache when they have expired. Code that
accesses the cache item simply checks for the
absence of the item and recreates it, if
necessary.

Cache Cache profiles are used to configure cache


Configuration profiles in the configuration system, and then
use those profiles on pages. This enables
changes to caching for sets of pages to be
made on a global basis.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1528
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Caching Techniques-Output Caching
Output Caching
Caches the static result of an ASP.NET page
• Declarative <%@ OutputCache %> directive
• Optional Output Cache APIs can also be called
Caching Options:
• Duration -Time item exists in the cache
• VaryByParam
 Varies cache entries by Get/Post params
 Name param, separate by semi-colons, supports *
• VaryByHeader
 Varies cache entries by Http header
• VaryByCustom
 Override method within Global.asax to custom vary by whatever
you want (you control the cache key)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1529
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Caching Techniques-Output Caching
Output Caching
 Location: This attribute is used to specify the location where the
data needs to be cached.This attribute can take one of the
following values.
 Client : It specifies the output cache to be located on the
client browser that set the request.
 Downstream: It specifies the output cache to be located on
the server downstream to the server where the request is
processed.
 Server: It specifies the output cache to be located on the
web server where the request is processed.
 Any : It specifies the output cache to be located on the
Client browser, the downstream server or the web server
where the request is processed.
 None : It specifies the output caching to be disabled for the
current page

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1530
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Caching Techniques-Output Caching
• Add a new Web form from the Project menu. Add a DataGrid to the
Web form.Add a label to the web form. Change its ID to
DisplayLabel.
• Add the following in the HTML view of the web form:
<%@ OutputCache Duration=“120” VaryByParam=“none”
%>
• Import the System.Data.SqlClient namespace to the application.
• Add the following in the load event of the web page.

String
String dsn
dsn ,sqlEmp;
,sqlEmp;
dsn=“server=localhost;uid=sa;pwd=sa;Database=pubs”;
dsn=“server=localhost;uid=sa;pwd=sa;Database=pubs”;
SqlConnection
SqlConnection objConn=new
objConn=new SqlConnection(dsn);
SqlConnection(dsn);
sqlEmp=“Select * from authors”;
sqlEmp=“Select * from authors”;
SqlDataAdapeter
SqlDataAdapeter objadap=new
objadap=new SqlDataAdapter(sqlEmp,objConn);
SqlDataAdapter(sqlEmp,objConn);
DataSet ds=new DataSet();
DataSet ds=new DataSet();
Objadap.Fill(ds);
Objadap.Fill(ds);
DataGrid1.DataSource=ds;
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
DataGrid1.DataBind();
DisplayLabel.Text=“Page
DisplayLabel.Text=“Page Cached
Cached at
at ::
“+System.DateTIme.Now.ToString();
“+System.DateTIme.Now.ToString();

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1531
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Caching Techniques-Fragment
Caching
Fragment Caching
The main features of fragment caching are:
• In this type of caching,data for only specific sections of the page is
cached.
• It can be implemented when you need to cache different portions
of a single web form for different durations or when you need to
cache only specific portions of the web form.
• Caching the entire page isn’t always possible
 Partial page personalization.
• Fragment Caching allows caching regions of a page by using user
controls (.ascx)
 User controls define <%@ OutputCache %> directive
• Additional Features
 VaryByControl – Varies cached items by controls
 VaryByCustom – Allows user cache key method

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1532
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Caching Techniques-Fragment Caching

To demonstrate the effect of fragment caching:


• A user controls needs to be created to display data from the
authors table. The control should display the order details and time
when the control was created.
• This user control needs to be displayed on a web page which does
not implements Output Caching. The page should display the time
when it was created.
To create a custom control , perform the following steps:
• Select Project > Add Web User Control from the menu bar. The Add new
Item dialog box is displayed.
• Enter the name of the control as MyCustomControl.ascx.
• Switch to the design mode and drag the DataGrid control on the web form.
Change the ID of DataGrid to AuthorGrid .
• Also drag a label and change its ID to DisplayLabel.
• In the HTML view of the user control, write the @OutputCache directive
<%@ OutputCache Duration=“180” VaryByParam=“none” %>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1533
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Caching Techniques-Fragment Caching

Import the System.Data.SqlClient namespace and add


the following code to the Page_Load event
string dsn, qrystr;
dsn=“server=localhost;user id=sa;pwd=sa;Initial Catalog=pubs”;
SqlConnection objSql=new SqlConnection(dsn);
qrystr=“Select * from authors”;
SqlDataAdapter sqladap=new SqlDataAdpater(qrystr,objSql);
DataSet dsAuthor=new DataSet();
Sqladap.Fill(dsAuthor);
AuthorGrid.DataSource=dsAuthor;
AuthorGrid.DataBind();
DisplayLabel.Text=“Control cached at ”+DateTime.Now.ToString();

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1534
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Caching Techniques-Fragment Caching

Create
Createaaweb
webform
formthat
thatwill
willdisplay
displaythe
theuser
usercontrol
controlcreated
created
Add
Add the following Text in the DisplayLabel in the loadevent
the following Text in the DisplayLabel in the load eventofofthe
theform
form

DisplayLabel.Text=“Page created at :”+DateTime.Now.ToString();

Since, we have used the OutputCache element to cache the data for
the user control when the page is refreshed the time of creation of the
control will be the same and will not be changed till 180 secs.
However,with each page refresh, the label on the web page shows the
changed timings since the page gets refreshed not from the cache.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1535
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Caching Techniques-Data Caching
Data Caching
The main features of Data Caching are
• Frequently accessed data is cached in server-side memory
variables.
• This type of caching is implemented programmatically.
• The Cache class encapsulates data caching.
• The Cache object stores each item as key/value pairs. E.g.
Cache[“unamekey”]=uname
• The lifetime of the Cache object is associated with an application.
• The cache object exists only while an application runs and the
Cache object is recreated when the application is restarted.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1536
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Caching Techniques-Data Caching
Add a DataGrid to a web form.Import the System.Data.SqlClient
namespace In the load event of the form write the code:
DataView AuthorSource;
AuthorSource=(DataView)Cache[“OrderSourceKey”];
if(AuthorSource==null)
{ string dsn=“server=localhost;uid=sa;pwd=sa;Database=pubs”;
SqlConnection objSConn=new SqlConnection(dsn);
string strcmd=“Select * from Authors”;
SqlDataAdapter objAda=new SqlDataAdapter(strcmd,objSConn);
DataSet dsauthor=new DataSet();
objAda.fill(dsauthor);
AuthorSource=new DataView(dsauthor.Tables[“Authors”]);
Cache[“OrderSourceKey”]=AuthorSource;
DisplayLabel.Text=“Data accessed from the database”;
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1537
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Caching Techniques-Data Caching

else
{
DisplayLabel.Text=“Data accessed from the cache”;
}
DataGrid1.DataSource=AuthorSource;
DataGrid1.DataBind();

In the given code, an object of DataView is created,which stores


the cache OrderSourceKey.Next a check is done to see whether the
cache object is null.If so,the records are retrieved from the
authors table and are stored in the dataset dsauthor and its cache
is stored in the variable AuthorSource.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1538
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Caching Techniques-Substitution Caching

A substitution involves writing a callback method in the code-


behind that returns HTML.
• Use Response.WriteSubstitution() method, then,
• In the form layout,the callback method is called for each request to
the page, even the rest of the page is being served from the output
cache. The HTML returned from the method is embedded into the
overall HTML for the page.
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Caching.aspx.cs" Inherits="Caching" %>
<%@ OutputCache Duration="5" VaryByParam="none" %>
<% Response.Write(DateTime.Now); %>
<% Response.WriteSubstitution(new
HttpResponseSubstitutionCallback(WriteCurrentTime)); %>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1539
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Caching Techniques-Substitution Caching

• Write a callback method called WriteCurrentTime.


 This method is added to your code-behind for the current
page, and must: return a string (i.e. the HTML) 
 Have one parameter of type HttpContext . Be static
protected static string WriteCurrentTime(HttpContext context)
{
   return DateTime.Now.ToString();
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1540
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Caching Techniques-Substitution Caching

• Alternatively to using WriteSubstitution in the page layout,


you can use the Substitution control to declaratively
perform the same thing:

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="Caching.aspx.cs" Inherits="Caching" %>
<%@ OutputCache Duration="5" VaryByParam="none" %>

<asp:Substitution MethodName="WriteCurrentTime" runat="server"


/>  

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1541
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Tracing

Web Application Tracing

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1542
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Tracing
“Tracing is a way to monitor the execution of your ASP.NET
application”
• It is often helpful to be able to insert debugging print statements into the
• code to output variables or structures, assert whether a condition is met, or
• just generally trace through the execution path of the application.
• ASP.NET provides two levels of tracing services
 Page-level Tracing
 Application-level Tracing
• There is a class called System.Diagnostics.Trace and there is also a public property on
System.Web.UI.Page called Trace. The Trace property on the Page class gives access
to the System.Web.TraceContext and the ASP.NET-specific tracing mechanism.
 The TraceContext class collects all the details and timing of a Web request. It
contains a number of methods,
 Trace. Write()
 Trace.Warn(), which simply calls Write(), and also ensures that the output
generated by Warn is colored red.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1543
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Tracing-Page level
Page-level Tracing:
• At the page level, developers can use the TraceContext intrinsic to
write custom debugging statements that appear at the end of the
client output delivered to the requesting browser.
• ASP.NET also inserts some helpful statements regarding the
start/end of lifecycle methods, like Init, Render, and PreRender, in
addition to the inputs and outputs to a page, such as form and
QueryString variables or headers, and important statistics about
the page's execution (control hierarchy, session state, and
application state).

• ASP.NET tracing can be enabled on a page-by-page basis by adding


Trace=”true” to the Page directive in any ASP.NET page:
<%@ Page Language="C#" Inherits="System.Web.UI.Page" Trace="true"
%>
TraceMode attribute that sets SortByCategory or the default,
SortByTime

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1544
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Tracing-Application Level
Application-level Tracing:
• Application-level tracing provides a view of several requests to an
application's pages at once.
• Application-level tracing is enabled through the ASP.NET
configuration system, and accessed as a special mapped URL into
that application (Trace.axd).
• When application tracing is enabled, page-level tracing is
automatically enabled for all pages in that application (provided
there is no page-level directive to explicitly disable trace).

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1545
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Tracing-Application Level
Application-level Tracing:
• Enable tracing for the entire application by adding tracing settings
in web.config.
 In the following example, pageOutput=”false” and
requestLimit=”20” are used, so trace information is stored for
20 requests, but not displayed on the page:
<configuration>
<system.web>
<trace enabled="true" pageOutput="false"
requestLimit="20" traceMode="SortByTime"
localOnly="true" />
</system.web>
</configuration>
• The page-level settings take precedence over settings in
web.config, so if enabled=”false” is set in web.config but
trace=”true” is set on the page, tracing occurs.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1546
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Tracing-Using Trace.Write()
Tracing can be viewed for multiple page requests at the application level
by requesting a special page (of sorts) called trace.axd.
• It is actually provided by System.Web.Handlers.TraceHandler, a
special IHttpHandler to which trace.axd is bound.
• When ASP.NET detects an HTTP Request for trace.axd, that request
is handled by the TraceHandler rather than by a page.
Tracing using Page.Trace
<configuration>
<system.web>
<trace enabled="true" pageOutput="true" />
</system.web>
</configuration>
protected void Page_Load(object sender, EventArgs e)
{
Trace.Write("This message is from the START of the Page_Load
method!");
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1547
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Tracing

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1548
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Tracing

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1549
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Tracing

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1550
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Trace Sections and Description

Section Description
Request Includes the ASP.NET Session ID, the character
Details encoding of the request and response, and the HTTP
conversation’s returned status code.

Trace Includes all the Trace.Write methods called during the


Informati life-time of the HTTP request and a great deal of
on information about timing. This is probably the most
useful section for debugging. The timing information
located here is valuable when profiling and searching
for methods in your application that take too long to
execute.
Control Presents an HTML representation of the ASP.NET
Tree Control Tree. Shows each control’s unique ID, runtime
type, the number of bytes it took to be rendered, and
the bytes it requires in View-State and
ControlState.The weight of the control indicates the
number of bytes occupied in ViewState and/or
ControlState by that particular Control.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1551
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Trace Sections and Description
Section Description

Session State Lists all the keys for a particular user’s session,
their types, and their values. Shows only the
current user’s Session State.
Application Lists all the keys in the current application’s
State Application object and their types and values.

Request Lists all the cookies passed in during the page’s


Cookies request.
Response Lists all the cookies that were passed back during
Cookies the page’s response.

Headers Shows all the headers that might be passed in


Collection during the request from the browser, including
Accept-Encoding, indicating whether the browser
supports compressed HTTP responses; Accept-
Languages, a list of ISO language codes that
indicate the order of the user’s language
preferences; and User-Agent, the identifying
string for the user’s browser.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1552
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Trace Sections and Description

Section Description

Form Displays a complete dump of the Form


Collection collection and all its keys and values.

Querystri Displays a dump of the Querystring collection


ng and all its contained keys and values.
Collection

Server A complete dump of name-value pairs of


Variables everything that the Web server knows about
the application and the requesting browser.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1553
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Trace Sections and Description

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1554
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Trace Attributes and Options
Attribute Options Description

Enabled true/false Specifies whether the tracing service


is enabled or disabled. The default
setting in machine.config is false.
localOnly true/false Specifies whether you can view trace
results
only from local host or remotely. The
default
is true.
pageOutp true/false Specifies whether trace results are
ut appended
to the end of a page or available only
through
the trace utility. The default is false.
requestLi Places a limit on the number of trace
mit requests to store on the server. The
default is 10.
traceMod SortByTime/ Specifies whether to sort the trace
e SortByCatego results by Time or Category. The
ry default is SortByTime.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1555
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Logging

Web Application Logging

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1556
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Logging
• ASP.NET writes messages to the event log in certain conditions in
which ASP.NET infrastructure encounters a fatal failure, such as
when it does not have access to required resources, or is unable to
create worker processes to host ASP.NET applications.

• The information in these events may be used to solve such


problems, especially when first deploying ASP.NET applications to
new machines where permission and installation issues may exist.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1557
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Debugging Techniques

Web Application Debugging

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1558
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Debugging Techniques
Design Time Support
• Syntax Notification
• Immediate and Command Window
• Task List
Exception Handing
• ErrorPages
• CustomExceptions

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1559
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
VS2005 Design Time Support for
Debugging
• Syntax Notification
 C# editors show squiggles and tooltips for many syntax errors
well before compilation
 XML Editor with enhancements like the following:
 Full XML 1.0 syntax checking
 Support for DTD as well as XSD validation
 Support for XSLT 1.0 syntax checking
• Immediate Window
 The Immediate Window enables to run arbitrary bits of code in
Design mode without compiling the application. It can be a
great way to test a line of code or a static method quickly.
 Access the Immediate Window from Debug Windows
Immediate. To evaluate a variable or run a method, simply click
in the Immediate Window and type a question mark (?)
followed by the expression, variable, or method you want to
evaluate

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1560
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
VS2005 Design Time Support for
Debugging
• Command Window
 The immediate window can also be switched into the Command
Window by prefacing commands with a greater-than sign (>).
When a greater-than sign in the Immediate/Command Window
is entered, an IntelliSense drop-down appears exposing the
complete Visual Studio object model as well as any macros that
have been recorded.
• Task List
 User Tasks view enables to add and modify tasks, which can
include anything from “Remember to Test” to “Buy Milk.” These
tasks are stored in the .SUO (solution user options) that is a
parallel partner to the .SLN files.
 The Comments view shows text from the comments in the code
where those lines are prefixed with a specific token. Visual
Studio comes configured to look for the TODO: token, but we
can add our own in Tools Options Environment Task List.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1561
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Error Pages
When an error occurs on a page, ASP.NET sends
information about the
error to the client. Errors are divided into four categories:
• Configuration errors: Occur when the syntax or structure of a
Web.config file in the configuration hierarchy is incorrect.
• Parser errors: Occur when the ASP.NET syntax on a page is
malformed.
• Compilation errors: Occur when statements in a page's target
language are incorrrect.
• Run-time errors: Occur during a page's execution, even though the
errors could not be detected at compile time.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1562
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Error Pages
• By default, errors are shown only to local clients (those clients on
the same computer as the server). To specify a custom error page
to redirect clients to if an error occurs.

• Custom errors are enabled in the Web.config file for an application.


For example:
<configuration>
<system.web>
<customErrors defaultRedirect="genericerror.htm"
mode="RemoteOnly" />
</system.web>
</configuration>
• Only files mapped to the aspnet_isapi.dll extension in IIS generate
these errors. Files not served through the aspnet_isapi.dll are not
processed by ASP.NET and generate IIS errors

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1563
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Error Pages
• Configuration attributes and values for the <customErrors> tag.
 mode Indicates whether custom errors are enabled, disabled,
or only shown to remote computers. Values: On, Off,
RemoteOnly (default).
 defaultRedirect Indicates the default URL to which a browser
should be redirected if an error occurs. This attribute is
optional.
• The Mode attribute determines whether errors are shown to local
clients, remote clients, or both. The effects of each setting are
described in the following table.
Mode Local host request Remote host request

On Custom error page. Custom error page.

Off ASP.NET error page. ASP.NET error page.

RemoteOnly ASP.NET error page. Custom error page.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1564
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Error Pages
• The <customErrors> configuration section supports an inner
<error> tag that associates HTTP status codes with custom error
pages
<configuration>
<system.web>
<customErrors mode="RemoteOnly"
defaultRedirect="/genericerror.htm">
<error statusCode="500" redirect="/error/callsupport.htm"/>
<error statusCode="404" redirect="/error/notfound.aspx"/>
<error statusCode="403" redirect="/error/noaccess.aspx"/>
</customErrors>
</system.web>
</configuration>
StatusCode HTTP status code of errors for which the custom error
page should be used. Examples: 403 Forbidden, 404 Not Found, or
500 Internal Server Error.
Redirect URL to which the client browser should be redirected if an
error occurs.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1565
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Error Pages

Handling
HandlingErrors
ErrorsatatPage
PageLevel
Level
public void Error_500(Object sender, EventArgs e)
{ String foo = null; Response.Write(foo.ToString());
}
public void Page_Error(Object sender, EventArgs e)
{ String message = "<font face=verdana color=red>" +
"<h4>" + Request.Url.ToString() +
"</h4>" + "<pre><font color='red'>" +
Server.GetLastError().ToString() + "</pre>" + "</font>";
Response.Write(message); Server.ClearError(); }

<asp:button
<asp:buttontext="500
text="500Server
ServerError"
Error"OnClick="Error_500"
OnClick="Error_500"width="150"
width="150"runat="server"/>
runat="server"/>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1566
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Error Pages

Handling
HandlingErrors
ErrorsatatApplication
ApplicationLevel
Level
Use the Application_Error event in Global.asax
void Application_Error(Object sender, EventArgs e)
{
//...Do something here
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1567
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web site Management

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Web site Management
• Web site Configuration
 Web Administration Tool
• Security
 Authentication
 Windows
 Forms
 Digest
 Authorization
 Allow/Roles/Verbs
• Health Monitoring
• Deployment

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1569
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Configuration

Configuration Management

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1570
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Configuration Tools & Files
ASP.NET 2.0 provides tools and APIs that enable
developers to
configure and manage ASP.NET 2.0–based applications
with reliability
and comfort.
Two powerful configuration tools are explored:
• The new ASP.NET Web Site Administration Tool, a Web-
based application
• The new MMC ASP.NET Snap-In, a plug-in configuration tab
for IIS.
Two configuration files are explored
• Machine.config
• Web.config

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1571
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Configuration Tool-Web
Administration Tool
The ASP.NET Web Site Administration Tool helps to manage
Web site
configuration through a simple, easy-to-use Web interface.
• It eliminates the need for manually editing the web.config file.
• If no web.config file exists when using the administration tool for
the first time, it creates one.
• The ASP.NET Web Site Administration Tool also creates the
standard ASPNETDB.MDF SQL Server Express Edition file in the
App_Data folder of the Web site to store application data.
• The changes made to most settings in the ASP.NET Web Site
Administration Tool take effect immediately.
• The default settings are automatically inherited from any
configuration files that exist in the root folder of a Web server.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1572
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Administration Tool
• The ASP.NET Web Site Administration Tool is automatically installed
during installation of the .NET Framework version 2.0.
• To use the administration tool to administer your own Web site,
you must be logged in as a registered user of the site and must
have read and write permissions to web.config.
• Access WAT with Visual Studio 2005, which, in turn, uses the new
built-in server (formally Cassini) to access the administration tool.
• In order to access this tool through Visual Studio 2005, click the
ASP.NET Configuration button found in the menu provided in the
Solution Explorer.
(or)
http://localhost/MyShop/Webadmin.axd

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1573
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Administration Tool

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1574
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Administration Tool

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1575
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Administration Tool-Security Tab

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1576
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Administration Tool-Security Tab

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1577
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Administration Tool-Security Tab

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1578
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Administration Tool-Security Tab

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1579
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Administration Tool-Security Tab

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1580
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Administration Tool-Application Tab

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1581
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Administration Tool-Application Tab

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1582
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Administration Tool-Provider Tab

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1583
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Administration Tool-Provider Tab

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1584
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Configuration File-Machine.config

machine.config :
• This is an XML based file is automatically installed with Visual
Studio.NET. The machine.config file is installed on the server in the
location

%windir%\ Microsoft.NET \ Framework \ v2.0\CONFIG


• The machine.config file is located at the highest level in the
configuration hierarchy

• Machine.config contains the default configuration settings for all the


applications hosted on the web server.

• This file is called the machine level configuration file.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1585
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Configuration File-Web.config

web.config
• This file is created in the Application’s root directory and contain
settings specific to a particular web application.

• This file contain settings specific to an application and therefore


called Application Level configuration file.

• On a single web server there exists as many as web.config files as


the No. of web applications hosted on it.

• The settings applied in the web.config file overrides the same


settings applied in the higher –level machine.config file

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1586
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Configuration File Tags
Configuration Description
Tag
<appSettings> Allows the configuration of Application custom
settings for your applications
<authentication Allows configuration of ASP.NET’s Security
> authentication support.
<authorization Allows configuration of ASP.NET’s Security
> authorization support.
<browserCaps> Allows configuration of settings for the browser
capabilities component.
<compilation> allows configuration of all ASP.NET compilation
settings.
<sessionState> Allows configuration of the System
session state HTTP module
<trace> Allows configuration of the ASP.NET Application
trace service.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1587
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Configuration File Tags

Configuration Description
Tag
<customErrors> Allows the definition of custom Errors for a
web application.
<compilation> Allows configuration of all ASP.NET
compilation settings.
<globalization> Allows the configuration of globalization
Settings for an application.
<pages> Allows configuration of page specific settings.
<securityPolicy Allows the mapping of defined security to
> policy files.
<trust> Allows configuration of the code Security
access security permission set used to run
your application.
<webServices> Allows configuration of ASP.NET System
Web Services settings.
<httpRuntime> Allows the configuration of HttpRuntime
Settings.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1588
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Configuration File Tags

Configuration Description
Tag
<forms> Specifies things such as the loginUrl, the
type of protection and the timeout of
inactivity.
<credentials specifies the username/password
> combinations .
The credentials tag also has an attribute
called passwordFormat. Password format
are: Clear|SHA1|MD5
<user> Contains name attribute for the username
and password attribute for the password.
.
<location> The location tag has one attribute, path,
which is the path to apply a different set of
security rules to

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1589
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Security

Web site Security

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1590
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Security

An
Animportant
importantaspect
aspectofofsecurity
securityisishow
howtotohandle
handlethe
the
authentication
authenticationand
andauthorization
authorizationfor
foraccessing
accessingapplication
application

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1591
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Security

44

IIS ASP.NET
(inetinfo.exe) (aspnet_wp.exe)
22 33 55 66
HTTP Requests

Authentication Authorization Authentication Authorization


Basic Web Permissions Windows File AuthZ
Digest NTFS Permissions Forms URL AuthZ
11 Integrated IP Restrictions Passport .NET Roles
Certificate None

77

Local or
Remote
Resource

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1592
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Security-Authentication
Authentication is the process that determines the
identity of the user.
• The different authentication modes are established
through settings that can be applied to the
applications web.config file or in conjunction with
the application server’s Internet Information
Provider Services
Description
(IIS) instance.
• The different authentication modes are as follows
Windows Used together with IIS authentication
Performed by IIS as: Basic,Digest or
Integrated Windows.(Default)

Forms Requested that are authenticated are


redirected to an HTML form using HTTP client-
side redirection

Passport A centralized authentication service provided


by Microsoft that offers single login and core
profile services for member sites

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1593
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Security-Windows Authentication

The Windows-Based Authentication is handled between the


windows server where the ASP.NET application resides
and the client machine.

• In this model,the request go directly to IIS to provide the


authentication process.
• Useful in Intranet environments where users are already
logged onto a network.IIS takes the user’s credentials from
the domain logic.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1594
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Security-Windows Authentication
Creating Users and Groups:
Steps to create a user:
1. From Windows Server 2003/XP Choose Control Panel->Administrative
tool->Computer Management(Manages and controls resources on the
local web server)
2. Expand System Tools node
3. Expand Local users and Groups node
4. Select Users folder
5. Right click and select New Users
6. Give username, password and description.Uncheck “User must change
password at the next login”
7. Click Create button
Steps to create a group
1. Right click the Groups folder under “System Tools” to select New Group
and add Users.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1595
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Security-Windows Authentication
ASP.NET is used to control client access to URL resources. It is
configurable for the HTTP method used to make the request
(GET or POST) and can be configured to allow or deny access to
groups of users or roles.
<authorization>
<authorization>
<allow
<allow users="someone@www.contoso.com"
users="someone@www.contoso.com" />
/>
<allow roles="Admins" />
<allow roles="Admins" />
<deny
<deny users="*"
users="*" />
/>
</authorization>
</authorization>

• Permissible elements for authorization directives are either allow or


deny.
• Each allow or deny element must contain a users or a roles attribute.
• Multiple users or roles can be specified in a single element by
providing a comma-separated
<allow
<allow users="John,Mary"
list/>
users="John,Mary" />

• The HTTP method can be indicated using the Verb attribute:


<allow
<allow VERB="POST"
VERB="POST" users="John,Mary"
users="John,Mary" />
/>
<deny
<deny VERB="POST"
VERB="POST" users="*"
users="*" />
/>
<allow VERB="GET" users="*"
<allow VERB="GET" users="*" />/>
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1596
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Security-Windows Authentication
Integrated Windows Authentication
• This was previously known as NTLM or windows NT
Challenge/Response Authentication.
• This model has the client prove its identity by sending a has of its
credentials to the server that is hosting the ASP.NET application.
Basic Authentication
• This model requires a username and password form the client for
authentication.
• The drawback is that it passes the username and password to the
server as
• clear text.To implement,
 Open IIS-the properties dialog for the Web site
 Select the Directory “Security Tab” and click Edit button in the
Anonymous Access and Authentication Control Box
 Uncheck the “Integrated Windows Authentication” check box at
the bottom and check the “Basic Authentication” checkbox

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1597
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Security-Windows Authentication
Digest Authentication
• This model uses an algorithm to encrypt the clients credentials
before they are sent to the application server. To use this model, it
is necessary to have Windows domain controller and browsers must
confirm to HTTP1.1 specification

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1598
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Security-Form Based Authentication

The Forms-Based Authentication is used to authenticate


users to access an entire application or resources within
an application.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1599
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Security-Form Based Authentication
<authentication mode="Forms">
<forms name=".ASPXCOOKIEDEMO" loginUrl="login.aspx"
defaultUrl="default.aspx"
protection="All"
timeout="30"
path="/"
requireSSL="false"
slidingExpiration="true"
enableCrossAppRedirects="false"
cookieless="UseDeviceProfile"
domain="">
<!-- protection="[All|None|Encryption|Validation]" -->
<!-- cookieless="[UseUri | UseCookies | AutoDetect |
UseDeviceProfile]" -->
</forms>
</authentication>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1600
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Security-Form Based Authentication
Attribute Description

name Cookie name saved to remember the user from


request to request
loginUrl Specifies the URL to which the request is redirected
for login
protection Specifies the amount of protection to be applied for
the authentication cookie
All-application uses both validation and encryption
Encryption-cookie is encrypted but no data validation
Validation-Validation of cookie but no encryption
None-no encryption to the cookie

path Path for cookies issued by the application

timeout Specifies amount of time in minutes after which


the cookie expires
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1601
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Security-Form Based Authentication

Attribute Description

cookieless Specifies whether form-based


authentication process should use cookies

defaultURL Specifies the default URL

domain Specifies the domain name to be sent with


forms authentication cookies

slidingExpiration The expiration of the cookie is reset with


each request made to the server if this
value is true. Default is false
enableCrossAppsRe Specifies whether to allow for cross-
direct application redirection
requireSSL Specifies whether a Secure Sockets Layer
connection is requires when transmitting
authentication information

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1602
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Security-Form Based Authentication

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="username" runat="server"></asp:TextBox>
<asp:TextBox ID="password" runat="server"></asp:TextBox>
<asp:Button ID="loginButton" runat="server"
OnClick="loginButton_Click" Text="Button" />
</form>
</body>
</html>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1603
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Security-Form Based Authentication

Authenticating against values contained in the web.config file


<authentication mode="Forms" >
<forms name="First" loginUrl="First" path="/">
<credentials passwordFormat="Clear">
<user name="anny" password="praveen"/>
</credentials>
</forms>
</authentication>

passwordFormat:
passwordFormat:Clear:
Clear:Passwords
Passwordsarearestored
stored
MD5:Passwords
MD5:Passwordsare arestored
storedusing
usingaaMessage
MessageDigest5
Digest5hash
hashdigest
digest
SHA1:Passwords
SHA1:Passwordsare arestored
storedusing
usingaaSHA1
SHA1hash
hashdigest
digest

protected void loginButton_Click(object sender, EventArgs e)


{if (FormsAuthentication.Authenticate(username.Text, password.Text))
{ FormsAuthentication.RedirectFromLoginPage(username.Text, true);
Response.Redirect(“Home.aspx");
} else{ Response.Write("Invalid Login"); } }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1604
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Security-Form Based Authentication

Authenticating against values in a Database


private void login_Click(object sender, System.EventArgs e)
{
String sqlStmt = "Select username from Users where username='" +
username.Text + "' and password='" + password.Text + "'";
SqlConnection sqlConn = new SqlConnection("Data
source=localhost;User ID=sa;Initial Catalog=myshop;");
SqlCommand sqlCmd = new SqlCommand(sqlStmt, sqlConn);
sqlCmd.Connection.Open();
SqlDataReader sqlReader =
sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
if (sqlReader.Read())
{FormsAuthentication.RedirectFromLoginPage(username.Text, true);
Response.Redirect(“Home.aspx");
}
else
Response.Write("Invalid Login");
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1605
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Security-Form Based Authentication

Authenticating using Login Control

protected void Login1_Authenticate(object sender,


AuthenticateEventArgs e)
{
if (Login1.UserName == "anny" && Login1.Password ==
"praveen")
{
Response.Redirect("Sample.aspx");
FormsAuthentication.RedirectFromLoginPage(Login1.UserName,
Login1.RememberMeSet);
}
else
{
Response.Write("Invalid user");
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1606
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Security-Form Based Authentication

Authenticating specific files and folders

<configuration>
<location>
<system.web>
<authentication mode="None">
</authentication>
</system.web>
<location path="Default.aspx">
<system.web>
<authentication mode="Windows">
</authentication>
<authorization>
<deny users="*"/>
</authorization>
</system.web>
</location>
</configuration>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1607
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Security-Authorization
Page objects “User” property provides the following property and method

Identity: :This property provides an instance of


System.Security.Principal.IIdentitty Object to get specific
properties of the authenticated user.
IsInRole: This method takes a single parameter ,a system
representation of system role

User.Identity provides the following properties


AuthenticationType :Provides authentication type of the current
user(Basic/Forms/..)
IsAuthenticated :Returns a boolean value specifying whether the user has
been authenticated
Name :Provides the username of the user as well as the domain of
the user

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1608
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Security-Authorization

To work with roles & Authentication, System.Security.Principal provides

1.WindowsBuiltInRole enumeration
Values: :AccountOperator, Administrator, BackupOperator, Guest, PowerUser, PrintOperator,
Replicator, SystemOperator,User

2.WindowsIdentity object
Properties:ImpersonationLevel, IsAnonymous, IsAuthenticated, IsGuest, IsSytem, Name

IsInRole()
IsInRole() IPrincipal
Identity
Identity

Name
Name IIdentity
IsAuthenticated
IsAuthenticated
AuthenticationType
AuthenticationType
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1609
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Security-Authorization

protected void Page_Load(object sender, EventArgs e)


{
Response.Write(User.Identity.AuthenticationType.ToString());
if (User.Identity.IsAuthenticated)
{
Response.Write("Name of user" +
User.Identity.Name.ToString()+"<br>");
Response.Write("Authentication Type" +
User.Identity.AuthenticationType.ToString()+"<br>");
WindowsIdentity AuthUser = WindowsIdentity.GetCurrent();
Response.Write(AuthUser.AuthenticationType.ToString()
+"<br>"+
AuthUser.ImpersonationLevel.ToString()+"<br>"+
AuthUser.IsAnonymous.ToString() + "<br>" +
AuthUser.IsAuthenticated.ToString() + "<br>" +
AuthUser.IsGuest.ToString() + "<br>" + //Guest Account
AuthUser.IsSystem.ToString() + "<br>" + //System Account
AuthUser.Name.ToString());
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1610
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Deployment

Web site Deployment

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1611
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Deployment
ASP.NET contains a lot of pieces that are all possible parts of the
overall application and need to be deployed with the application
in order for it to run properly
• .aspx pages
• The code-behind pages for the .aspx pages (.aspx.vb or .aspx.cs
files)
• User controls (.ascx)
• Web service files (.asmx and .wsdl files)
• .htm or .html files
• Image files such as .jpg or .gif
• ASP.NET system folders such as App_Code and App_Themes
• JavaScript files (.js)
• Cascading Style Sheets (.css)
• Configuration files such as the web.config file
• .NET components and compiled assemblies
• Data files such as .mdb files

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1612
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Deployment
Steps to Take before Deploying
• The first step you should take is to turn off debugging in the
web.config file
<configuration
xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<system.web>
<compilation debug="false" />
</system.web>
</configuration>

• The second step is to build the application in Release mode. This


can be accomplished by changing the Active Solution Configuration
from Debug to Release through the drop-down list in the Visual
Studio menu

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1613
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Deployment Methods
Methods of Deploying Web Applications
• Use the XCopy capability that simply wows audiences when
demonstrated (because of its simplicity).

• Use Visual Studio 2005’s capability to copy a Web site from


one location to another using the Copy Web Site feature, as
well as an alternative method that uses Visual Studio to
deploy a precompiled Web application.

• Use Visual Studio to build an installer program that can be


launched on another machine

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1614
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Deployment-XCopy
XCopy Option
• Applications in .NET compile down to assemblies, and these
assemblies contain code that is executed by the Common
Language Runtime (CLR). The great thing about assemblies
is that they are self-describing. All the details about the
assembly are stored within the assembly itself.
 XCOPY is the command-line way of basically doing a copy-and-
paste of the files needed to move.
 XCOPY helps to move files, directories, and even entire drives
from one point to another.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1615
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Deployment-XCopy
• The default syntax of the XCOPY command is as follows:

xcopy
xcopy [source]
[source] [destination]
[destination] [/w]
[/w] [/p]
[/p] [/c]
[/c] [/v]
[/v] [/q]
[/q]
[/f]
[/f] [/l]
[/l] [/g]
[/g] [/d[:mm-dd-yyyy]]
[/d[:mm-dd-yyyy]] [/u]
[/u] [/i]
[/i] [/s
[/s [/e]]
[/e]] [/t]
[/t]
[/k]
[/k] [/r]
[/r] [/h]
[/h] [{/a|/m}]
[{/a|/m}] [/n]
[/n] [/o]
[/o] [/x]
[/x] [/exclude:file1[+
[/exclude:file1[+
[file2]][+file3]]
[file2]][+file3]] [{/y|/-y}]
[{/y|/-y}] [/z]
[/z]

• When using XCOPY, this method does not allow for the
automatic creation of any virtual directories in IIS.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1616
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Deployment-XCopy
Parameters
Parame Description
ter
/w Displays the message: Press any key to begin copying file(s). It waits for your
response to start the copying process.

/p Asks for a confirmation on each file being copied. This is done in a file-by-file
manner.

/c Ignores errors that might occur in the copying process.

/v Performs a verification on the files being copied to make sure they are identical
to the source files.

/q Suppresses any display of the XCOPY messages.

/f Displays the file names for the source and destination files while the copying
process is occurring.

/l Displays a list of the files to be copied to the destination drive.

/g Builds decrypted files for the destination drive.

/d When used as simply /d, the only files copied are those newer than the existing
files located in the destination location.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1617
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Deployment-XCopy
Parameters

Parameter Description
/u Copies only source files that already exist in the destination location.

/i If what is being copied is a directory or a file that contains wildcards and the
same item does not exist in the destination location, a new directory is created.
The XCOPY process also copies all the associated files into this directory.

/s Copies all directories and their subdirectories only if they contain files. All
empty directories or subdirectories are not copied in the process.

/e Copies all subdirectories regardless of whether these directories contain files.

/t Copies the subdirectories only and not the files they might contain.

/k By default, the XCOPY process removes any read-only settings that might be
contained in the source files.

/r Copies only the read-only files to the destination location.

/h Specifies that the hidden and system files, which are usually excluded by
default, are included.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1618
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Deployment-XCopy
Parameters

Parameter Description

/exclude Allows you to exclude specific files. The construction used for this is
exclude:File1.aspx+File2.aspx+File3.aspx.

/y Suppresses any prompts from the XCOPY process that ask whether to
overwrite the destination file.

/-y Adds prompts in order to confirm an overwrite of any existing files in


the destination location.

/z Copies files and directories over a network in restartable mode.

/? Displays help for the XCOPY command.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1619
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Deployment-XCopy
Parameters

Parameter Description

/a Copies only files that have their archive file attributes set, and leaves
the archive file attributes in place at the XCOPY destination.

/m Copies only files that have their archive file attributes set, and turns off
the archive file attributes.

/n Copies using the NTFS short file and short directory names.

/o Copies the discretionary access control list (DACL) in addition to the


files.

/x Copies the audit settings and the system access control list (SACL) in
addition to the files.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1620
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Deployment-Copy Web Site
VS Copy Web Site Option
• This GUI enables you to copy Web sites from your
development server to either the same server or a
remote server (as you can when you use the XCOPY
command).
 Pull up this Copy Web Site dialog in Visual Studio in two ways.
 Click in the Copy Web Site icon in the Visual Studio Server
Explorer.
 Open the Copy Web Site GUI is to choose Website Copy Web
Site from the Visual Studio menu.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1621
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Deployment-Copy Web Site

VS Copy Web Site Option


Click the Connect To a Remote Server button

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1622
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Deployment-Copy Web Site
• File System: Allows navigating through a file explorer view of the
computer. To install on a remote server from this view, a drive
must be mapped to the installation location.

• Local IIS: This option enables to use local IIS in the installation of
Web application. The Local IIS option does not permit to work with
IIS installations on any remote servers.

• FTP Site: This option enables to connect to a remote server using


FTP capabilities. From this dialog, specify the server to contact
using a URL or IP address, the port to use, and the directory on the
server. Also specify the username and password to access the
server via FTP.

• Remote Site: This option enables to connect to a remote site


using FrontPage Server Extensions. Also connection to the remote
server is possible using Secure Sockets Layer (SSL).

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1623
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Deployment-Visual Studio Installer

Visual Studio Installer Option


• Setup Project: This project type helps in creating a standard
Windows Installer setup for a Windows application.
• Web Setup Project: It’s the type of setup project used to create an
installer for an ASP.NET Web application.
• Merge Module Project: This project type creates a merge module
similar to a cabinet file.This project type produces a file type with an
extension of .msm.
• Setup Wizard: This selection actually gives a wizard to assist the
installer through one of the other defined project types.
• Cab Project: This project type creates a cabinet file (.cab) that
packages a group of files for distribution.
• Smart Device Cab Project: This new project type allows for the
creation of a cabinet file that is installed on a smart device instead of
on a typical operating system.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1624
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Deployment-Visual Studio Installer

Web Setup Project


• Open up the project for which a deployment project has to be created
in Visual Studio. Choose FileNewProject from the Visual Studio menu.
• From the New Project dialog, Expand Other Project Types from the
left-hand pane in the dialog and then select Setup and Deployment.
• Select Web Setup Project
• The File System Editor shows a single folder: the Web Application
Folder.
• Choose ProjectAddProject Output from the Visual Studio menu.
• The Add Project Output Group dialog opens
• Highlight the Content Files option and click OK. This adds all the files
from the MyShop project to the WebSetup1 installer program
• Click the Launch Conditions Editor but-ton in the Solution Explorer to
open the editor
• To add conditions->Right-click the Requirements On Target Machine
node. Then select Add .NET Framework Launch Condition

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1625
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Deployment-Visual Studio Installer

• Highlight the WebSetup1 program in the Visual Studio Solution


Explorer so you can modify some of the properties that appear in
the Properties window
• Select ‘Release’ as the active solution configuration in the Visual
Studio toolbar
• Build the installer program by choosing BuildBuild WebSetup1 from
the menu.
• Look in C:\Documents and Settings\Administrator\My
Documents\Visual Studio\Projects\MyShop\WebSetup1\Release,
 Setup.exe: This is the installation program. It is meant for
machines that don’t have the Windows Installer service
installed.
 WebSetup1.msi: This is the installation program for those that
have the Windows Installer service installed on their machine.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1626
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Health Monitoring

Web Site Health Monitoring

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1627
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Health Monitoring
ASP.NET provides an easy way to monitor the health of deployed
ASP.NET applications, providing detailed run-time information
about ASP.NET resources.

ASP.NET health-monitoring features can be used to perform the


following tasks:
• Monitor live ASP.NET applications, individually or across a Web
farm, to ensure that they are working properly.
• Diagnose ASP.NET applications that appear to be failing.
• Log events that do not necessarily relate to errors in an ASP.NET
application but can be useful for examination.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1628
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Web Services

Web Services

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1629
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Web Services
Topics for Discussion
• Web Service Architecture

• Building Blocks of Web Service


 Protocols
• Web Service Development
 Designing a Web Service
 Creating a Web Service

• Web Service Deployment and Consumption of a Web Service


 In an Web Application
 In an Windows Application

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1630
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Web Services
Web Services
• Traditional middleware platforms such as DCOM,CORBA / IIOP and
Java RMI are used to build distributed systems. When exposed to
the World Wide Web they encounter the following problems:
 Getting through firewalls.
 Communicating across platforms.
 Keeping systems components independent of each other.
• Web Service technology is the result of extensive collaboration
between industry leaders such as Microsoft and IBM and has
received widespread industry support.
• Web Service is loosely coupled, reusable software components that
semantically encapsulate discrete functionality and are distributed
and programmatically accessible over standard Internet protocols.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1631
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ASP.NET Web Services
Web Services
• Web services are a stack of emerging standards that describe a
service-oriented, component-based application architecture.
• A Component That Uses XML & HTTP To Define and Deliver A
Service
 Global reach
 Based on open set of standards
 Reuse across platforms
 Works with any operating system, programming language, or
network
 Expose legacy code

• Different systems can actually talk

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1632
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Service Architecture
Architecture
• The browser sends a HTTP request to the Web server.
• Upon receiving the request the web server parses it.
• The Web server then sends a SOAP (Simple Object Access Protocol)
request over HTTP to the web service provider.
• The web service provider parses the request and extracts the
required information from its database.
• The Web service provider then sends the headlines in a SOAP
response to the web server.
• The Web server parses the response and creates an HTML page and
sends it via HTTP to the browser.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1633
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Services-Usage

Static  HTML
Content  Dynamic HTML (JavaScript)
Web

 CGI (using Perl, etc.)


 ColdFusion, ASP, Java Servlet, JSP
Dynamic
Interactive  ASP.NET
Web  XML (Document interchange)

Integrated  XML
Programmable  Web Services (SOAP, WSDL, UDDI)
Web

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1634
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Services-Protocols

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1635
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Services-Protocols
Service
Registries
• Public UDDI
• Private UDDI
d
Fin

er eria
es

vic

Bu rvi to

Pu
b s rit
w e ch c

se RL
sin ces WS

bli
sh
U

es in D
for ear

s & fo. L
RL
S

LU


SD
W

Bind 

 WSDL URL
Web Web
Service WSDL File  Service
Consumers Providers
 SOAP Request

SOAP Response

Invoke

Role Operation Data flow n Data/Message


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1636
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Services-Protocols

Service Composition
(BPEL4WS)
(XML 1.0 Specification and XML Schema)

Service Directory
Standard Definition Languages

(UDDI)

Service Description

(SAML, WS-Security)

(WS-Manageability )
(WSDL)

Management
Security
Messaging Protocol
SOAP Extension
Reliability, Transaction
(WS-ReliableMessaging, WS-Transaction)

(SOAP)

Communication Protocol
(HTTP, FTP, SMTP, etc.)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1637
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Services Protocols-SOAP
Protocols
• The SOAP specification was designed by industry leaders such as Microsoft ,
IBM and Lotus.
• SOAP: "Simple Object Access Protocol“
 SOAP 1.1
 SOAP 1.2
• XML-based lightweight protocol for exchanging information in a
decentralized, distributed, heterogeneous environment
 Encapsulates the ability to make RPC Calls
 Data Encoding (serializing and de-serializing)
 Message Structure
 Message-Processing
• SOAP is used by the following .NET technologies.
 ATL web services ( Active Template Library).
 .NET remoting.
 ASP.NET Web services.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1638
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Services Protocols-SOAP
• Simple Object Access Protocol (SOAP) is the protocol used by
consumers for sending requests to, and receiving responses from,
XML Web services.
• It defines an XML grammar for specifying the names of methods that
a consumer wants to invoke on an XML Web service; for defining the
parameters and return values; and for describing the types of
parameters and return values.
• When a client calls an XML Web service, it must specify the method
and parameters by using this XML grammar.
• SOAP is being adopted as an industry standard. Its function is to
improve cross- platform interoperability. The strength of SOAP is its
simplicity and also the fact that it is based on other industry standard
technologies: HTTP and XML.
• The SOAP specification defines a number of things. The most
important are the following:
 The format of a SOAP message
 How data should be encoded
 How to send messages (method calls)
 How to receive responses

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1639
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Services Protocols-SOAP

Phase 1 SOAP Phase 2


Serialize request Deserialize
XML XML

SOAP SOAP
message message
Attachments SOAP Envelope HTTP
Header

XML Web
Proxy XML Data Service
object object
Web
Client
Server

XML XML
Phase 4 SOAP Phase 3
Deserialize SOAP SOAP Serialize
message response message
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1640
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Services Protocols-SOAP Request

The SOAP request sent by the client might look like this:
POST /NorthwindServices/ProductService.asmx 
HTTP/1.1 Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: 633
SOAPAction: "http://www.contentmaster.com/webservices/HowMuchWillItCost" <?
xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/ XMLSchema" xmlns:soap="
http://schemas.xmlsoap.org/soap/envelope/">   
<soap:Body>     
<HowMuchWillItCost xmlns="http://www.contentmaster.com/webservices">       
<productName>Chai</productName>       
<howMany>39</howMany>     
</HowMuchWillItCost>   
</soap:Body>
</soap:Envelope>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1641
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Services Protocols-SOAP Response

The Web server will receive this request, identify the XML Web
service and method to run, run the method, obtain the results,
and send them back to the client as the following SOAP result:
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8Content-Length: 515
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/ XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">  
<soap:Body>    
<HowMuchWillItCostResponse xmlns=     
"http://www.contentmaster.com/webservices">      
<HowMuchWillItCostResult>529</HowMuchWillItCostResult>    
</HowMuchWillItCostResponse>  
</soap:Body>
</soap:Envelope>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1642
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Services Protocols-WSDL
WSDL
• WSDL (Web Services Description Language) was created to address
the problem of describing web services in a comprehensive ,
understandable and formalized manner.
• It is a XML based language that describes the interfaces of web
services , their input and output parameters and their protocol
bindings.
• The structure and format of WSDL documents is formally specified
– making every document machine readable.
• WSDL description documents can describe the following type of
web service protocol bindings- HTTP GET,HTTP POST,SOAP,MIME
• A client can submit a request to an XML Web service with the query
string wsdl appended to
it:http://localhost/NorthwindServices/ProductService.asmx?wsdl
• The XML Web service will reply with a description
• This description provides enough information to allow a client to
construct a SOAP request in a format that the Web server should
understand.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1643
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Services Protocols-WSDL
WSDL Document Structure
• Each WSDL document id divided into distinct sections-Types,
Messages, Port types, Bindings and Services.
• The root element of a WSDL description is <definitions>. Below this
element are a list of XML namespaces.
• The <message> element occurs within the Messages section. It
comprises a group of parameters to a web service operation, which
is essentially a function.
• The Port Types section optionally comprises <portType> elements,
which provide abstract definitions of operations.
• There can be zero or more <binding> elements in the Binding
section-if there are no binding elements, the web service will be
functional but not accessible.
• The Services section comprises <port> elements, which associate
with <binding> elements in the binding section.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1644
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Services Protocols-UDDI
UDDI
• UDDI (Universal Description Discovery and Integration) is a platform independent,
open framework for discovering businesses and services using the internet. It acts as
a functional business and service registry.
• It enables applications to locate the Web Services, either within the internal system or
over the internet by referencing WSDL formatted protocol descriptions.
• UDDI is maintained by the UDDI community, which is a consortium of more than 200
companies that includes all industry leaders.
• Since the technology used is XML based, its searching and describing potential is
extensible.
• UUDI was jointly launched by Microsoft, IBM and Ariba.
• Its purpose is to standardize how businesses describe and publish the Web Service.
• The UDDI tool has 2 main elements :
 UDDI XML schema for business description.
 Web based registry.
• There are currently 2 public versions of UDDI registry hosted by Microsoft and IBM.
• To access the Microsoft UDDI and located the Microsoft services type
http://uddi.microsoft.com in the browser.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1645
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Designing a Web Service
Designing a Web Service
• This involves breaking the entire process into smaller design stages
and completing each stage before moving on to the next. It
involves the following stages:
 Vision Document.
 Conceptual Design.
 Logical Design.
 Physical Design.
 Architecture.
 Security Design

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1646
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Designing a Web Service
Vision Document
• The vision document establishes the goals of the service. It should
cover the following areas:
 The user base for your service.
 The business objectives.
 Its specific functions.
 Accessing running costs.
 How long it would take to attract users and what they would
pay for it.
 Deciding how Managers and maintainers would access the
service.
 The end users of the service.
 Any third party companies that might not pay for the service
but would need to access the same for security and
authentication.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1647
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Designing a Web Service
Conceptual Design
• The purpose of conceptual design is to plan how your service will
actually be used.
• This can be done by identifying users and their requirements.
• The advantages of the conceptual design is
 Identify common system access points.
 Have a better idea about how the different elements of a
service will work together.
 Logical components that would comprise the web service.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1648
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Designing a Web Service
Logical and Physical Design
Logical Design involves
 Analyzing the functions the service will have to perform .
 Breaking the functions into logical components.
 Determining the relation among objects of a web service.
Physical Design
• Examine the components of the web service identified earlier and
decide about their physical implementation.
• There are certain criteria that should be applied while selecting
components
 Scalability
 High performance.
 High availability.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1649
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Designing a Web Service
Security Design and Architecture
• While designing the Web service the security requirements must be
considered regarding the following issues
 Authentication: The identity of a user should be checked before
letting them access personal data. Could be one among the
following: Web Forms, Integrated Windows, clear text,
certificates.
 Privacy : The information sent by the web service should be
seen by the user for which it is intended.
 Authorization : Only authorized users should be provided
access to certain code and the privilege to change data.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1650
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Designing a Web Service
Authentication
Web services can use either one or more of the following
authentication methods:
• Web Forms: When the user attempts to access a Web service, he is redirected to an
HTML Form, usually containing simple user name and password. Use for protecting
the user’s custom settings rather than for protecting valuable data.
• Integrated Windows Authentication: Performed by IIS ( Internet Information Server).
Accounts are created for users who can then access the services. It allows us to group
accounts for users.
• Clear text authentication: Uses user names and passwords to identify users and
encode the information using Base64 encoding before sending it to the internet.
• Certificates : Issued by third parties and users can use them to identify themselves to
the web service. The authentication work is handled by the issuing authority.
• Advanced Authentication methods : HTTPS or SOAP can be used . SOAP provides
 Greater customization.
 Protocol Independence.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1651
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Designing a Web Service
Authentication
• Malicious users would try to gain access to the web service through
spoofing. A strong encryption method is one of the best defenses.
• Hackers might try to detect the common passwords to gain
unauthorized access. This is called dictionary attack. This can be
checked by frequently changing the passwords and frequent
system audits.
• Denial of service attacks might be used to bring down services and
servers. This can be done by issuing a ping request to another
computer. To deal with the menace denial of ping request can be
done.
• Another alternative could be to place your web service behind a
firewall. This can be useful if the No. of users are lesser and within
a range e.g. employees of a particular company.
• The best way could be to remove all non essential software from
your machine and distributing the services across multiple servers

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1652
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Designing a Web Service
Design Issues
• While designing a web service client, you can use two methods of
invoking the service methods:
 Synchronous
 Asynchronous
• In the synchronous web service, communication between client and
server occurs at regular intervals.
• In an asynchronous communication, the client connects at irregular
intervals. Client is free to call other methods before the service
responds. Writing these web services is more complex for parallel
execution.
• However, asynchronous programming has these advantages
 Efficient use of processing resources.
 Better use of threads in Server side programming.
 Ability of a single program to exploit multiple processors.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1653
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Designing a Web Service
Design Issues-Exception Handling
• Using the wsdl.exe tool of Microsoft Framework, for a single web
method present in the Web service, 3 methods are generated:
 The first method is a synchronous method.
 The other 2 are asynchronous method-one to begin the request
and other to end it.
• Web services are subjected to failure due to bugs, network
problems or other reasons. The SOAP specifications communicates
these exceptions to the web client. These are called SOAP faults.
• By default, when the web client receives a SOAP fault, it generates
an error message.
• For displaying Custom error messages from the client, the SOAP
fault message can be trapped using the SOAPException class
located in the System.Web.Services.Protocols namespace.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1654
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Web Services
Creating the ProductService Web Service
• Create a new project using the ASP.NET Web Service template. Call
the project NorthwindServices, and create it on your local Web server.
• In Solution Explorer, change the name of the Web service class file
from Service1.asmx to  ProductService.asmx.
• In Class View, rename the Service1 class to ProductService.
• Select the class, and then on the View menu, click Code to display the
Code And Text Editor window for ProductService. Notice that it is held
in a file called  ProductService.asmx.cs.
• Examine the ProductService class; it is descended from System.Web.
Services.WebService. Scroll to the bottom of the class. A method has
been commented out because this is just a sample Web method.
• Add the following WebService attribute to the ProductService class.
This attribute indicates the namespace used to identify the XML Web
service:
[WebService     (Namespace="http://www.contentmaster.com/NorthwindServices")]
public class ProductService : System.Web.Services.WebService {     ⋮ }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1655
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Web Services
Define the HowMuchWillItCost Web method
• Delete the sample Web method (HelloWorld, which is commented
out) in the ProductService class. In its place, add the following
method:
[WebMethod] public decimal HowMuchWillItCost(string productName,
    int howMany) { }
• All methods exposed by an XML Web service must be tagged with
the WebMethod attribute. This method will expect the client to pass
in the name of a product found in the Products table in the
Northwind Traders database and a quantity of that product. The
method will use the information in the database to calculate the
cost of supplying this quantity of the product and pass it back as
the return value of the method.
• Add the following using statement to the top of the file:
using System.Data.SqlClient;

• This is the namespace that contains the Microsoft ADO.NET classes


for gaining access to the Microsoft SQL Server computer.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1656
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Web Services

Define the HowMuchWillItCost Web method


In the HowMuchWillItCost Web method, type the following
statements:
try {     
SqlConnection sqlConn = new SqlConnection( "data source=localhost;" +
        "initial catalog=Northwind;integrated security=true");     
SqlCommand sqlCmd = new SqlCommand();     
sqlCmd.CommandText = "SELECT UnitPrice FROM Products " +        
"WHERE ProductName = ’" + productName + "‘";     
sqlCmd.Connection = sqlConn;     
sqlConn.Open();     
decimal price = (decimal)sqlCmd.ExecuteScalar();     
sqlConn.Close();     
return price * howMany;
} catch(Exception e)
{     
throw new Exception("Error calculating cost: " + e.Message);
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1657
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Web Services
Define the HowMuchWillItCost Web method
• This code connects to the Northwind Traders database and runs an
SQL SELECT statement to retrieve the UnitPrice column for the
selected product in the Products table. The ExecuteScalar method
is the most efficient way of running a SELECT statement that
returns a single value. The UnitPrice column is stored in the price
variable, which is then multiplied by the howMany parameter that
is passed in to calculate the cost.
• Although the Web service uses a try...catch block to trap any
database access errors, it does not validate the parameters passed
in (for example, the client might supply a negative value for the
howMany parameter). You should add the necessary code yourself.
[WebMethod]
• On the Build menu, click Build Solution to compile the
WSDLXML Web
Public Function HelloWorld() as String WSDL
service.
return “Hello World” Compiler Web
Web
Test
Test Service
Service
End Function Page
Page Object
Object

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1658
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Web Services

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1659
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Web Services

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1660
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Web Services

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1661
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Web Services

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1662
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Consuming Web Services
Create XML Web service Control Property Value

client application label1 Text Product Name

• In the Visual Studio .NET Location 16, 40

programming environment, label2 Text Number Required


create a new project using the Location 16, 80
Windows Application template.
Call the project OrderCost label3 Text Total Cost

• Change the Text property of Location 16, 200

Form1 to Order Cost. textBox1 Name ProductName

• Add and set the properties of Location 128, 40


these controls using the values in Text Leave blank
the following table.
numericUpDown1 Name NumberRequired
• On the Project menu, click Add
Location 128, 80
Web Reference. In the Add Web
reference dialog box, type textBox2 Name TotalCost

http://localhost/NorthwindSe Location 128, 200


rvices/ProductService.asmx in Text Leave blank
the URL text box and press Enter.
button1 Name HowMuchButton
• Click Add Reference. The
Location 16, 136
localhost Web Reference will be
added to the project. Text How Much

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1663
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Consuming Web Services

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1664
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Services-Deployment

Web Services Provider WSClass.Method(…) as Method


Return Type
VS.NET Add Web Ref Web Services
HTTP/WSDL Application Server
Web Service
Source Code HTTP-SOAP-IN
(Server) Web Service Message
Deploy Executables HTTP-SOAP-
OUT
Compiler WSDL

VS.NET .NET Client


Web Services Platform
Consumer Web Service
Proxy Code Web Service
(client) Proxy Code
Compiler
Client Client
Source Code Application

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1665
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Best Practices with
.NET Framework

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Web Application Development with ASP.NET
ASP.NET Best Practices-Planning

How do I…
• Create an n-tier design for my Web site?
• Store and retrieve application settings?
• Create a dynamic and flexible user interface?
• Ensure common code runs each time a page is loaded?
• Track users’ actions throughout my Web application?
• Track and notify tech support of exceptions that occur?
• Provide bullet-proof access to Session variables?
• Ensure unexpected errors are handled gracefully?
• Assign roles to users and secure Web pages?
• Provide the best performance?

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1667
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Quiz

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Final Case Study

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DotNet Schedule

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1670
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Evaluation Criteria

Appraisals Weightage Pass Criteria

Mini Case study 15 Marks 10 Marks

Final Case study 35 Marks 23 Marks

Test 50 Marks 32 Marks

Total 100 Marks 65 Marks

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
1671
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thank You

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.

You might also like