Professional Documents
Culture Documents
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?
©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();
©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
©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
©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 ]
}
}
©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.
©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.
©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.
©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.
©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.
©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
©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
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;
}
}
©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.
©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)
©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
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.
©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.
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.
©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
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
©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
©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
©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
©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.
©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.
©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
©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
©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
©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
©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
©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
©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
©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
©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
©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
©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:
©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
©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)
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
©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
©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
©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
©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
©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
Results
Results
Transact-SQL
Transact-SQL
Application
Application
Client SQL Server
Relational Database
Management System
While Constructs
Syntax:
WHILE Boolean_expression
{ sql_statement | statement_block }
[ BREAK ]
{ sql_statement | statement_block }
[ CONTINUE ]
©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
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
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)
©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
©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
©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
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
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
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
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
©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
©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
©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
©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
©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
©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
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
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()
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
©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
©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
©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…)
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?
©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!
©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
©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
©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?
©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
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
©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
©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
©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
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>> }
©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
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>> }
©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
©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
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
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”);
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
©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
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”);
©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
©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
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
©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
©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
©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
©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
©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 :
Data Cables
Hard Disk Motherboard Power Supply
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
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
©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
©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
©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
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
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
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, …
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
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
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# …
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
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
©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
©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
©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
©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)
©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
©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
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
©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
©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;
©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
©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);
}
©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
©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
©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
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
©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”
©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
©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
©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
©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
©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
©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!");
}
}
}
©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]
©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
©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
©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)
©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;
©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
©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);
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
}
©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
©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
©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
©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
©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
©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;
©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();
}
}
©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
©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
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
©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
}
©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
}
}
©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 );
©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);
}
©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);
}
©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
©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];
intializations
myArray = new int[] {1, 3, 5, 7, 9}; // OK
©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)
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];
©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) …..
©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)
©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.
©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.
©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
If you are inside of Visual Studio with an open project, you can use the
Debug menu to get started.
©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.
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
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
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
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
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
©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
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.
©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
ToolBox
©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
©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.
©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
©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
©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 }
©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)
©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
©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
©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
©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
©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;
}
}
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
©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
©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()
{...}
}
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{}
©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
[System.SerializableAttribute]
partial class Kid { }
[System.ObsoleteAttribute]
partial class Kid { }
[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
©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.
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
©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:
©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.
©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()
{
}
©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…
©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;
©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
©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
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));
©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
©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
• 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
©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
©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 );
}
©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
{
}
©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
©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
©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
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
©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
©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;
©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);
}
©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;
}
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)
©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
©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);
Array.Sort(myIntArray);
Sort is a static method of System.Array class
The Contract is :
interface IComparable
{
int ComparteTo(object o);
}
Array.Sort(prods);
©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);
}
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);
}
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();
©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
©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
©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);
}
}
©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
©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
©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
©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
©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
©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.
©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
Attributes
A line of text within the class box
©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
The name of the property goes at the target end of the association,
together with its multiplicity.
©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 …
©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
©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).
©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
©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.
©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
©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
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
©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.
©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)
©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.
©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
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?
©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;
©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
©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
©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.
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.
©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
©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];
}
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.
©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:
©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:
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
©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>();
©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.
©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?
©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);
©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!
©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);
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();
}}
©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
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);
}}
©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.
©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
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
©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.
©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
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
©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
©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
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
©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
©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
©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
©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
©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
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.
©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
MyAssembly.dll
Graphic.bmp
©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
©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
©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:
©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:
©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
©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..)
©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.
©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.
©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.
©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:
©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
©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.
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
©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( ).
©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.
©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)
©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)
©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
}
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)};
©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;
}
©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
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
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
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
©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
©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:
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
©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
©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
Base Classes
©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
©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 to Business
©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
©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
©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
©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
©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
©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
©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
©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
©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
©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…
©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)
©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
©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
©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
©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
©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
©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
©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
constraints, Table
©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.
©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
©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
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
©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
©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
©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
©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
©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
©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
©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
©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
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
©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
©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
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);
©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
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
©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
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
©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
view2.RowStateFilter= DataViewRowState.ModifiedOriginal;
©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
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
©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
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
string strCmd=
"Insert into input(EmpId,EmpName,Department,BasicSal)
values(@Eid,@Ename,@Dept,@Esal)";
©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
©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.
©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
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
©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.
©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
©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
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();
}
} }
©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
</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
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
©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.
©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();
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
©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.
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
source.Open();
destination.Open();
cmd.ExecuteNonQuery();
©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
©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.
©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.Open();
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
©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();
SqlDataReader sqlDataReader =
sqlCommand.ExecuteReader(CommandBehavior.CloseConnecti
on);
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
©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
©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.
©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
©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
©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
Provider-
independent apps
Db* abstract base classes (e.g. DbConnection) Code to this layer
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");
©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”
©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
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
©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
©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
©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
©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
©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
©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
©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
©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:
©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:
©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
©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
©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
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
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
©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
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:
©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
©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
©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
©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.
©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
©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
©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
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
©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
©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
©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
©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
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.
©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
©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
©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
©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
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 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.
©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.
©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.
©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
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).
©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
©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">
©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.
©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.
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.
©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.
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).
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.
<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
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
©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.
©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.
©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>.
• 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
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.
©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
©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
©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
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
Master Pages
and Skins Client Scripting & Localization
Role
Membership Profiles Configuration
and APIs
Management
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
Master
MasterPages Themes/Skins Localization Adaptive
Pages Themes/Skins Localization AdaptiveUIUI
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)
Business
BusinessLogic
LogicTier
Tier
Proxy ADO.NET RCW
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
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
©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
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.
©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.
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
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
©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
©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)
©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
©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)
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
©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
©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.
©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)
©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
Assigning
AssigningaaControl’s
Control’sSkinID
SkinIDProgrammatically
Programmatically
©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
IPostBackEventHandler
Control
Click!
Click! calls OnClick()
Control
Control
invokes event handler
Button1_Click()
HTTP form post
Page/Control Processing
First load
©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" …>
©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
©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
<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
<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 />
©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
<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
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
©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
©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>
©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
©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
<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
©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
}
}
©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
<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
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
©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
©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
©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: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
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
©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
<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.
©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
<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
©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
©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
©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" />
©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
©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
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
©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.
<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
©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
©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
©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
©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
©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
©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
©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
©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
©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
©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
<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
©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
<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
©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
©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
©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
©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
<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
©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
<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
<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
©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
©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
©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
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
©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
©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
©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
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
<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
<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>
©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>
<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
©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
©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
©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
Adding
AddingXmlDataSource
XmlDataSourceand
andassigning
assigningthe
thefilename
filenametoto“DataFile”
“DataFile”Attribute
Attribute
©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
©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();
}
<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>
©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
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
<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
<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
©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
©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
<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.
©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
©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
©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
©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
©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
©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
©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
©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
©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
<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
©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
©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
©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
©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
©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
©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
©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
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
©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
©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
©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
<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.
©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
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
©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
©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
©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
©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
©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.
• 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
©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
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
©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
©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
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
©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
©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
©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
• Highly customizable UI
<asp:GridView
<asp:GridView DataSourceID="Employees"
DataSourceID="Employees" Width="100%"
Width="100%"
RunAt="server" />
RunAt="server" />
©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
©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
©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
©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.
©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
Property Description
ShowFooter Shows or hides the footer 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
©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
©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
©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.
©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" />
©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
©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
<asp:DetailsView DataSourceID="AuthorsSource"
AllowPaging="true"
AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true"
AutoGenerateInsertButton="true"
DataKeyNames="au_id" 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
©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
©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
©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.
©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
©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
©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
©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
[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
©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
©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); }}
©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
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
©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
©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
©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
©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
©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
©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
©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
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();
©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
©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
©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
©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
©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).
©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.
©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.
Section Description
©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
©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.
©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
©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.
©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
©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
©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.
©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
©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
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)
©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
©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>
©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
©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
Attribute Description
©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
©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
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
©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
©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
©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
<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
©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
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
©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
©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>
©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).
©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.
/v Performs a verification on the files being copied to make sure they are identical
to the source files.
/f Displays the file names for the source and destination files while the copying
process is occurring.
/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.
/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.
/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.
©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.
/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
©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.
©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
©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
©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
©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
©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.
©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
©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
©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
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
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
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;
©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
©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
©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
©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
©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.