Anda di halaman 1dari 1672

DOTNET

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

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

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

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

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 No Topics

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 No Topics

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 No Topics

780 Web Site Management


829 Best Practices with .Net Framework

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

When you go against a standard, document it.


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

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

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

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

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

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

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

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

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

Instead of following example


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

This will unnecessarily occupy two memory locations

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

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

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

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

When the above steps are complete and correct, check


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

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

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

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

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

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

Example of Switched Loop


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

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

The for statement is repeated, so the code uses more


space, but the time savings speak for themselves.

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

Example of Separate Loops that could be Jammed


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

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

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

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


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

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

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

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


readability

Example of Complicated Pinter Expression Inside a Loop


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

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

Example of Nested Loop That Can be Improved


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

The key to improving the loops is that the outer loop


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

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

String str = new String(“Hello”);


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

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

String str = “Hello”;


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

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


performance a bit.

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

Example of Not Stopping after we know the Answer

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

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

Alternate for multiple IF clause


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

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

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

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

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

Unexpected program failures are a disaster - at the best,


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

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


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

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

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

Authorization provides controlled access to protected


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

Authentication is a process that verifies the identity


of a user

Access Control is a process that determines whether


this authenticated user is entitled to access a
particular requested resource

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

Role - an abstract name for the permission to access a


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

User - an individual (or application program) identity


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

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

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

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

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

Reasons for Layering


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

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

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

The major activities are


• Designing the routine
• Checking the design
Begin
• Coding the routine
• Checking the codeDesign Check
the the
routine design
Repeat if
necessar
y
Check Code
the code the
routine
Done
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
57
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Routines/ Modules
Characteristics of Routine (Modules)
Strong Cohesion
Cohesion refers to how closely the operations in a routine are
related or how strongly the operations are related in a Layer

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

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

Advantages
The payoff is higher reliability.

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

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

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

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

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

A great developer knows that there


is more to development than development.

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

COE – Current Technologies


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

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

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

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

Database Management Systems or Database Systems consists of :


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

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

The goal of a DBMS is :


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

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

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

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

Collection of conceptual tools for describing data, data


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

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

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

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

Object Oriented Model


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

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

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
71
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Record Based Logical Models
The Relational Model
Data and relationships are represented by a collection of
tables.
Each table has a number of columns with unique names, e.g.
customer, account.
Nam e S treet C ity N u m ber N um ber B alanc e
H a rry M a ples Q ueens 900 90 0 3000
S h iver N orth B ro nx 646 64 6 500
D e rek S ideh ill B ro ok ly n 337 33 7 1500
G ail W es t B uffalo 801 80 1 300
H o dges S ou thw oodJers ey 617 61 7 2500

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

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

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


relationships in data

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

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

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

Databases changes over time


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

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

Ability to modify a schema definition in one level without


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

The Application Programmer


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

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

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

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
79
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Database System Components &
Architecture
USERS DBA
Application Database
Query
Programs Schema

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

External Schema
(User View)

Conceptual Schema
(Logical View)

Internal Schema
(Physical View)

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

Entity Relationship Model :


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

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

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

Relationship/ Relationship Sets


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

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

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

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

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

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

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

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

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

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

E-R Model uses a graphical notation for


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

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

Proposed by E.F.Codd on the mathematical


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

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

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

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

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

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

• Operations produce a new relation as a result.

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

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

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

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

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

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

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

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

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

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

• Class hierarchy and inheritance:


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

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

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

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

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

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

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

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

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

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

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

Normalization : Process of refining the E-R


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

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

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

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

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

Relations that contain redundant information may


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

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

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


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

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

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

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

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

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

Ist Normal Form

ecode dept projcode hours hod


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

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

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

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

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

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

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

dept hod ecode dept


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

Table in 3NF

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

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

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

UNF To BCNF

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

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

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

Fourth Normal Form ( 4 NF)


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

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

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

Fourth Normal Form ( 4 NF)

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

Fifth Normal Form ( 5 NF)


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

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

Fifth Normal Form ( 5 NF)

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

Fifth Normal Form ( 5 NF)

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

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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
138
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to Databases
(Continued)
➢ Rule 9: Logical Data Independence
How a user views data should not change when the logical structure (tables structure) of the
database changes. This rule is particularly difficult to satisfy. Most databases rely on strong ties
between the user view of the data and the actual structure of the underlying tables.
➢ Rule 10: Integrity Independence
The database language (like SQL) should support constraints on user input that maintain database
integrity. This rule is not fully implemented by most major vendors. At a minimum, all databases do
preserve two constraints through SQL.
• No component of a primary key can have a null value. (see rule 3)
• If a foreign key is defined in one table, any value in it must exist as a primary key in another table.

➢ Rule 11: Distribution Independence


A user should be totally unaware of whether or not the database is distributed (whether parts of the
database exist in multiple locations). A variety of reasons make this rule difficult to implement;
➢ Rule 12: Non subversion Rule
There should be no way to modify the database structure other than through the multiple row
database language (like SQL). Most databases today support administrative tools that allow some
direct manipulation of the data structure.

For Internal Use Only


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

Results
Results

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

For Internal Use Only


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

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
141
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DML Statements
➢ SELECT
• Syntax :
select {[alias.]column name}[, {[alias.]column name}[, …]]
from {database name}.{object owner}.{table name} [[{alias 1}]
[inner join {database name}.{owner name}.{table name} [{alias 2}]
on {alias 1}.{column name} = {alias 2}.{column name}[{next join}]]
[where {constraint condition}[and {constraint condition}[…]]]
[group by {column [list]}
[having {constraint condition}]]
[order by {column [list]}][{union}{next select statement}]
• Example:
Select empno, empname
from employee
group by dept
order by empno

For Internal Use Only


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
142
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DML Statements
(Continued)
➢ INSERT
• Syntax :
insert [into] {database name}.{owner}.{table name}
({column name}[,{column name}[,…}})
values
({value or variable}[,{value or variable}[,}…]]
• Example:
insert Parts.dbo.TB_TOASTER (TOASTER_ID,
MANUFACTURER_ID, NAME, NOTES)
values
(1,1, 'spring', 'cross sell handle latch')

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

Types of Integrity and Constraints


➢ Domain
• DEFAULT
• CHECK

➢ Entity
• PRIMARY KEY
• UNIQUE

➢ Referential
• FOREIGN KEY
• CHECK

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

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

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

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

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

For Internal Use Only


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

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

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

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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

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

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

Executing Stored Procedures with Input


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

➢ Passing Values by Position


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

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

CREATE
CREATE PROCEDURE
PROCEDURE dbo.mathtutor
dbo.mathtutor
Creating
Creating Stored
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
Executing Stored
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
Results of
of Stored
Stored
Procedure
Procedure
The
The result
result is:
is: 30
30
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
195
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Stored Procedures
(Continued)
Explicitly Recompiling Stored Procedures

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

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

➢ Increase SQL Server Functionality


➢ Are Programmed Using Open Data Services API
➢ Can Include C and C++ Features
➢ Can Contain Multiple Functions
➢ Can Be Called from a Client or SQL Server
➢ Can Be Added to the master Database Only

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

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

➢ RETURN Statement Exits Query or Procedure


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

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

For Internal Use Only


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

title
title
title_no
title_no title
title author
author synopsis
synopsis
11 Last
Lastof
ofthe
theMohicans
MohicansJames
JamesFenimore
FenimoreCooper
~~~
Cooper~~~
22 TheTheVillage
VillageWatch-Tower
Kate
KateDouglas
Watch-Tower 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
Lastof
ofthe
theMohicans
MohicansJames
JamesFenimore
FenimoreCooper
Cooper User’s
User’sView
View
The
TheVillage
VillageWatch-Tower
Kate
KateDouglas
Watch-Tower DouglasWiggin
Wiggin
Poems
Poems Wilfred
WilfredOwen
Owen

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

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

➢ Restrictions on View Definitions


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

For Internal Use Only


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

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

For Internal Use Only


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

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

➢ Dropping Views

DROP
DROP VIEW
VIEW UnpaidFinesView
UnpaidFinesView

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

For Internal Use Only


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

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

For Internal Use Only


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

For Internal Use Only


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

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

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

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

➢ Altering and Dropping Triggers


• Changes the definition without dropping the trigger
• Can disable or enable a trigger

USE
USE Northwind
Northwind
GO
GO
ALTER
ALTER TRIGGER
TRIGGER Empl_Delete
Empl_Delete ONON Employees
Employees
FOR DELETE
FOR DELETE
AS
AS
IF
IF (SELECT
(SELECT COUNT(*)
COUNT(*) FROM
FROM Deleted)
Deleted) >> 66
BEGIN
BEGIN
RAISERROR(
RAISERROR(
'You
'You cannot
cannot delete
delete more
more than
than six
six employees
employees at
at aa time.',
time.', 16,
16, 1)
1)
ROLLBACK TRANSACTION
ROLLBACK TRANSACTION
END
END

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

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

INSERT statement to a table with an INSERT Trigger Defined


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

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

TRIGGER Actions Execute


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

DELETE Statement to a table with a DELETE Trigger Defined


Trigger Actions Execute
Categories
Categories
DELETE
11 Statement to
CategoryID a Table with
CategoryName
CategoryID
CategoryName a DELETE
Description
Description Picture
Picture
DELETE
DELETE Categories Products
Products
Statement
WHERE
Defined
Categories 11 Beverages Soft
BeveragesSoft drinks,
drinks, coffees…
0x15…
coffees…
0x15…
WHERE ProductID
Discontinued
ProductID … …
Discontinued
CategoryID
CategoryID == 44
22 Condiments Sweet
Condiments
Sweet and savory…
and savory … …
0x15…

0x15…
22 33 Confections
Confections 11
Desserts,
Desserts, 00
candies,
candies,0x15…

0x15…

DELETE Statement Logged 2
4 Dairy ProductsCheeses 1
00 0x15…
USE Northwind 2
USE Northwind 33 00
CREATE
33 TRIGGER
CREATE TRIGGER Category_Delete
Category_Delete
Trigger
ON Actions Executed
ON Categories
Categories 44 00
FOR
FOR DELETE
DELETE
AS
AS
UPDATE
UPDATE PP SET
SET Discontinued
Discontinued == 11
FROM
FROM Products
Products ASAS PP INNER
INNER JOIN
JOIN deleted
deleted AS
AS dd
ON P.CategoryID
ON DELETE == d.CategoryID
statement
P.CategoryID logged
d.CategoryID
Deleted
Deleted
44 Dairy
Dairy Products
Cheeses
Cheeses 0x15…
Products 0x15…

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

Create a View That Combines Two or More Tables


CREATE
CREATE VIEW
UPDATE is Made
VIEW
toCustomers
INSTEAD OFAS
Customers
11 View
the Trigger
AS Can Be on a Table or View
SELECT *
SELECT *
FROM
FROM CustomersMex
CustomersMex Customers
INSTEAD
UNION OF
UNION Customers
SELECT
trigger
SELECT **
directs the CustomerID
CompanyName
CustomerID
CompanyName Country
Country Phone
Phone …

2
Theupdate
Action That
2 to
FROM
FROM base Initiates
CustomersGer
CustomersGer
the ALFKI theFu…
ALFKIAlfreds
ALFKI Alfreds Trigger
Germany
Germany
Fu…
Germany Does NOT
030-0074321~~~
030-0074321
~~~ Occ
table ANATR
ANATRAna
Ana Trujill…
Mexico
Mexico (5)
Trujill… (5) 555-4729
555-4729~~~
~~~
ANTON
ANTONAntonio
Antonio M…
M…Mexico
Mexico (5)
(5) 555-3932
555-3932~~~
~~~
Original Insert to
Allows 33 Updates to Views Not Previously Updateable
the Customers
CustomersMex
CustomersMex
View CompanyName
CustomerIDDoes
CustomerID Not Country
CompanyName Country Phone
Phone
CustomersGer …

CustomersGer
Occur Ana Trujill…Mexico
ANATR (5)CompanyName
555-4729~~~
CustomerID Country Phone …
ANATRAna Trujill…Mexico (5)CompanyName
CustomerID555-4729~~~ Country Phone …
ANTON
ANTONAntonio
Antonio M…
M… Mexico
Mexico(5)
ALFKI 555-3932
(5)Alfreds
555-3932 ~~~
Fu…Germany
~~~
Germany030-0074321~~~
ALFKI Alfreds Fu…Germany 030-0074321
~~~
CENTC Centro Co… Mexico
CENTCCentro Co…Mexico (5)
BLAUS 555-3392
(5)Blauer
555-3392
Se…~~~
~~~
Germany0621-08460
BLAUS Blauer Se…Germany 0621-08460~~~
~~~
DRACD
DRACDDrachenb…
Drachenb… Germany
Germany0241-039123~~~
0241-039123
~~~

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

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

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

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

CREATE
CREATE TRIGGER
TRIGGER BackOrderList_Delete
BackOrderList_Delete
ON
ON Products
Products FORFOR 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
UnitsInStock
ProductID …
……
UnitsInStock … ProductIDUnitsOnOrder
UnitsOnOrder…
ProductID …
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
Trigger Deletes
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
IFCannot
IF (Select Be(*)
(Select Count
Count Deleted
(*)
FROM
FROM [Order
[Order Details]
Details] INNER
INNER JOIN
JOIN deleted
deleted
ON [Order Details].ProductID = deleted.ProductID
ON [Order Details].ProductID = deleted.ProductID
)) >> 00
ROLLBACK
ROLLBACK TRANSACTION
TRANSACTION
DELETE statement Trigger code Transaction
executed on Product checks the Order Details rolled back
table
Products table Order
Products OrderDetails
Details
ProductID
UnitsInStock
ProductID …
……
UnitsInStock … OrderID
ProductID
OrderID UnitPrice
ProductID Quantity
UnitPrice Discount
Quantity
Discount
11 15
15 10522
10522 10
10 31.00
31.00 77 0.2
0.2
22 0
10
10 10523
10523 22 19.00
19.00 99 0.15
0.15
33 65
65 10524
10524 41
41 9.65
9.65 24
24 0.0
0.0
44 20
20 10525
10525 77 30.00
30.00

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

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

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

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

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

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

DECLARE @tablename nvarchar(256)


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

CLOSE tnames_cursor
DEALLOCATE tnames_cursor

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

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

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

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

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

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

Target Audience

Analysts
Designers
Reviewers

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

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

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

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

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

0..* Action Servlet Action Classes Controller Layer


0..*

Respondant
Evaluator
Service Locator
evaluates
respondsto

Value Objects
0..*
.. *
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
1
Objects Objects Objects Objects Objects
0..*
1
Data Data Data Data Data
Access Access Access Access Access
Data Access Layer
creates
Section 0..* 0..* Objects Objects Objects Objects Objects
1 1 has 0..*

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

Buyer

Subsection

Object
Analyst
Oriented
Architect
Thinking

Buyer Respondant
Evaluator

createSurvey() respondToSurvey()
evalua teResponse()
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( )

addSubs ection() 0..1


0..* 0..*
addQuestion()
load( )
1 Ques tion 1 0..* Answer
has

0..*
0..*
Subsection
0..1
addQuestio n()

Developer Designer

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

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

Manager
Review Employee
Creates

Complete

InfraTeamMember ServiceRequest

JobRequest SoftwareRequest HardwareRequest

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

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

• How can the requirements be met using the


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

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

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

Main program/subroutine Object-oriented

Componen modules objects


ts

Connector Procedure calls messages


s

Properties Hierarchical control main Main program instantiates


program objects

Single thread of control Parallel threads of control


possible
Execution from start to end
Execution never ends
Global data on
files/databases Objects responsible for own
data
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
245
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Paradigm Shift – Procedural Vs Object Oriented
(cont…)

• Drawbacks in procedural paradigm


• Takes no account of evolutionary change
• system characterized by a single function - a questionable
concept
• does not encourage reusability
• based on functional mindset, data structure aspect often
neglected
Procedural Mindset Object-oriented Mindset
• Shift of mindset
What does the system do? Of what objects is the system
composed?
What is its purpose?How do I design How can I model the system
and code to achieve this functional dynamically using objects, their
behaviour? behaviour, and other objects they
use?

Focus on algorithms Algorithmic functions deferred

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

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

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

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

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

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

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

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

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

• Functional approach
• Changing requirements
• An alternative

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

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

How well will the


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

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

Implementing this approach would require


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

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

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

Impact on functional solution?


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

Impact on alternative solution?


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

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

People are responsible for themselves


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

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

In the alternative solution


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

This is the structure provided by Object-


Orientation
• Objects are responsible for themselves
• Objects tell each other to do things at a conceptual level

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

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

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

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

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

• Implementation
 Packets of code and data

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

• Have a type
 Name is a string, address is a string, GPA is a float
• Define the state of an object
 An object might behave differently depending upon its state

One object may have another object as an


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

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

Calling an operation could change the state of the object


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

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

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

A class is a template for a set of objects


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

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

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

A sneak peak Here’s some


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

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

s1:Student s2:Student s3:Student


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

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

A sneak peak Same thing in


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

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

s1:Student s2:Student s3:Student


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

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

Inheritance is a relationship between classes Generalization

• Subclass may inherit from a superclass


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

A subclass can override superclass operations


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

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

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


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

StudentList slist = new StudentList();


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

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

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

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

Subclasses will usually override operations


• Implement their own specialized behavior
• PayingStudents get to the next class differently than
KeaneStudents
 PayingStudents get directions and go directly to next class
 KeaneStudents help collect evals and then go to the next class

Inheritance provides the structure to treat all kinds


of students the same
• What we think is a generic Student might actually be a
subclass
Student s = slist.getNextStudent();
s.goToClass();

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

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

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

StudentList slist = new StudentList();


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

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

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

:StudentList

:Student s2:KeaneStudent Collects evals


goToClass() first

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

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

A new type of student


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

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

StudentList slist = new StudentList();


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

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


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

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

In many cases, the base class can not


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

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

Most base classes will have at least one abstract


method

Student
No behavior
implemented.
goToClass()
AuditStudent

goToClass()

PayingStudent KeaneStudent

goToClass() goToClass()

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

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

Classes define different levels of visibility for their


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

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

• Well encapsulated objects minimize the impact of change


 Clients should be ignorant and unaffected

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

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

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

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

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

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

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

Abstraction Instantiation
Service
Request
Software Hardware
Job Request email Request
Request Request

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

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

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

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

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

©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: 6748Employee Id: 2343Employee Id: 5436 Name: Deepak Name:Raj
Name:Riya

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

Object Identity Behaviour State

Employee Employee Id: Join, Project


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

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

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

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

Base Unit Keyboard


Monitor

Data
Hard Disk Motherbo Power
Cables
ard Supply

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

Hardware Service Software Service


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

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

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

COE – Current Technologies


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

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

XML Web
Services
Integrate business
Authentication applications and
Scheduling processes
Notification

Back Office
Heterogeneous
application and
server
infrastructure

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

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


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

A specific software framework


Includes a common runtime

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

Programming model for .NET


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

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

Common Language Runtime


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

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

• CLR manages code execution at runtime


• Memory management, thread management, etc.

Common Language Runtime

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

• Object-oriented collection of reusable types


• Collections, I/O, Strings, …

.NET Framework (Base Class Library)

Common Language Runtime

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

• Access relational databases


• Disconnected data model
• Work with XML

ADO .NET and XML

.NET Framework (Base Class Library)

Common Language Runtime

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

ASP .NET Windows


Web Forms Web Services
Forms
Mobile Internet Toolkit

ADO .NET and XML

.NET Framework (Base Class Library)

Common Language Runtime

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

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


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

ADO .NET and XML

.NET Framework (Base Class Library)

Common Language Runtime

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

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

ADO .NET and XML

.NET Framework (Base Class Library)

Common Language Runtime

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

C++ C# VB Perl J# …

Common Language Specification

Visual Studio .NET


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

ADO .NET and XML

.NET Framework (Base Class Library)

Common Language Runtime

Operating System

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
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# …

Common Language Specification


Open Language
Specification

Visual Studio .NET


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

ADO .NET and XML

.NET Framework (Base Class Library) XML-based


data access
Common Language Runtime

Operating System

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

Manages running code – like a virtual machine


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

Fine-grained evidence-based security


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

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

Code that targets the CLR is referred to as


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

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

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

 IL (MSIL or CIL) – Intermediate Language


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

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

.NET languages are compiled to an


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

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

All .NET languages have the same primitive data types.


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

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

Languages provided by Microsoft


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

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

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

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

COE – Current Technologies


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

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

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

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

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

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

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

The first component oriented language in


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

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

C# is the first “component oriented” language


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

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

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

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

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

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

using System;

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

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

Namespaces
• Contain types and other namespaces
Type declarations
• Classes, structs, interfaces, enums,
and delegates
Members
• Constants, fields, methods, properties, indexers, events,
operators, constructors, destructors
Organization
• No header files, code written “in-line”
• No declaration order dependence

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

using System;

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

public void Push(object data) {


top = new Entry(top, data);
}

public object Pop() {


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

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

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

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

i 123

s "Hello world"

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

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

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

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

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

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

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

Like classes, except


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

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

interface IDataBound
{
void Bind(IDataBinder binder);
}

class EditBox: Control, IDataBound


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

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

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

enum Color: byte


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

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

Object oriented function pointers


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

delegate void MouseEvent(int x, int y);

delegate double Func(double x);

Func func = new Func(Math.Sin);


double x = func(1.0);

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

object

Stream Hashtable int double

MemoryStream FileStream

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

What defines a component?


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

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

public class Button: Control


{
private string caption;

public string Caption {


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

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

How do you associate information with types


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

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

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

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

First class user-defined data types


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

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

Problem in most languages


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

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

class Base // version 2


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

class Derived: Base // version 2b


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

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

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

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

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

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

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

ToolBox

Soluition
Explorer

Form Designer

Properties

Code Defnision Window

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

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

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

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

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

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


case)
• The System.Console class contains a WriteLine method that can be
used to display a string to the console
• The Console class is contained in the namespace System
• Hello Class will be part of namespace HelloWorld

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

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

WriteLine method is used to print values of


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

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

Thru Project -> <Proj Name> Properties menu


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

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

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

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

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

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

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

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

Categories (discussed later)


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

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

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

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

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

bool 1 byte System.Bool true or false

char 2 byte System.Char Unicode 16 bit character

short 2 byte System.Int16 Signed

ushort 2 byte System.Uint16 Unsigned

int 4 byte System.Int32 Signed

uint 4 byte System.Uint32 Unsigned

float 4 byte System.Single Signed, 7 digit precision

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

decimal 8 byte System.Decimal Signed, 28 digit precision


Used in Financial calculations
long 8 byte System.Int64 Signed

ulong 8 byte System.Uint64 Unsigned

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

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

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

Variables can take an initial value


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

A value must be assigned to a variable


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

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

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

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

Each type has its own conversion rule, may result in


data loss if used improperly

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

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
370
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Formatting numeric types
Currency
Console.Write("{0:C}", 2.5); // $2.50
Console.Write("{0:C}", -2.5); // ($2.50)
Decimal
Console.Write("{0:D5}", 25); // 00025
Scientific
Console.Write("{0:E}", 250000); // 2.500000E+005
Fixed Point
Console.Write("{0:F2}", 25); // 25.00
Console.Write("{0:F0}", 25); // 25
General
Console.Write("{0:G}", 2.5); // 2.5
Number
Console.Write("{0:N}", 2500000); //2,500,000.00
HexaDecimal
Console.Write("{0:X}", 250); // FA

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
371
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
String to numbers
static void Main(string[] args)
{
int i;
//read from keyboard
Console.WriteLine(“Enter a value for I : ”);
string s = Console.ReadLine();
//Convert to integer
i = System.Int32.Parse(s);
Console.WriteLine("i = {0}", i);

Console.ReadLine(); //Close terminal


}

ReadLine reads the string from Keyboard , Type 100 and


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

General form
const datatype Constant-name = value;

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

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

LayerType layer1 = LayerType.opaque;


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

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


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

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

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

Enumeration type variables can be assigned only values


defined with in the enum leading to Strong type
checking

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

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

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

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

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

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

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

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

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

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

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

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


relational expressions
must be true

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


expression may be true

not !(x == 3) true. Unary operator.


Works with one logical
/ relational
expression

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

The following sample accepts a char from the user and


prints the type of the character

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

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

• If we need to change the program to check for


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

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

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

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

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

//Small cup costs 25 cents


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

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

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

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

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
391
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Ternary Operator
A conditional operator Involves 3 operands
Syntax
Conditional Expression ? expr1 : expr2

Returns expr1 if condition is true expr2 otherwise

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

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
392
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Bitwise operators
& Binary, Bitwise AND For (u)int and (u)long operands bitwise
AND is done. For bool operands it is
conditional operation
| Binary, Bitwise OR Same as above

^ Binary, Bitwise XOR Same as above

~ Unary, Bitwise NOT Only for (u)int, (u)long

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

public void addFormat(int formatConst)


{
format = format | formatConst;
}

public bool checkFormat(int formatConst)


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

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

A TextFormat object could be defined with a combination of


Bold, italic and underline

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

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

Condition is evaluated before the loop starts


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

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

This loop prints numbers from 1 to 5 when n


becomes 6 loop is exited and program ends

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

Loop executes atleast once


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

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

Same as while loop sample


Executes once even if n is initialized to 6

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

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

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

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

This sample is the same as while and do samples


Prints numbers from 1 to 5

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

break Used inside loops to exit out. Seen the use of


break with switch statement
continue Skip part of loop and go to top of loop again

goto Jump to any label. Including case


expression
return Exit out of a function.
(will be covered in return 0; inside Main function ends the
function topic) program.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
404
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
break sample
static void Main(string[] args)
{
string s = "Copy till the end and look for ?";
StringBuilder sb = new StringBuilder();
int i = 0;
while (s[i] != 'g')
{
sb.Append(s[i++]);
if (i == s.Length )
break; //exit loop if you have copied last char
}
Console.WriteLine(sb);
}

break terminates the closest enclosing loop in case of


nested loops

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

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

When using a continue statement with while or do


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

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

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


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

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


{
//obtain an array element to print
Console.WriteLine("Array[{0}] = {1}", i, evenArray[i]);
}
}
Accessing an element of an array
ArrayName[n] where n is between 0 and array length -1

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
409
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Array Initialization
Arrays can be initialized with constant values
The following 3 are equal
int[] myArray = new int[5] {1, 3, 5, 7, 9};

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

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

However For an unallocated array


int[] myArray;

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

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

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

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

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

For the previous sample


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

Similarly
myArray.GetUpperBound(1)
gives 1

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

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


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

What does this program do?


Add code to print the contents like a matrix.

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

• Declare a jagged array with 3 arrays


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

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

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

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

For each iteration of statements the variable


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

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

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

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

The two options of debugging are


1. Debug locally
2. Debug remotely

You can debug assemblies hosted by SQL Server, and JavaScript


hosted by Internet Explorer

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

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

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

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

you can view both local and global variables.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
421
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Debugging Features In Visual
Studio 2005
There are three ways to start a debugging session in Visual
Studio.NET
The “Start” and “Step Into”
commands will both launch
your application and begin
a debugging session.

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

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


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

The Attach command


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

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

ASP.NET developers won’t be


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

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

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

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

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

The other way to set a


breakpoint is add break
point to function

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

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

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

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

You can also


combine logical
clauses to set a
condition

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

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

There are hundreds


of macros by
default available for
specific task

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

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

Best suted for


handling bugs in code

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


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

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

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

Step Out command, is used


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

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

You can add a variable to


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

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

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

Use the Server Explorer to select any SQL


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

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

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

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

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

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
437
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Features of Visual Studio Class
Designer
1. The Visual Studio Class Designer lets you visualize the
structure of classes and other types, and through these
visual representations edit their source code.
2. Changes made to the class diagram are immediately
reflected in code, and changes made to the code
immediately affect the appearance of the designer.
3. Complex CLR types can be configured visually .
4. Visual Studio Class Designer lets you to easily refactor the
code.
5. You can easily rename identifiers and override methods
6. You can automatically generate classes and structures, and
implement interfaces by automatically generating stubs.
7. Class Designer also serves as a communication tool by
letting you easily communicate areas of your code base to
colleagues
8. Display reports in HTML pages or PowerPoint presentations.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
438
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Components of Visual Studio 2005
Class Designer

The Class View


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

Class Details Window

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

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

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

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

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

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


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

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


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

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

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

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

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

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


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

Class diagrams for documentation: Class diagrams can be used to


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

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

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

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

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

attributes & base-list are deferred to a later time

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

• static variables can be accessed without creating an


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

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

• public , private and static mean the same as that


of variables
Again this syntax is also not complete

Let us explore creating functions in the following


sections …

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

From the previous slide


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

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

public static int Main(string[] args)


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

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
451
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Function types…
Class SimpleInterest {
public static float CalculateInterest(
float amount,
int year,
float rate)
{
float interest = (amount * year * rate)/100;
return interest;
}
static void Main(string[] args)
{
float intamount = CalculateInterest(1000F, 1, 7.25F);
Console.WriteLine("Interest = {0:F2}", intamount);
}
}
Static function – No object of type SimpleInterest need to be created
in Main

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
452
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Parameter mechanism
• amount, year and rate are called formal parameters
• Formal parameters are declared with appropriate type
• The values 1000F, 1 and 7.25F or are the actual parameters
• The values of actual parameters are copied into the formal parameters
and the statements of the function body are executed
• Actual parameters could be passed as constant values or variables
containing input values
• Only the result is returned, the values are not copied back to formal
parameter (Pass By value)
• DIY :
Declare 3 variables inside Main and intialize them to
1000F, 1 and 7.25F respectively. Pass them as
parameters to the function.Try to change the value of
amount or year or rate inside the function and print the
values in main after calculating interest. Check whether
they are changed

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

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


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

• The function does not return a value – void


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

static void Main(string[] args)


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

This mechanism is one way; the values are passed


from a formal parameter to the actual parameters,
opposite to pass by value mechanism.

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

Ref parameters are used as two way parameters


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

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

static void Main(string[] args)


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

This mechanism is two way; the values are passed


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

Write a method that accepts a list of numbers and


computes sum and average

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

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

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

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

• Try creating 2 kid objects one by invoking the


constructors with parameters and other without
parameters. Print the objects and check the values

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

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

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

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

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

Now age for a Kid object could be set using


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

Demo With Visual Studio


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

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

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

C# 2.0 allows you to specify different visibility


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

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


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

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

public class MyClass


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

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
475
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Property visibility
Considerations
1. First, the visibility qualifier you apply on the set or
the get can only be a stringent subset of the visibility
of the property itself.
2. If the property is public, then you can specify
internal, protected, protected internal, or private.
3. If the property visibility is protected, you cannot
make the get or the set public.
4. you can only specify visibility for the get or the set,
but not both.

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

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

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

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

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

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

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

public partial class MyClass{


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

Partial type support is available for classes,


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

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

The partial modifier is not available on delegate


or enumeration declarations.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
484
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Partial Class
Support
C# 2.0 supports partial types as follows: when the
compiler builds the assembly, it combines from the
various files the parts of a type and compiles them into a
single type in Microsoft intermediate language (MSIL).
The generated MSIL has no recollection which part came
from which file. Just like in C# 1.1 the MSIL has no record
of which file was used to define which type.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
485
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Advantages of Using
Partial Class
In ASP.NET 2.0 we can use partial classes for the
code-beside class (the evolution of codebehind),
storing the machine-generated part of the page
separately.
In Windows® Forms partial classes are used to
store the visual designer output of the
InitializeComponent method as well as the member
controls in a separate file thus giving code clarity.
Partial types also enable two or more developers to
work on the same type while both have their files
checked out from source control without interfering
with each other.

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

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

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

At compile time, attributes of partial-type


definitions are merged. For example, the
following declarations:

[System.SerializableAttribute]
partial class Kid { }

[System.ObsoleteAttribute]
partial class Kid { }

are equivalent to:

[System.SerializableAttribute]
[System.ObsoleteAttribute]
Partial class Kid{}

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

The following are merged together from all the partial-


type definitions:
XML comments

interfaces
generic-type parameter attributes
class attributes
members

For example, the following declarations:

partial class Kid : Icomparable, Icomparer { }


partial class Kid : IEnumerator { }
are equivalent to:

class Kid : Icomparable, Icomparer , IEnumerator { }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
489
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Constraints for a
partial Class
All partial-type definitions meant to be parts of the same
type must be modified with partial.

The partial modifier can only appear immediately before


the keywords class, struct, or interface.

All partial-type definitions meant to be parts of the same


type must be defined in the same assembly and the
same module (.exe or .dll file). Partial definitions cannot
span multiple modules.

The class name and generic-type parameters must


match on all partial-type definitions.

Generic types can be partial.

Each partial declaration must use the same parameter


names in the same order.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
490
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Partial Types
The following keywords on a partial-type definition are optional,
but if present on one partial-type definition, cannot conflict with
the keywords specified on another partial definition for the same
type:
public
private
protected
internal
abstract
sealed
base class
new modifier (nested parts)
generic constraints

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

public partial class Kid


{
private string name;
private int age;
public Kid(string x, int y)
{
this.name = x;
this.age = y;
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
492
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Partial Class Example
public partial class Kid
{
public void PrintKid()
{
System.Console.WriteLine(“The Kid is {0},
{1}", name, age);
} }
class TestCoOrds
{
static void Main()
{
CoOrds kidObj = new CoOrds(Mickey, 15);

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

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

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

Under C# 1.1, if you want to prevent people from instantiating


objects of your class then you can provide a private default
constructor.
Without any public constructors, no one can instantiate objects
ofpublic
yourclass
class:
Kid
{
private Kid()
{
}
static public object CreateObject()
{...}

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

It is still up to you to enforce the fact that only static


members are defined on the class.

public class Kid


Have You Noticed ,C# compiler will
{ still allow you to add instance
private Kid() members, although they could never
be used.
{
}
static public object CreateObject()
{...}

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

C# 2.0 adds support for static classes by allowing


you to qualify your class as static
The C# 2.0 compiler will not allow
public static class Kid you to add a non-static member to
{ a static class

private Kid()
{
}

static public T CreateObject<T>()


{...}
What else…
}

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

1. C# compiler will not allow you to create


instances of the static class as if it were an
abstract class.
2. You cannot derive from a static class. It's as
if the compiler adds both abstract and sealed
to the static class definition.
3. You can define static classes but not static
structures, and you can add a static
constructor.

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

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

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Structures – struct
• Are value types
• All C# datatypes have a struct equivalent (already seen)
• Are similar to classes and have
• Constructors
• Properties
• Methods
• Cannot initialize member data
• Do not support inheritance (Discussed later)
• No default constructor provided
• Cannot have destructors (not a reference type)
• Are implicitly derived from object (like any other value
type)
• Used to represent light weight objects that have a value
semantics
• Complex numbers, point, rectangle…

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
500
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Struct - sample
public struct Location
{
private int xCoord;
private int yCoord;

public Location(int x, int y)


{
this.xCoord = x;
this.yCoord = y;
}
public int x
{
get { return this.xCoord; }
set { this.xCoord = value; }
}
public int y
{
get { return this.yCoord; }
set { this.yCoord = value;}
}
}

This shows a struct which is similar to a class which has


Constructors, encapsulated members and properties
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
501
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Structs …
Creating a Location variable
Location Loc1 = new Location(10,10);
We can also create a struct variable without new (
a characteristic of value type)

But with this sample


Location Loc2;
Loc2.x = 10; //error
The error is because Loc2 is not initialized. Not
only properties, methods also wont work.

If we don’t want to use new to create struct


variables then the struct data members must
have to be initialized directly

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
502
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Structs… exercise & Learn
Fix the Location struct so that the following code works
static void Main(string[] args)
{
Location loc2;
loc2.xCoord = 50; //Please see note below
loc2.yCoord = 100; //Please see note below
loc2.printLocation(); //A method to be added to Location
}
Note :
All data members of struct need to be initialized in the calling
code before using it
Compact the code by removing the properties. Data members
have been made public. So we don’t need encapsulation
and constructors also not needed.
Remember the implications of coding while deciding on struct
Vs class. For Object oriented behavioral semantic objects
use classes
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
503
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Structs sample code
public struct Location
{
public int xCoord;
public int yCoord;
public Location(int x, int y)
{
this.xCoord = x;
this.yCoord = y;
}
public int x
{
get { return this.xCoord; }
set { this.xCoord = value; }
}
public int y
{
get { return this.yCoord; }
set { this.yCoord = value;}
}
public void printLocation()
{
Console.WriteLine("x = {0}, y = {1}", this.xCoord,
this.yCoord);
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
504
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Boxing & Un-Boxing
Value type variables are short lived and created in stack
Reference type variables are created in heap (Global
memory)
Boxing : Converting a value type into a reference type
Unboxing : Converting reference type to a value type
static void Main(string[] args)
{
int i =123;
object o = i; //boxing
int j = 0;
if (o is Int32) //Checking the type using is operator
{
j = (int)o; //Unboxing
}
Console.WriteLine(" j = {0}", j); //prints 123
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
505
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Boxing & Un-Boxing pitfalls
When we pass value type variable into a method which
expects an Object type as parameter
Boxing takes place automatically and a temporary object is
created

The formal parameters and local variables of a method are


created in stack only if they are value types
For reference type parameters the variable containing the
reference of the temp object is created in stack as per
above rule
But the temporary object itself is created in heap

This temporary object need to be Garbage collected and a


lot of such empty boxes created with the careless coding
can stress the memory and affect performance

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

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

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
1. Inheritance
2. Abstract methods and Classes.
3. Multiple Inheritance.
4. Operator Overloading and Type Conversion.
5. Interfaces.
6. Collection Interfaces.
7. Nested Classes.
8. Indexers.
9. CallBacks
1. Delegates
2. Events
10.Exception Handling.

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

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

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Inheritance
Objectives :
• To build a family of related classes
• Code reuse amongst related objects
How ?
• Find Is-a relation ship
• Generalization
• Find Common things in related entities
• Create a base class with common attributes and behaviors
• Mammal is general class for Dog, Whale and Human
• Specialization
• Used mostly for adding entities later into the system
• Find the base class to inherit from and add special attributes &
behavior
• For a scalable design both Generalization and
Specialization must be used
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
510
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Simple Inheritance - Sample
Assume a typical Payroll application with an
Employee class
class Employee
{
protected int EmployeeID;
protected string FullName;
protected decimal BaseSalary;
public Employee() { }
public Employee(int id, string fullName, decimal baseSalary)
{
this.EmployeeID = id;
this.FullName = fullName;
this.BaseSalary = baseSalary;
}
public decimal computePay()
{
return this.BaseSalary;
}
public string Name //Only one property shown for simplicity
{
get { return this.FullName; }
}
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
511
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Base Class Explained
• Protected members could be accessed only in
the derived classes, unrelated classes cannot
access them
• Only Name property is shown, it is always
better to have other read-only properties as
well
• A default constructor is provided here, Though
it is not a good practice
• We will learn how to get rid of that when we
get more knowledge in inheritance

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

Client

Child Class Unrelated Class

Component

Public

Protected

internal

Private
Child Class Unrelated Class

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
513
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Simple Inheritance - Sample
Now a Contractor class inherited from Employee
The pay for the contractor is based on overtime
(Specialization)
class Contractor : Employee
{
public int OverTime; //Additional Attribute
public decimal Rate; //Additional Attribute
public Contractor(int id, string fullName,
decimal baseSalary, int overTime, decimal rate)
{
EmployeeID = id; //Access base class Members
FullName = fullName; //Access base class Members
BaseSalary = baseSalary; //Access base class Members
OverTime = overTime;
Rate = rate;
}
public decimal computePay()
{
return (BaseSalary + OverTime * Rate);
}
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
514
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Simple Inheritance - Sample
Now the PayRoll Class :
class PayRoll
{
public static void Main(string[] args)
{
ArrayList Employees = new ArrayList();
Employees.Add(new Contractor(100, "Andrew Troelson",
1500.00M, 20, 25.00M));
Employees.Add(new Contractor(101, "Jesse Liberty",
1400.00M, 30, 20.00M));
Employees.Add(new Contractor(102, "Juval Lowy",
1700.00M, 10, 30.00M));

foreach (Contractor w in Employees)


{
decimal pay = w.computePay();
Console.WriteLine("{0} -> {1:C}", w.Name, pay);
}
}
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
515
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
PayRoll Explained
• The ArrayList “Employees” is the collection to
hold the 3 contractors
• Contractors are created and added to the virtual
organization
• For each contractor the pay is computed and
printed

This program just runs fine and prints the correct


output except for 1 warning ……………

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
516
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Revelation #1 : Bad Construction
• We saw during our class construction that default
constructors put the object in an inconsistent state
• Why do we have it here then?
• Try adding a
Console.WriteLine(“Hello, I am an Employee”); Statement
to the Employee’s default constructor
• You see this message getting printed while you create 3
of those Contractors
• So the derived class constructor calls the base class
constructor
• If you remove the default constructor you get an error
message from the compiler
• The best way is to invoke the non default base class
constructor from the non default derived class
constructor yourself and get rid of the default constructor
from the Employee class
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
517
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Revelation #1 : Bad Construction…
• How to do?
• Similar to invoking a non default constructor from a
default constructor by passing default state values
• But with a different keyword, change the code as below
public Contractor(int id, string fullName,
decimal baseSalary, int overTime,
decimal rate) : base ( id, fullName, baseSalary)
{
this.OverTime = overTime;
this.Rate = rate;
}
• Now when you run the Hello message is not printed
anymore
• Delete the default constructor from the Employee
• RIP

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

• C# Compiler tells you that you need to add


keyword new to the computePay method because it
hides the Employee.computePay method
• Before learning what this new keyword is, let us see
some design aspects
• You will not have only one employee type in the organization, if
you have then inheritance may not be required
• Even if you have only one type for now you don’t know about
tomorrow
• To worsen the IS departments life a Manager class is added to
the Organization whose pay depend upon their performance
bonus
• Now you will be creating few Manager objects and adding them
to the ArrayList
• And change the foreach statement to
foreach (Employee w in Employees)
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
519
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Revelation #2 : Inheritance taught by C# compiler
• If we try to run even without creating a Manager class and
adding Manager objects, but changing the foreach statement
alone
• Compiler warning is still there (What is this new?)
• But to our horror the payroll prints BaseSalary 
• The lesson is that
• When you inherit the computePay method but changing the way it
calculates the pay
• The method in the base class must be marked virtual and the
derived class method must be marked override
• Change the signatures to
• Employee class
public virtual decimal computePay()
• Contractor class
public override decimal computePay()
• Now this in Main will print the correct pay for the contractors
foreach (Employee w in Employees)
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
520
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Revelation #2 : Inheritance taught by C# compiler

• Now happy compile and happy run


• Exercise
Make changes as per the revelations Add a manager
class and add managers to your organization and
compute pay
After adding Manager type you have 2
implementations of computePay method that is
invoked using a base class reference
• Still it invokes the appropriate types
calculations
• This is achieved using Virtual/override pair
• In OO terms this is called POLYMORPHISM
• Many forms of one function

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

• In Continuation to the Compiler warning of the


previous section …
• Scenario #1
• A method available in base class (Employee) as
public void display()
{
Console.WriteLine("{0}, {1}, {2}",
EmployeeID, FullName, BaseSalary );
}
• This is supposed to be available thru the objects of type
Contractor or Manager
• So, if you have a function in Contractor with similar signature
which prints ID, Name, Basesalary, extra pay, total pay
public void display()
• You are not overriding since this is not virtual in base class
• Hence C# Compiler asks you to add new which is
public new void display()
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
522
Versioning, Shadowing – new keyword

• Scenario #2
• A virtual method available in base class (Employee) as
public virtual void display()
{
//Statements
}
• And you have a function in Contractor with a signature
public void display()
• Compiler warns you to either override or hide display
function
• So, to override
public override void display()
• Or to Hide
public new void display()

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

• Scenario #2 (Contd)
• Overriding (Polymorphic)
 You can use the base class object reference and invoke display method
 A proper derived class’s display method is executed as with the
computePay method
 Try this with the following code in the Main after adding the Display
method in derived classes
foreach(Employee e in Employees)
{
e.display();
}
• Hiding (Not Polymorphic)
 You can invoke the display method of derived class only using a derived
class’s object reference
 The code above will invoke only Employee class’s display method
 If we have a collection of Contractor and managers in ArrayList how do we
invoke the display method of the appropriate derived class ???
 See next slide
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
524
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Versioning, Shadowing – new keyword

Change the foreach loop to :


foreach(Employee e in Employees)
{
if (e is Contractor) //Check if object is Contractor
((Contractor)e).display();
else if (e is Manager) //Check if object is Manager
((Manager)e).display();
}

Hiding base implementation using new keyword is


called SHADOWING

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

What is versioning ?
And another VERSION of a method is provided
which is different from the base class method

• Assume a method by name ExtraMethod is


introduced in a derived class
• And a method with the same name is added to
the base class at a later point of time
• Adding new keyword proactively to the derived
class method will prevent the code from
breaking
• While it is tempting to add new to all the new
methods of the derived class it must be done
judiciously
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
526
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Abstract Methods & Class
• An abstract method does not have a body
Public abstract type method-name(p1, p2…);
• Defining a base class method as abstract forces the
derived classes to override this method
• A new method of the same signature cannot be defined in
the derived class
• So, the derived class must override the method unlike
virtual methods
When a class defines one or more methods as abstract
then the class must be declared abstract
abstract classes cannot be instantiated thus preventing
invocation of a abstract method directly

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
527
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Abstract - Sample
Now the Employee class includes an abstract
method
public abstract decimal computeExtraPay();
And a modified display method
public virtual void display()
{
decimal extra = this.computeExtraPay();
decimal total = BaseSalary + extra;
Console.WriteLine(“Emp:{0}, {1}, {2:C}, {3:C}, {4:C}",
EmployeeID, FullName, BaseSalary, extra, total );
}

There is a change in Contractor Class ( Must


Override the abstract method)
public override decimal computeExtraPay()
{
return this.OverTime * this.Rate;
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
528
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Employee – Complete Source (Minus
Properties)
abstract class Employee
{
protected int EmployeeID;
protected string FullName;
protected decimal BaseSalary;

public Employee(int id, string fullName, decimal baseSalary)


{
this.EmployeeID = id;
this.FullName = fullName;
this.BaseSalary = baseSalary;
}
public virtual decimal computePay()
{
return this.BaseSalary ;
}
public abstract decimal computeExtraPay();
public virtual void display()
{
decimal extra = this.computeExtraPay();
decimal total = BaseSalary + extra;
Console.WriteLine("Emp:{0}, {1}, {2:C}, {3:C}, {4:C}",
EmployeeID, FullName, BaseSalary, extra, total );
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
529
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Contractor – Complete Source
class Contractor : Employee
{
public int OverTime;
public decimal Rate;
public Contractor(int id, string fullName, decimal baseSalary,
int overTime, decimal rate) :
base ( id, fullName, baseSalary)
{
this.OverTime = overTime;
this.Rate = rate;
}
public override decimal computePay()
{
return (this.BaseSalary + this.OverTime * this.Rate);
}
public new void display()
{
Console.WriteLine("{0}, {1}, {2:C}, {3:C}, {4:C}",
EmployeeID, FullName, BaseSalary, OverTime*Rate, computePay() );
}
public override decimal computeExtraPay()
{
return this.OverTime * this.Rate;
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
530
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Main Function and more revelations
foreach(Employee e in Employees)
{
//invoke display of base class
e.display();
//invoke display of derived class (new methods)
if (e is Contractor)
((Contractor)e).display();
}
Both print the same values, How ?
• The base class’s display method hooks the derived class’s
computeExtraPay method
• An abstract function is used for this and is like a contract
• Base class invokes the derived class method to know about
something which only derived class knows
• Display method of base class is called a Template Function and this
pattern of designing is called Template Design Pattern

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
531
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sealed Method
A method marked as sealed cannot be further
overridden in a derived class
sealed modifier must always come along with the
override modifier of a method
Cannot be combined with abstract modifier

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
532
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sealed Classes
This is quite opposite to abstract
That is if you don’t want people inheriting from
your class mark them as sealed
sealed class MyClass
{
//fields, properties and methods
}
Class YourClass : MyClass //Not Allowed
{
}

Sealed classes logically can not contain any


abstract method

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
533
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Multiple inheritance
C# permits inheritance from only one class
Multiple inheritance is not allowed
But could be achieved indirectly with interface
(a.k.a Mixins)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
534
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Structs & Inheritance
Structs cannot be base classes
Structs cannot inherit from other classes

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
535
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Object Behavior
All types are implicitly inherited from Object
The following methods are provided by Object

Equals Evaluates whether 2 objects are equal

GetHashCode Objects can provide their own hash values


and used in Collections
GetType Provide access to the Type object

ToString Provide a String representation of the object

Finalize Similar to destructor, called by Garbage


Collector
MemberwiseClone Creates copis of the object, Must not be
overridden

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
536
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Overriding Object Methods
Most often the following methods are overridden
in any class
• Equals
• ToString

Kid class revisited :

How to compare 2 kids for equality?


How to print Kid objects like any normal built in
type?

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
537
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Equals
Revisit Kid class created earlier
Kid kid1 = new Kid("Craig", 11);
Kid kid2 = new Kid("Craig", 11);

if (kid1 == kid2)
Console.WriteLine(“Equal”);
else
Console.WriteLine(“Not Equal”);
The above code will print “Not Equal”, though the objects
contain equivalent values
Since Object variable stores only reference to the Object
and these 2 are two distinct object on the heap with
distinct references == operator returns false
Hence to compare objects (reference types ) we need to use
if (kid1.Equals(kid2))

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
538
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Equals …
Add the following method to the Kid class
public override bool Equals(object obj)
{
if (obj is Kid) //Check for type
{
Kid k = (Kid)obj; //Cast type
//Check individual fields
return(this.name.Equals(k.name) && this.age == k.age);
}
return false;
}
Note here that for comparing the name field which
is a string we have used Equals method

Check the method invoking Equals to compare Kid


objects.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
539
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ToString
• PrintKid is the method which is used for printing
the kid object’s value
• It is better to de-couple the print functionality
from the Kid class
• The users of kid class could print it on various
devices
• But formatting information must be provided by
Kid class
• If we try to print any Kid object using

Console.WriteLine("{0}", kid1);
The output is not as you expected, we need to
implement ToString method to make it happen
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
540
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
ToString
public override String ToString ()
{
StringBuilder sb = new StringBuilder("Kid ");
sb.Append(this.name);
sb.Append(" is ");
sb.Append(this.age);
sb.Append(" years old.\n");
return sb.ToString(); //Check the use of ToString of sb
}

Now
Console.WriteLine("{0}", kid1); //No need for invoking ToString
In Main will print
Kid Craig is 11 years old.

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

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

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Operator Overloading
User defined classes can have all the functionality of
built-in types
Operators are static methods whose return value
represents the result of the operation
You can add a functionality to add two complex
numbers by overloading + operator
Mathematical operators are overloaded mostly for
entities modeled after mathematical concepts like
measurements, number systems etc.
For application specific entities the logical operators
come in handy to compare the objects
To compare 2 Kid objects it will be natural to use the
== operator than
Equals method

Let us add the functionality to the Kid class…


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
543
== , != Operator
Let us add this code to Kid class
public static bool operator ==(Kid lhs,Kid rhs)
{
return (lhs.Equals(rhs));
}

public static bool operator !=(Kid lhs, Kid rhs)


{
return(!(lhs == rhs));
}
You cannot overload just == operator, conditional
operators need to be overloaded in logical pairs
This is insisted by C# Compiler, if we leave “!=“
compiler generates an error

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
544
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Cleaning the code
• In our code Operator == method uses the Equals method
internally
• Equals method checks for the object type, this happens
unnecessarily though Operator == method can take only Kid
objects
• So it is better that Equals uses == operator

public override bool Equals(object obj)


{
if (obj is Kid)
{
Kid k = (Kid)obj;
return (this == k);
}
return false;
}
public static bool operator ==(Kid lhs,Kid rhs)
{
return(lhs.name.Equals(rhs.name) && lhs.age == rhs.age);
} ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
545
Exercise
• Create a complex number class with
• ToString
• + Operator
• - Operator

• Check with Operator overloading tutorial in


the .Net SDK Documentation

• For Contractor and Manager classes add


• >, <, >=, <= based on total Salary
• ToString
• Equals

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
546
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Type Conversion
Type conversion (Casting) is also done thru operators
We can implement rules for converting between user
defined types
Assume a struct like this exists
public struct Human
{
public string Name;
public int Age;

public Human(string name, int age)


{
this.Name = name;
this.Age = age;
}
}
We can obviously convert a kid object to Human
variable implicitly

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
547
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Implicit Conversion
Add this method to Kid class
public static implicit operator Human(Kid k)
{
return new Human(k.name, k.age);
}

So we can use this by


Kid kid1 = new Kid("Craig", 11);
Human h = kid1;

Provide an implicit conversion method only when


you are sure of no data loss

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
548
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Explicit conversion
Conversion between types which are not exactly
similar
Converting a Kid object to a String Object must be
forced explicitly
Add this method to Kid class
public static explicit operator string(Kid k)
{
return k.name;
}

If you need to use this :


Kid kid1 = new Kid("Craig", 11);
String s = (string)kid1;

Thus loosing the age value in the target


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

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

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Introduction to interface
• An interface defines a contract
• A collection of semantically related abstract members
• Classes and structs implementing the interface must
adhere to this contract by implementing ALL the methods
and properties
• Implementing interface is like inheritance
• When a class inherits from another class it shares the
capability
• Since interfaces do not have any capability the
implementing classes share a common responsibility
defined in the contract
• Set of components working together can often be glued
by interfaces
• Another strong point of interface is maintainability
• Using too much of inheritance lead to explosion of
hierarchy and poor maintainability of design and code
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
551
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Interfaces
The .Net SDK is full of contracts which need to be fulfilled
by user defined class types to achieve additional
functionality
• The additional functionalities include but not limited to
• Creating copies of objects (Cloning)
• Comparing types
• Iterating thru lists (Enumeration)

• Let us see some sample interfaces available in .Net SDK


and implement them in our own classes
• Interface take the following form
• (public | internal) interface interface-name :
base-interface-list
{
members;
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
552
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Cloning
Consider this code :
Kid kid1 = new Kid("Craig", 11);
Kid kid2 = kid1; //Shallow Copy
There is only one kid object after this code executes
Both Kid2 and Kid1 contain the same reference of the
only Kid object
This is called a shallow copy

Cloning is creating another instance of the object.


Done by
interface ICloneable {
Object Clone();
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
553
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Cloning implemented
class Product : ICloneable //Implement interface
{
public readonly int SKU;
public readonly string Name;
public readonly decimal Price;

public Product(int sku, string name, decimal price)


{
this.SKU = sku;
this.Name = name;
this.Price = price;
}
//Implement Clone function
public object Clone()
{
return new Product(this.SKU, this.Name, this.Price);
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
554
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Cloning used
static void Main(string[] args)
{
Product p1 = new Product(100, "Tooth Brush", 12.5M);

Product p2 = (Product)p1.Clone(); //Make a copy

Console.WriteLine("{0}, {1}, {2:C}",


p2.SKU, p2.Name, p2.Price);
if (p1 == p2)
Console.WriteLine("reference equal");
else
Console.WriteLine("reference unequal");
}

Output shows that : Values are equal References are


unequal
Here Clone is invoked using a Product Object P1.
This is called implicit implementation
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
555
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Comparison - Sorting
Sorting built-in types
int[] myIntArray = new int[5] { 5,4,3,2,1 };

Array.Sort(myIntArray);
Sort is a static method of System.Array class

Consider an array of Product objects


Product[] products = new Product[10];
products[0] = new Product(100, "Tooth Brush", 12.5M);
products[1] = …

Can we sort the products array using


Array.Sort(products); ????
Answer is NO! NOT YET!!!
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
556
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Comparison - Sorting
Sorting to work on an array of user defined types
• A contract need to be adhered to in our type
• A Comparator function

The Contract is :
interface IComparable
{
int ComparteTo(object o);
}

• Our type must implement this contract


• Sort method will invoke this CompareTo method by passing an
object to compare to the current object
• We need to provide the logic and return
 -1 if this is less than the object passed
 0 if they are equal
 +1 if this is greater
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
557
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Comparison - Sorting
While implementing IComparable interface you need
to decide which field to sort by
For this example let us sort by SKU which is an
integer
class Product : ICloneable, IComparable
{
//Fields here…
//Constructor
//Clone Method
int IComparable.CompareTo(object obj)
{
Product p = (Product) obj; //Cast obj to Product
if (this.SKU < p.SKU)
return -1;
if (this.SKU > p.SKU)
return 1;
return 0;
}
} ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
558
Bit of Interface theory
We have implemented 2 interfaces and 1 method in each of
them
But there is a subtle difference in the way the functions are
written
When you add the interface name to class definition
class Product : ICloneable, Icomparable
Visual Studio asked you to press <tab> key and added the
empty methods
When you added ICloneable the signature was
public object Clone()
And when you added the IComparable the signature was
public int CompareTo(object obj)
But it was changed in the code to
int IComparable.CompareTo(object obj)
What does it mean?
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
559
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Bit of Interface theory
You can implement a function as public with methodname or
interfacename.methodname without access specifier
In the former the method could be accessed using just the
object reference
• Since you need to invoke clone method on the object
In the later it is not possible since the method is not public
• Sort Method invoke the CompareTo method not using the
Product Object
• Because it does not know what Product object is
• Here the method must be accessed using a reference to the
interface IComparable
This is called Explicit implementation
But note that the comparable could be implemented
implicitly also
Why we have not done that is anybody who is holding a
reference to Product object should not access the method
just like that!
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
560
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
CompareTo - rewritten
You might have noticed the logic of the CompareTo function
according to the rules (return –1, +1, 0 on conditions)
But there is a real smart way of doing this

Consider for a moment how the sorting of an integer array


works?
Because int type has already implemented the IComparable!
Yes ! Structs can implement interfaces
So, why don’t we make use of the CompareTo method of int ?
Here is how the smart code looks :
int IComparable.CompareTo(object obj)
{
Product p = (Product) obj;
return(this.SKU.CompareTo(p.SKU));
}
This was possible for us because int has implemented the

IComparable interface implicitly ! 

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
561
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
IComparable - Used
Enough of theory!
static void Main(string[] args)
{
Product[] prods = new Product[5];
//Initialize product array, create products
prods[0] = new Product(104, "Washing Soap", 62.0M);
prods[1] = new Product(101, "Shower Gel", 90.0M);
prods[2] = new Product(102, "Tooth Paste", 20.0M);
prods[3] = new Product(103, "Toilet Soap", 15.6M);
prods[4] = new Product(100, "Tooth Brush", 12.5M);

Array.Sort(prods);

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


{
Product p = prods[i];
Console.WriteLine("{0}, {1}, {2:C}",
p.SKU, p.Name, p.Price);
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
562
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Interface theory - Casting
How do we invoke the explicitly implemented method of an
interface if we only have an object?
Assume you want to compare prods[0] and prods[1]
yourself :
Product p0 = prods[0];
IComparable ic = (IComparable) p0;
int val = ic.CompareTo(prods[1]);
Console.WriteLine("Val is : {0}", val);
Here you are having the p0 object yourself,
But if somebody else passes an object to you and you need
to invoke a interface member on it
Then type casting to the interface may result in runtime
error!
So, you can check before casting using is operator
if (p0 is IComparable)
{
//Cast and use
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
563
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Interface theory – Casting…
But a much more efficient method is to cast using
as Operator :
Product p0 = prods[0];
IComparable ic = p0 as IComparable;
if (ic != null)
{
int val = ic.CompareTo(prods[1]);
Console.WriteLine("Val is : {0}", val);
}

as operator casts to the interface


and
if the object does not implement the interface it
returns null

as operator is efficient than is operator


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
564
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Implementing multiple interfaces
It is better to implement explicitly if two or more
interfaces contain exactly similar method(s)

interface Walkable {
void move(int pos);
}
interface Swimmable {
void move(int pos);
}
Class Human : walkable, Swimmable
{
Walkable.move(int pos) //Explicit implementation makes it possible
{
}
Swimmable.move(int pos) //Explicit implementation makes it possible
{
}


}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
565
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Enumeration
To iterate over custom collection classes
There are 2 interfaces involved
• IEnumerable
• IEnumerator GetEnumerator()

• IEnumerator
• void Reset()
• object Current {get;} //Property
• bool MoveNext()

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
566
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Product Collection class – Step 1
public class ProductCollection : IEnumerable, IEnumerator
{
private Product[] products;

public ProductCollection()
{
products = new Product[5];
products[0] = new Product(104, "Washing Soap", 62.0M);
products[1] = new Product(101, "Shower Gel", 90.0M);
products[2] = new Product(102, "Tooth Paste", 20.0M);
products[3] = new Product(103, "Toilet Soap", 15.6M);
products[4] = new Product(100, "Tooth Brush", 12.5M);
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
567
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
IEnumerable, IEnumerator – Step 2
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerator)this);
}

private int pos = -1; //State variable counter for Looping

void IEnumerator.Reset()
{
pos = -1;
}
object IEnumerator.Current
{
get { return products[pos]; }
}
bool IEnumerator.MoveNext()
{
pos++;
if (pos == products.Length) return false;
return true;
}
} //End Product Collection Class

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
568
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Using – Step 3
ProductCollection pc = new ProductCollection();

foreach (Product p in pc)


{
Console.WriteLine("Collections - > {0}, {1}, {2:C}",
p.SKU, p.Name, p.Price);
}
This implementation works fine but has a few drawbacks
Try adding another For Each loop below the first one , The
products wont get printed for the second time.
For each does not invoke Reset. We need to call reset in the
GetEnumerator method.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
569
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Collection in a better way
Instead of containing an Array contain an ArrayList
Advantages
• Can provide add, remove functions with strong typing
• Pre built Enumerators

class ProductList : IEnumerable


{
private ArrayList products;
public ProductList()
{
products = new ArrayList();
}
public int Add(Product p) //Manage Collection operations
{
return products.Add(p);
}
public IEnumerator GetEnumerator()
{
return products.GetEnumerator();
}
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
570
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Using List based Collection
ProductList pl = new ProductList();
pl.Add(new Product(104, "Washing Soap", 62.0M));
pl.Add(new Product(101, "Shower Gel", 90.0M));
pl.Add(new Product(102, "Tooth Paste", 20.0M));
pl.Add(new Product(103, "Toilet Soap", 15.6M));
pl.Add(new Product(100, "Tooth Brush", 12.5M));

foreach (Product p in pl)


{
Console.WriteLine("List - > {0}, {1}, {2:C}",
p.SKU, p.Name, p.Price);
}

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

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

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Indexers
Allow us to make classes look like virtual arrays
Appropriate to add this capability to collection classes

ArrayList is a collection class not a fixed size Array


While adding to the ArrayList is done by add() method
• Accessing elements sequentially are done by Enumerators
• Accessing at random facilitated by Indexers
Consider the ProductList class of previous sample the 3rd
product in the list could be accessed using
Pl[3]
How do we add this capability to the ProductList ?

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
573
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Indexer - Sample
Indexer is like a property the signature is
public type this[int index-var]
{
get { }
set { }
}
For the ProductList class we should not provide a
set method. Why?
And we need to provide a Length property also.
Why?

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
574
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Indexer - Sample
Indexer is like a property the signature is
public Product this[int index]
{
get
{
return (Product)products[index];
}
}
//Provide a Length property to prevent index going out of bounds
public int Length
{
get
{
return products.Count;
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
575
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Indexer - Exercise
Create a class which accepts an English sentence
where words are separated by space or comma
or full stop
Provide an indexer to access and set the
individual words.
Constructor of the class looks like this :
public Words( string sentence)
{
char[] delim = {' ', '.', ','};
words = sentence.Split(delim);
}

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

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

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sorting using different fields
An overload of Array.Sort is available for this purpose
Array.Sort(arr, Comparer)
The second parameter Comparer is an Object which
implements IComparer Interface
int IComparer.Compare(object x, object y)
Each Implementation of this method must compare using a
specific field
• The problem is we cannot implement any interface more
than once in a class
• The trivial solution suggests that This interface could be
implemented in 3 different classes(Anyway both the
objects for Comparison are passed as parameters)
• But we are increasing the number of Public classes
available which is also a potential problem. For Product
class we need need 3 more classes for implementing
Compare on each field
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
578
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Problems with IEnumerator
What if 2 concurrently executing foreach loops want access
to the same ProductCollection class?
The output will jump and items will be skipped by the two
loops, since they share the index variable pos and the
object
This situation is more common in a web application
environment
The solution is to provide a new Enumerator object each
time GetEnumerator is called
The IEnumerator must be implemented on a different class
and an object of this class must be created and returned
by the GetEnumerator, pos variable must be in this new
class
But how do we make the Products array available to this
class?

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
579
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Nested Classes
• A Class defined with in another class
• An Inner class can
• Access the outer class’s static members with or without specifying
the outer class name as qualifier
• Cannot access instance members of outer class unless a reference is
passed to the inner class
• When a reference is known then it can access all instance members
including Private members
• An outer class can
• Access the inner class’s static member by qualifying the member
with the inner class name
• Cannot access the instance members unless a reference is created
• An Inner class could be created with any member access
modifier
• Thos who have access to inner class can access the static members
of inner class
• Instance members of inner class can be accessed only when an
instance of inner is available with outer and is accessible
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
580
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Comparers
We are going to create 3 inner classes inside the
Product class Implementing IComparer
private class SKUComparer : IComparer
{
public int Compare(object x, object y)
{
return ((Product)x).SKU.CompareTo(((Product)y).SKU);
}
}

The inner class is private because nobody in the


outside world needs to know about this class
The instance of SKUComparare is independent of
the outer product class (Not accessing any of
the outer’s instance members)
Then how do people get an instance of this?
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
581
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Comparers
People of the outside world can get an object of
SKUComparer (the only one) thru a Static member of the
Product class
Add this line to the product below the inner
class(SKUComparer )
public static IComparer SKUCOMPARER = new SKUComparer();
Public : Client should be able to access this instance
Static : One instance is enough (Nothing to do with
outer class instance variables)
Type IComparer : Need not expose this as type
SKUComparer since it is Private. Or this is why we made
it as private?
• Can we expose this as a SKUComparer Type? Why?

Add Other 2 inner classes and static members. Sort by any


of the 3 fields and check the output.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
582
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Comparer - Solution
private class NAMEComparer : IComparer
{
public int Compare(object x, object y)
{
return ((Product)x).Name.CompareTo(((Product)y).Name);
}
}
private class PRICEComparer : IComparer
{
public int Compare(object x, object y)
{
return ((Product)x).Price.CompareTo(((Product)y).Price);
}
}
public static IComparer SKUCOMPARER = new SKUComparer();
public static IComparer NAMECOMPARER = new NAMEComparer();
public static IComparer PRICECOMPARER = new PRICEComparer();

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
583
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Comparer - Solution
Product[] prods = new Product[5];
prods[0] = new Product(104, "Washing Soap", 62.0M);
prods[1] = new Product(101, "Shower Gel", 90.0M);
prods[2] = new Product(102, "Tooth Paste", 20.0M);
prods[3] = new Product(103, "Toilet Soap", 15.6M);
prods[4] = new Product(100, "Tooth Brush", 12.5M);

Array.Sort(prods, Product.PRICECOMPARER);
//Print the sorted Array
for(int i =0; i < prods.Length; i++) //Print the sorted Array
{
Product p = prods[i];
Console.WriteLine("{0}, {1}, {2:C}", p.SKU, p.Name, p.Price);
}
Array.Sort(prods, Product.NAMECOMPARER );
//Print the sorted Array
Array.Sort(prods, Product.SKUCOMPARER );
//Print the sorted Array

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
584
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Enumerator
You got it!
IEnumerator must be implemented as an inner
class
Let us create an inner class by name
ProductEnumerator inside ProductCollection
class
Now the Enumerator class needs access to the
outer class’s instance member products Array
To enable this a reference of the outer class
instance is passed to the constructor of inner
class
And thru this reference the Enumerator inner
class accesses the private member of the outer
class
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
585
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Enumerator- Solution
private class ProductEnumerator : IEnumerator
{
private ProductCollection items;
private int pos;
public ProductEnumerator(ProductCollection items)
{
pos = -1;
this.items = items; //get outerclass ref thru constructor param
}
void IEnumerator.Reset() { pos = -1; }
object Ienumerator.Current //Access the outerclass private member
{
get { return items.products[pos]; }
}
bool Ienumerator.MoveNext()
{
pos++;
if (pos == items.products.Length) return false;
return true;
}
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
586
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Enumerator- Solution
Now the outer class ProductCollection implements only
IEnumerable
public class ProductCollection : IEnumerable
{
private Product[] products;
//Constructor
//Inner Class
IEnumerator IEnumerable.GetEnumerator()
{
//Pass a reference of self
//so that the inner class can access the array
ProductEnumerator pe = new ProductEnumerator(this);
return((IEnumerator) pe);
}
}
The Main Method
ProductCollection pc = new ProductCollection();
foreach (Product p in pc)
{
Console.WriteLine("Collections1 - > {0}, {1}, {2:C}",
p.SKU, p.Name, p.Price);
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
587
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
UML For Beginners

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

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Course Objectives
Ensure that trainees can
• Understand basic UML concepts
• Interpret requirements given in UML notation
• Prepare design artifacts using UML notation

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
589
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Target Audience
• Software Engineer Trainees
• SEs/SSEs looking for a basic understanding of
UML

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
590
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Prerequisites for the Course
• Understanding of OOPs and basic coding skills

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
591
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Session Plan
• What is UML?
• Where can UML be used?
• Types of UML diagrams/artifacts
• Use Cases & Use Case Diagrams
• Class Diagrams
• Sequence Diagrams
• Package Diagrams
• Deployment Diagrams
• Q/A Session

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
592
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
What is not covered
• Not a full fledged UML course
• Advanced concepts in most diagrams are not
covered

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
593
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
What is UML?
• Born out of the unification of the many object-
oriented graphical modeling languages
• Open standard, controlled by the Object
Management Group (OMG)
• Family of graphical notations
• Single meta-model
• Helps in describing and designing software
systems
• Common language for communicating design
concepts among software
developers/designers

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

How people
interact with
Conceptual the
perspective -A
••
Use system.
Canwayshow the
UseCase
Case good
Requirements
Diagram
Diagram of context
building
Can to for
beup use cases
a rigorous
useful and alsohas
ifcomplex
a concept
•Class Used
theandetailsexplain a cycle, use
Analysis •Class vocabulary ofofthe
interestinghowdomain.
life
diagram cases
complicated usestates
case works.
diagram with various and events
••
Activity that change that state.
Activity
Diagram
Diagram
••
State
State
Diagram
Diagram
••
Sequence
Sequence
Diagram
Diagram
Show the classes in the
software
To andwhat
figure out how happens
they in
••
Class interrelate
Show the large-scale
the software for the use case
Class For classesof
with
Diagram organization
scenarios thecomplex
softwarelife
Diagram Show the
histories. physical layout of
Design ••
Sequence
Sequence the software
diagram
diagram
••
Package
Package
Diagram
Diagram
••
State
State
Diagram
Diagram
••
Deployment
Deployment
Diagram
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

D ia g ra m P u rp o s e
A c t ivit y P ro c e d u ra l & P a ra lle l B e h a vio ra l
C la s s C la s s , F e a tu re s & R e la tio n s h ip s
C o m m u n ic a tio n In te ra c tio n s b e t w e e n o b je c t s ; e m p h a s is o n L in k s
C om ponent S tru c t u re a n d C o n n e c t io n s o f C o m p o n e n t s
C o m p o s it e S t ru c t u re R u n tim e C o m p o s itio n o f a n e w c la s s
D e p lo y m e n t D e p lo y m e n t o f a rt ifa c t s t o n o d e s
In t e ra c t io n O ve rvie w M ix o f s e q u e n c e a n d A c t ivit y D ia g ra m
O b je c t E x a m p le c o n fig u ra t io n s o f in s ta n c e s
P ack age C o m p ile Tim e H ie ra rc h y o f S t ru c t u re
S equenc e In te ra c tio n s b e t w e e n o b je c t s ; e m p h a s is o n S e q u e n c e s
S t a te M a c h in e H o w e ve n t s c h a n g e a n o b je c t o ve r it s life
Tim in g In te ra c tio n s b e t w e e n o b je c t s ; E m p h a s is o n tim in g
Us e Case H o w u s e rs in te ra c t w it h a s y s te m

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
597
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Use Cases
• Describe the typical interactions between the users of
a system [actors] and the system itself
• Provide a narrative of how a system is used
• Capture the functional requirements of a system
using scenarios
• Use case - set of scenarios tied together by a
common user goal
• Scenario - sequence of steps describing an
interaction between a user and a system. Eg: Buy a
Product in a Web-based on-line store
• An actor is a role that a user plays with respect to
the system

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
598
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Use Cases – Contents of a Use Case

• Pick the main


success scenario
• Break main
success scenario as
a sequence of
numbered steps
• Note down
extensions
• Extensions can be
successes— as in
3a—or failures, as
in 6a

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
599
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Use Cases – Contents of a Use Case ...

• Primary actor
• Secondary actors
• Each step in a use case is an element of the interaction
between an actor and the system
• A complicated step in a use case can be another use case
i.e. the first use case includes the second
Thus in the previous figure, the first step includes the use case
"browse catalog and select items to buy"
• Additional information
- A pre-condition
- A guarantee [Success guarantees and minimal
guarantees]
- A trigger

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

• The use case diagram


shows the actors, the
use cases, and the
relationships between
them:
1) Which actors carry out
which use cases
2) Which use cases include
other use cases

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
601
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Use Cases – Tips
• Use cases represent an external view of the system
• Do not expect any correlations between use cases
and the classes inside the system
• Each step in the use case should be a simple
statement
• The step should show the intent of the actor, not the
mechanics
• Do not describe the user interface in the use case
• Brainstorm all the extension conditions first, before
working out the consequences

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
602
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Class Diagrams
• Describes the types of objects in the system and the
various kinds of static relationships that exist among
them
• Shows the properties and operations of a class
• Mentions constraints that apply to the way objects
are connected
• Associations and generalizations

The slide below has a simple example of a class


diagram for order processing

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

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
604
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Class Diagrams ...
• Classes are represented by rectangles
• A class icon can be subdivided into compartments
• The top compartment is for the name of the class
• The second is for the variables of the class
[properties]
• The third is for the methods [operations] of the class

• Properties – An attribute of the class


• Operations – Actions a class performs on its data

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
605
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Constituents of Class Diagram -
Operations
Operations are the actions that a class knows to carry out.

The full UML syntax for operations is:


visibility name (parameter-list) : return-type {property-string}

• This visibility marker is public (+) or private (-);


• The parameter-list is the list of parameters for the operation
• The return-type is the type of the returned value, if there is one
• The property-string indicates property values that apply to the given
operation

The parameters in the parameter list are notated in a similar way to


attributes.
The form is:
direction name: type = default value
• The name, type, and default value are the same as for attributes
• The direction indicates whether input (in), output (out) or both (inout).
Default is (in)

An example operation on account might be:


+ balanceOn (date: Date) : Money

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

appear in two quite distinct notations: attributes


Properties
and associations

Attributes
A line of text within the class box

The full form of an attribute is:


visibility name: type multiplicity = default {property-string}

• This visibility marker is public (+) or private (-);


• The property-string indicates property values that apply to the given
operation

An example of this is:


- name: String [1] = "Untitled" {readOnly}

Only the name is mandatory.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
607
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Constituents of Class Diagram - Association
• Association –
 Is a solid line between two classes

 Directed from the source class to the target class.

 The name of the property goes at the target end of the association, together with
its multiplicity.

Association can be Uni directional/Bi Directional.

• Uni Directional Association -> Ex:

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

• Bi Directional Association ->


A pair of properties that are linked together as inverses.

Ex: The Car class has property owner:Person[1], and the


Person class has a property cars:Car[*].

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
609
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Constituents of Class Diagram - Multiplicity
More on Multiplicity
 Optional implies a lower bound of 0.
 Mandatory implies a lower bound of 1 or possibly more.
 Single-valued implies an upper bound of 1.
 Multivalued implies an upper bound of more than 1: usually *. If an
attribute is multi valued, this implies that
the data concerned is a collection.

Examples:
Mandatory/Multi valued Association
• Digit -The exact number of elements.
• 1..* - One to many.
• 3..5 - Three to five.
Optional/Multi Valued Association
• * or 0..* - Zero to many.
Mandatory/Single Valued
• 1 – One
Optional/Single Valued
• 0..1 – Zero or One

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

• Aggregation is the
‘whole/part-of’ relationship
• Cannot have cyclic
relationships i.e. part cannot
contain its whole

Composition:
• Same as aggregation, except
that ‘whole’ takes control of
creating/destroying ‘part’
• The "no sharing" rule is the
key to composition
• When composite is destroyed,
it must destroy all its parts

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

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

A relationship where the generalized behavior is


segregated into
a parent class.
Ex:

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

definition of one «call» The source calls an operation in the target.

element (the supplier) «create» The source creates instances of the target.
may cause changes to «derive» The source is derived from the target.
the other (the client) «instantiate» The source is an instance of the target. (Note that if
the source is
a class, the class itself is an instance of the class
class; that is, the target class is a metaclass).

«permit» The target allows the source to access the target's


private features.
«realize» The source is an implementation of a specification or
interface defined by the target
«use» The source requires the target for its implementation.
The general rule should be to minimize
dependencies, particularly when they cross large
areas of a system.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
614
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Class Diagrams – Tips
The trouble with class diagrams is that they are
so rich; they can be overwhelming to use. Here
are a few tips.
• Start with the simple stuff. Introduce other notations
only when you NEED them
• Don't draw models for everything; instead,
concentrate on the key areas
• Use notes and comments to make your intent clear.
See example below

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

• Typically captures the behavior of a single scenario


• Shows a number of objects and the messages that
are passed between these objects within the use case
• Each participant has a lifeline that runs vertically
down the page
• Displays the interaction using lifelines and the
ordering of messages by reading down the page

Consider a simple order-processing scenario.


The next slide has a sequence diagram that shows one
implementation of this scenario.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
616
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sequence Diagrams ...
An instance of order
sends getQuantity and
getProduct messages
to the order line.

The order invokes a


method on itself and
that method sends
getDiscountInfo to an
instance of customer.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
617
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sequence Diagrams ...
Another possible
approach to this
scenario is given.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
618
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sequence Diagrams – Life of a participant

• Activation bar shows


when the participant is
active in the
interaction
• Deletion of a
participant is indicated
by big X
• An X at the end of a
lifeline
shows a participant
deleting itself

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

The image to the left implements


the following pseudo code:

procedure dispatch
foreach (lineitem)
if (product.value > $10K)
careful.dispatch
else
regular.dispatch
end if
end for

if (needsConfirmation)
messenger.confirm
end procedure

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

Loop Meaning
Operator
alt Alternative multiple fragments; only the one
whose condition is true will execute
opt Optional; the fragment executes only if the
supplied condition is true. Equivalent to an alt
with only one trace
par Parallel; each fragment is run in parallel.
region Critical region; the fragment can have only one
thread executing it at once.
loop Loop; the fragment may execute multiple
times, and the guard
indicates the basis of iteration

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
621
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sequence Diagrams – Tips
• Use sequence diagrams when you want to look
at (or explain) the behavior of several objects
within a single use case
• Sequence diagrams are good at showing
communication among the objects
• Not so good at precise definition of the
behavior
• Instead of creating sequence diagrams for all
cases, use them to elucidate only the more
complex cases/scenarios

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
622
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Package Diagrams
• A package is a grouping construct that allows
you to take any construct in the UML and group
its elements together into higher-level units
• Each class is a member of a single package
• Packages can also be members of other
packages forming a hierarchic structure
• A package can contain both subpackages and
classes
• Packages correspond to such grouping
constructs as packages (in Java) and
namespaces (in C++ and .NET)

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
623
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Package Diagrams ...
• Each package represents
Different ways to represent a namespace
Packages • Every class must have a
unique name within its
owning package
• Use a fully qualified name
that shows the owning
package structure
E.g. System::Date
and
MartinFowler::Util::Date

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

•A package diagram
shows packages and their
dependencies
•Interpackage
dependencies summarize
the dependencies
between their contents

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

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
626
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Package Diagrams – When to use
• Extremely useful on larger-scale systems to
understand dependencies between major
elements of a system
• Correspond well to common programming
structures
• Plotting diagrams of packages and
dependencies helps keep an application's
dependencies under control
• Represent a compile-time grouping
mechanism

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

Deployment
diagrams show a
system's physical
layout, revealing
which pieces of
software run on
what pieces of
hardware.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
628
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Deployment Diagrams
• The main items on the diagram are nodes
connected by communication paths
• A node is something that can host some software
• Nodes come in two forms. A device is hardware, it
may be a computer or a simpler piece of hardware
connected to a system
• An execution environment is software that itself
hosts or contains other software, examples are an
operating system or a container process

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
629
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Deployment diagrams - When to use
• Deployment diagrams are very handy in
showing what is deployed where
• Useful in understanding the enterprise
architecture and design philosophies

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

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

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

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

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generics
Generics are a new feature in version 2.0 of the C#
language and the common language runtime (CLR).
Generics introduce to the .NET Framework the
concept of type parameters, which make it possible
to design classes and methods that defer the
specification of one or more types until the class or
method is declared and instantiated by client code.
The First Best thing you come to notice while using
Generics is that it helps you avoid run time exceptions
which happens because of wrong casting.

Generic classes encapsulate operations that are not


specific to a particular data type. The most common
use for generic classes is with collections like linked
lists, hash tables, stacks, queues, trees and so on
where operations such as adding and removing items
from the collection are performed in much the same
way regardless of the type of data being stored.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
633
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generics are new in
Version 2.0
Through Generics we can create classes which work on classes
You don’t have to give the types of the classes when you write the code
Instead you use placeholders which are “filled in” at runtime in a type safe
manner

Why generics?
• Compile-time type checking
• Performance (no boxing, no downcasts)
• Reduced code bloat (typed collections)

C# generics vs. C++ templates

• C# generics are checked at declaration


• C# generics are instantiated at run-time

C# generics vs. proposed Java generics

• C# generics work over entire type system


• C# generics preserve types at run-time

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
634
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Avoiding run time exceptions using
Generics
Lets now take the kid class and work out this assertion.

using System;
using System.Text;
using System.Collections;

namespace TestKid
{
class Kid
{
ArrayList kids;
Kid(string name,int age)
{
kids= new ArrayList();
kids.Add(name);
kids.Add(age);
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
635
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Avoiding run time exceptions using
Generics
public void PrintKid()
{
foreach (string k in kids)
{ The Program compiles
Console.WriteLine(k); with no Error but at
} runtime it throws an
invalid cast exception.
}
static void Main(string[]
args)
{
Kid myKid = new Kid(“Roy", 9);
myKid.PrintKid();
}
}
}

It would be better if you can spot these errors at compile time itself.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
636
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generic List
Now lets do this with a Generic List..
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace TestKid
{
class Kid
{
List<string>kids;
Kid(string name,int age)
{
kids = new List<string>();
kids.Add(name);
kids.Add(age);
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
637
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generic List
public void PrintKid()
{
foreach (string k in kids)
{ Now this code generates
Console.WriteLine(k); an error and warns you
} before u go to runtime.

static void Main(string[] args)


{
Kid myKid = new Kid("Ruby", 9);
myKid.PrintKid();
}
}
} What’s More…

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

Using an Arraylist with our Kid class was convenient but


this convenience comes at a cost. Any reference or value
type that is added to an ArrayList is implicitly upcast to
Object. If the items are value types, they must be boxed
when added to the list, and unboxed when they are
retrieved. Both the casting and the boxing and unboxing
Hence it is better to implement the kid code like this
operations degrade performance
List<string> list1 = new List<string>(); //Noboxing,No
casting:
list1.Add(“Ruby”);
list1.Add(9); // Compile-time error:

For client code, the only added syntax with List<T>


compared to ArrayList is the type argument in the
declaration and instantiation. In return for this slightly
greater coding complexity, you can create a list that is
not only safer than ArrayList, but also significantly
faster, especially when the list items are value types.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
639
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
How are C# generics implemented?

• Instantiated at run-time, not compile-time

• Checked at declaration, not instantiation

• Work for both reference and value types

• Exact run-time type information

Generics increases the performance of your code by


eliminating Boxing and UnBoxing.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
640
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generics
Now lets create a method called AddKids to add
more Kid objects to the Kid class.
public class Kid
{
private object[] KidObj=new object[5];
private int count;

public void AddKids(object K) {


KidObj[count++] = K;
}

public int Count {


get { return count; }
}
}

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

public class Kid


{
private object[] KidObj;
private int count;

public void AddKids(object K) {


KidObj[count++] = K;
}

public int Count {


get { return count; }
}
}

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

class KidMain
{
public static void Main()
{
intList.Add(1); // Argument is boxed
Kid mykid=new Kid(); intList.Add(2); // Argument is boxed
mykid.AddKids(1); intList.Add("Three");
mykid.AddKids(2);
mykid.AddKids("Three");

}
}

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

public class Kid<ItemType>


{
private ItemType[] KidObj=new ItemType[5];
private int count;

public void AddKids(ItemType K) {


KidObj[count++] = K;
}

public int Count {


get { return count; }
}
}

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

class KidMain
{
public static void Main()
{
Kid<int> mykid = new Kid<int>();
intList.Add(1); // No boxing
mykid.AddKids(1);
intList.Add(2); // No boxing
mykid.AddKids(2); intList.Add("Three"); // Compile time error
mykid.AddKids("Three");

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
645
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generic Type Parameters
In a generic type or method definition, a type parameters is
a placeholder for a specific type that a client specifies when
they instantiate a variable of the generic type.

A generic class, such as GenericList<T> cannot be used as-


is because it is not really a type; it is more like a blueprint
for a type.

To use GenericList<T>, client code must declare and


instantiate a constructed type by specifying a type
argument inside the angle brackets.

The type argument for this particular class can be any type
recognized by the compiler.
GenericList<float> list1 = new GenericList<float>();
GenericList<ExampleClass> list2 = new
GenericList<ExampleClass>(); GenericList<ExampleStruct>
list3 = new GenericList<ExampleStruct>();

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
646
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generic Type Parameters
Type parameters can be applied to
• Class, struct, interface, and delegate types

class Dictionary<KeyType, ValueType> {...}

struct Pair<FirstType, SecondType> {...}

interface IComparer<T> {...}

delegate ResType Func<ArgType, ResType>(ArgType arg);

Dictionary<string, Customer> customerLookupTable;

Dictionary<string, List<Order>> orderLookupTable;

Dictionary<int, string> numberSpellings;

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
647
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generics
Type parameters can be applied to
• Class, struct, interface, and delegate types
• Methods

class Array
{
public static T[] Create<T>(int size) {
return new T[size];
}

public static void Sort<T>(T[] array) {


...
}
}

string[] names = Array.Create<string>(3);


names[0] = “Roy";
names[1] = “Rennit";
names[2] = “Allam";
Array.Sort(names);
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
648
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Inheritance with
generics
For a generic class Node<T>, derived code can reference
the class either by specifying a type argument, to create a
closed constructed type (Node<int>), or it can leave the
type parameter unspecified, for example when specifying
a generic base class, to create an open constructed type
(Node<T>). Generic classes can inherit from concrete,
closed constructed, or open constructed base classes:
class BaseNode { }
class BaseNodeGeneric<T> { }
// concrete type
class NodeConcrete<T> : BaseNode { }
//closed constructed type
class NodeClosed<T> : BaseNodeGeneric<int> { }
//open constructed type
class NodeOpen<T> : BaseNodeGeneric<T> { }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
649
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Inheritance with
generics
Non-generic — concrete — classes can inherit from
closed constructed base classes, but not from open
constructed classes or naked type parameters because
there is no way at run time for client code to supply the
type argument required to instantiate the base class.
//No error
class Node1 : BaseNodeGeneric<int>
{
}
//Generates an error
class Node2 : BaseNodeGeneric<T>
{
}
//Generates an error
class Node3 : T
{
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
650
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Inheritance with
generics
Generic classes that inherit from open constructed types
must supply type arguments for any base class type
parameters that are not shared by the inheriting class, as
demonstrated in the following code:
class BaseNodeMultiple<T, U>
{
}
//No error
class Node4<T> : BaseNodeMultiple<T, int>
{
}
//No error
class Node5<T, U> : BaseNodeMultiple<T, U>
{
}
//Generates an error
class Node6<T> : BaseNodeMultiple<T, U>
{}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
651
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Inheritance with
generics
Generic classes that inherit from open constructed types must specify
constraints that are a superset of, or imply, the constraints on the base type.

class NodeItem<T> where T : System.IComparable<T>, new() { } class


SpecialNodeItem<T> : NodeItem<T> where T : System.IComparable<T>,
new() { }

Generic types can use multiple type parameters and constraints.

class SuperKeyType<K, V, U> where U : System.IComparable<U> where


V : new() { }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
652
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Open constructed and closed constructed types can be used as method
parameters:

void Swap<T>(List<T> list1, List<T> list2) //code to swap


items
{ }
void Swap(List<int> list1, List<int> list2) //code to swap
items
{
}

Remember : Generic classes are invariant.

List<BaseClass>, // compile-time error


List<DerivedClass>.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
653
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Use of Default Keyword in Generic
Code
In generic classes and methods, one issue that arises
is how to assign a default value to a parameterized
type T when you do not know the following in
advance:
1. Whether T will be a reference type or a value
type.
2. If T is a value type, whether it will be a numeric
value or a struct.
For this we can use the Default Keyword

The default keyword, which will return null for reference


types and zero for numeric value types. For structs, it will
return each member of the struct initialized to zero or
null depending on whether they are value or reference
types.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
654
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Use of Default Keyword in Generic
Code
public class GenericList<T>
{
private class Node
{
public Node Next;
public T Data;
}
private Node head;
public T GetNext() {
T temp = default(T);
Node current = head;
if (current != null) { temp = current.Data; current =
current.Next; }
return temp;
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
} }
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
655
Generic Collections
The major advantage that generics brings for
learner programmers is a better way to deploy
collection classes
They remove the need to cast items read from the
collection

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

public class Kid<ItemType>


public
{ class Kid<T>
{ private ItemType[] KidObj=new T[5];
private
private intT[] KidObj=new T[5];
count;
private int count;
public
public void AddKids(ItemType
void AddKids(T K) { K) {
if (count == KidObj.Length)
KidObj[count++] = K; Resize(count * 2);
}KidObj[count++] = K;
}
public int Count {
public get { return
int Count { count; }
}get { return count; }
} }
}

©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
>
Collection classes Stack<T>
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>
Reflection KeyedCollection<T>
ReadOnlyCollection<T
>
Nullable<T>
EventHandler<T>
Comparer<T>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
659
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Example (Generic List for Kid Class)
public class Kid
{
protected string name;
protected int age;
public string Name
{
get
{ return name; }
set { name = value; }
}
public int Age {
get { return age; }
set { age = value; }
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
660
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Example (Generic List for Kid Class)
public class MainClass
{
public static void Main(string[] args)
{
List<Kid> objList = new List<Kid>();

Kid objKid = new Kid();


objKid.Name = "Rennit";
objKid.Age = 22;
Kid objKid2 = new Kid();
objKid2.Name = "Pcube";
objKid2.Age = 23;
objList.Add(objKid);
objList.Add(objKid2);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
661
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Example (Generic List for Kid Class)
foreach (Kid user in objList)
{

System.Console.WriteLine(System.String.Format("{0}:{1}",
user.Name, user.Age));
}
System.Console.WriteLine("press enter");
System.Console.ReadLine();
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
662
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generics best
practices.
1. Create a generic classes by starting with an existing
concrete class, and changing types into type parameters
one at a time until you reach the optimal balance of
generalization and usability.
2. As a general rule, the more types you are able to
parameterize, the more flexible and reusable your code
becomes. However, too much generalization can result
in code that is difficult for other developers to read or
understand.
3. A good rule is to apply the maximum constraints
possible that will still let you handle the types you need
to handle. For example, if you know that your generic
class is intended for use only with reference types, then
apply the class constraint. That will prevent unintended
use of your class with value types, and will enable you to
use the as operator on T, and check for null values.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
663
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generics best
practices.
4. Since generic classes can serve as base classes,
the same design considerations apply here as
with non-generic classes.
5. if you are designing a class that will be used to
create items in a generics-based collection, you
may need to implement an interface such as
IComparable<T> where T is the type of your
class.
6. With generic classes it is preferable to use
generic interfaces, such as IComparable<T>
rather than IComparable, in order to avoid boxing
and unboxing operations on value types.

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

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

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Callbacks
What is a callback?
You call a method of a class and that method invokes
• Methods on the other class ( No big deal! )
• Methods of your class ( Probably I have written both the classes and
they know each other by name! )
• Methods of a class which will be written at a future date ( That
sounds interesting! )
Items 1 & 2 are nothing but 2 classes written about the
same time and the class names are hard coded in each
other or strongly coupled
Imagine how you invoked Sort method Array class
( provided by .net) and sort method invoked your
CompareTo method on the product class!
Here the programmer who wrote the array class would
not have had the slightest clue that a developer in
India is going to use this method to sort an array of
Products
Yes! It was possible because of interfaces! And it is
possible if we use abstract classes too!
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
666
Callbacks
These interfaces / or abstract classes which are
published by a contract maker and whoever
wants to get called they implement the
interface or derive from that abstract class
Using interface is better than inheriting an
abstract class for achieving a callback
functionality because
• With interfaces you can derive from another appropriate
class of your domain
• While inheriting from a contract class you lose that
opportunity
Think for a while how weird it will be when
• You want to add the CompareTo method to Contractor class
to sort on Rate
• And CompareTo method is defined in an abstract class by
name Comparable instead of an interface IComparable!
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
667
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Callbacks
So Interface is better to define a callback /
contract than an abstract class
But we can do better by reducing the coupling still
Because interface forces you to implement all the
functions in the contract, What if you need an
option to selectively respond to callbacks?

Delegates come to help!


• Special feature of .net
• Almost like a function pointer
• A reference type
• Promotes loosely coupled code

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
668
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Delegate
The person who advertises a function does so by
publishing the function prototype
public delegate int DelegateProcess(string s);

When somebody else writes a function to match


this signature that function could be attached to
this publisher ( as a property or a private
variable set thru constructor)

The publisher invokes the method thru this


variable by passing a string and gets a integer
result back

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
669
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Delegate - Sample
public delegate int DelegateProcess(string s);
public class Publisher
{
private DelegateProcess DPMessage; //Declare a variable
public Publisher( DelegateProcess dpMessage)
{
this.DPMessage = dpMessage;
}
public void Publish()
{
int n = DPMessage("xyz");
Console.WriteLine("{0} ", n);
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
670
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Delegate - Implementing
class Subscriber
{
static void Main(string[] args)
{
Subscriber sb = new Subscriber();
DelegateProcess dp = new DelegateProcess( sb.MessageCount);
Publisher p = new Publisher(dp);
p.Publish();
Console.ReadLine();
}
public int MessageCount(string s)
{
return s.Length;
}
}
Main calls Publish method of publisher and Publisher calls
MessageCount method
Note here that the publisher does not have any clue of the
Subscriber class name or the method name which implements
the delegate!

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
671
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Strategy
In the previous sample it is not possible to attach
a method (as delegate) after creating Publisher
This is because it has to be set thru the
constructor
While this is a best practice for other instance
variables, it is not applicable to delegates
Hence it is better to set delegate thru a property
or keep the delegate as a public variable in the
publisher

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
672
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
MultiCast Delegate
Attaching more than one function to a delegate
When publisher calls the delegate all the attached
functions get invoked
Since there are more than one function all
Multicast delegates will be a void type functions!
Let us assume a Publisher sends out Greetings to
people registered
The Greetings are generated based on some
algorithm which we are not going to bother
about
What we consider here is how to register multiple
persons and receive the greeting!

public delegate void DelegateGreetings(string s);


©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
673
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Multicast – Publisher
public delegate void DelegateGreetings(string s);
public class Publisher
{
public DelegateGreetings DGMessage;

public void Greet()


{
DGMessage("Good Morning");
}
}

Nothing specific here about multicast


delegate except for void return type

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
674
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Multicast - Subscriber
public class Personal
{
private string Name;
public Personal(string name)
{
this.Name = name;
}
public void GreetMe(string msg)
{
Console.WriteLine(msg + " ," + Name + "!");
}
}
Subscriber – Personal implements a method with
matching Signature to receive the greeting /
Call !

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
675
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
MultiCasting…
Provide a Main method in another class which has
Personal p1 = new Personal("David");
Personal p2 = new Personal("Goliath");
Personal p3 = new Personal("Henry");
//Create 3 delegates
DelegateGreetings dg1 = new DelegateGreetings(p1.GreetMe);
DelegateGreetings dg2 = new DelegateGreetings(p2.GreetMe);
DelegateGreetings dg3 = new DelegateGreetings(p3.GreetMe);

//Delegates could be added with +


p.DGMessage = dg1 + dg2 + dg3;
p.Greet();

//could be removed with –


p.DGMessage -= dg2;
p.Greet();

Publisher invokes the method once but all the


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

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

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Anonymous methods

C# supports delegates for invoking one or


multiple methods. Delegates provide
operators and methods for adding and
removing target methods, and are used
extensively throughout the .NET Framework
for events, callbacks, asynchronous calls, and
Anonymous methods is a new feature in C#
multithreading.
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)
} {
} Kid k = new Kid();
void InvokePrint(KidDelegate del) k.PrintKid();
{ }
del();
} }
©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
{ message to be displayed from the
public void KidThread() new thread.

{
Thread T = new Thread(delegate() {
MessageBox.Show(“Kid is printed");
} );
T.Start();
}}
You saw that we used an anonymous method as a parameter
for launching a new thread without explicitly defining a
ThreadStart delegate or a thread method:

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
683
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Passing Parameters to Anonymous
Methods
When defining an anonymous method with parameters, you
define the parameter types and names after the delegate
keyword just as if it were a conventional method.
The method signature must match the definition of the
delegate to which it is assigned.
When invoking the delegate, you pass the parameter's
values, just as with a normal delegate invocation.

class Kid{
delegate void KidDelegate(string str);
public void InvokePrint()
{ KidDelegate del = delegate(string str)

{
System.Console.WriteLine(str);
};
del(" Kid is printed”);
}}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
684
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Anonymous methods
?
SomeDelegate del = delegate()
Anonymous methods without parameters
Ans
If the anonymous method has no parameters, you can
use a pair of empty parens after the delegate

class Kid {
delegate void KidDelegate();
public void InvokePrint()
{ KidDelegate del = delegate() {
System.Console.WriteLine("Kid is Printed");};
del(); }}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
685
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Anonymous methods
?
How about Anonymous methods with no
parenthesis
Ans
Yes Possible these are called special
delegates.
class kid {
delegate void KidDelegate(string str);
public void InvokePrint()
{ KidDelegate del = delegate {
System.Console.WriteLine("Kid is Printed");
};
del("Parameter is ignored"); }}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
686
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Anonymous methods

But wait …..

Note that you must still provide arguments when


invoking the delegate because the compiler generates
nameless parameters for the anonymous method
anonymous methods without a parameter list cannot
be used with delegates that specify out parameters.
An anonymous method can use any class member
variable, and it can also use any local variable defined
at the scope of its containing method as if it were its
own local variable.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
687
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Generic Anonymous Methods

An anonymous method can use generic parameter types,


just like any other method. It can use generic types
defined at the scope of the class
class Kid<T>
{
delegate void KidDelegate (T t);
public void InvokeKid (T t)
{
KidDelegate del = delegate (T item) {...}
Del (t);
}}
Delegates can define generic parameters, an anonymous method can
use generic types defined at the delegate level.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
688
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Anonymous methods
Ok lets sum up this.
Anonymous Methods are useful because it replaces
the need for creating a simple method in cases
where only a delegate will suffice.
class KidForm:Form
{
private Button button1;

KidForm()
{
this.button1 = new
System.Windows.Forms.Button();

this.button1.Name = "btnClick";

this.button1.Text = "Click";
this.Controls.Add(button1);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
689
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Anonymous methods
button1.Click += delegate(object sender, EventArgs args)
{
MessageBox.Show("Button Clicked !");
};
}
public static void Main()
{
Application.Run(new KidForm());
} }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
690
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Delegate Inference
The C# compiler's ability to infer from an anonymous method
assignment which delegate type to instantiate is an important capability.
In fact, it enables yet another C# 2.0 feature called delegate inference.
Delegate inference allows you to make a direct assignment of a method
name to a delegate variable, without wrapping it first with a delegate
object.

class Kid In C# 1.1


{
delegate void KidDelegate();
public void InvokePrint() {
KidDelegate del = new KidDelegate(PrintKid);
del();
}
void PrintKid() {...}}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
691
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Delegate Inference

class Kid
{ IN C# 2.0
delegate void KidDelegate();
public void InvokePrint()
{
KidDelegate del = PrintKid;
del();
}
void PrintKid() {...}
}

When you assign a method name to a delegate, the compiler first infers the
delegate's type. Then the compiler verifies that there is a method by that
name and that its signature matches that of the inferred delegate type.
Finally, the compiler creates a new object of the inferred delegate type,
wrapping the method and assigning it to the delegate.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
692
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Events

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Events
Declaring a multi cast delegate as a public property of a
publishing class may result in anybody invoking it

Events are there to rescue us!

Events are similar to multicast delegates they are used to


inform clients of some things happening in the publisher
But with a difference :
Only the publisher can fire an event (invoke the delegate
method)!

Events use delegates internally

Events are mostly used for UI components

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
694
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Events Greeting
Let us rewrite the greetings application using events
public delegate void GreetingsHandler(string message);
public class Publisher
{
public event GreetingsHandler GotGreetings; //Event
public Publisher() { }
//Wrapper to invoke events – Best Practice
protected virtual void OnGotGreetings(string message)
{
if (GotGreetings != null)
GotGreetings(message);
}
public void Greet() //Exercise Event Firing
{
OnGotGreetings("Good morning");
}
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
695
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Events Greeting
In publisher the event firing code is encapsulated
in a protected virtual function
Any class inheriting Publisher could override or
invoke this code!
Personal class is the same as before
Here is the code for subscribing to events

Personal p1 = new Personal("David");


Personal p2 = new Personal("Goliath");
Personal p3 = new Personal("Henry");

Publisher p = new Publisher();


//Subscribe to events
p.GotGreetings += new GreetingsHandler(p1.GreetMe);
p.GotGreetings += new GreetingsHandler(p2.GreetMe);
p.Greet();
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
696
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Events Conventions
Apart from best practice of making the event raising
wrapper function protected & virtual
• Event methods return void because of multicasting
• Event parameters
• An Object – Sender
• A class derived from EventArgs
Introduce a new class :
public class GreetingEventArgs : EventArgs
{
private string message;
public GreetingEventArgs(string message)
{
this.message = message;
}
public string Message //Property
{
get { return message; }
}
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
697
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Events Conventions
Change Publisher class :
public delegate void GreetingsHandler
(object o, GreetingEventArgs e);
public class Publisher
{
public event GreetingsHandler GotGreetings; //Event
public Publisher() { }
//Wrapper to invoke events – Best Practice
protected virtual void OnGotGreetings(string message)
{
if (GotGreetings != null)
GotGreetings(this, new GreetingEventArgs(message));
}
public void Greet() //Exercise Event Firing
{
OnGotGreetings("Good morning");
}
}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
698
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Event Conventions
Change personal class event handler code :
public void GreetMe(object o, GreetingEventArgs e)
{
Console.WriteLine(e.Message + " ," + Name + "!");
}

Exercise :
Create a Timer class which publishes a TimeChanged
event every second. This timer class will run for only
a preset amount of seconds. Notify new time using
eventargs (TimeChangedEventArgs with hour, minute
and second in the parameter)
Hint : Timer runs in a never ending loop but terminate
using the preset seconds. Use Thread.Sleep and
System.DateTime.Now to control the timer.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
699
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Exception Handling

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Exception Handling
• Error condition(fault) or Unexpected behavior
• Happen in our code or the code that we call
• Can be application specific or the platform or runtime
specific errors
• Can recover from application errors
• Say an invalid input ask user to enter again
• Cannot recover from runtime exceptions
• A resource not found

• It is better to be balanced not over use and at the same


time under use exceptions
• Check the conditions in code where you can
• Handle exceptions when you cannot
We can create our own application specific exceptions
and use them

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
701
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Exception Language elements
There are 3 block definitions (Handle exceptions)
and 1 statement (to raise an exception)
try – Block :
• Have statements that could potentially cause exception(s)
catch – Block :
• Statements that can be used to take an action (log / display
error message, run the recovery code etc.)
• Each type of exception will be caught using a separate catch
statement
finally – Block :
• Statements used to cleanup
• Executes always whether an exception occurred or not
Throw statement :
throw new <exception class(args)>

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
702
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Mechanism
class BadClass //simulates a method which could go wrong
{
public static void BadMethod()
{
throw new ArgumentException("Test throw"); //throw an exception
}
}

static void Main(string[] args)


{
try
{
BadClass.BadMethod();
}
catch(Exception e) //catch Any exception
{
Console.WriteLine("Got an exception : {0}", e.Message);
}
finally
{
Console.WriteLine("Cleaning up");
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
703
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Mechanism
Code in try block executes (Badmethod is invoked)
Exceptions occurs and caught by the catch statement
(Infact any exception could be caught here)
Finally executes
If we remove the BadMethod call in the try we can see that
finally is executed still
Here we have caught the exception using the generic base
class exception
This is not a good idea since all exceptions will be handled
by one catch and we cannot take different action for
different exceptions
The best thing is to catch & handle the individual exceptions
first and catch the generic exception as a last catch
Thorough testing helps Better exception handling

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
704
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Recommended
try {
//statements that could throw exceptions
}
catch (SpecificException1 se1) {
//handle here
}
catch (SpecificException2 se2) {
//handle here
}
catch (SpecificException3 se3) {
//handle here
} …
Finally {
//Clean up resources
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
705
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
User Defined Exceptions
Can be thrown if some other exception is
encountered (in a catch statement) or during
other conditions(mostly a check done in code)
Create a class with name ending in Exception
deriving from ApplicationExcption class

Constructors to be provided
• Avoid default constructor
• When another exception is the cause
public myappException(string message, Exception cause)
• When an exception is thrown this way it is easy to check the
StackTrace property for fixing
• Otherwise
public myappException(string message)
• StackTrace is usefull here also
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
706
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Sample
public class EmployeeListNotFoundException:
ApplicationException
{
public EmployeeListNotFoundException(string message)
: base(message)
{
}
public EmployeeListNotFoundException(string message,
Exception inner): base(message, inner)
{
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
707
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Inline Warning

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Inline Warning
We have seen that in C# 1.1 we can disable specific compiler warnings
using project settings or by issuing command-line arguments to the
compiler.

The problem here is that this is a global suppression, and it also


suppresses warnings that you still want.

In C# 2.0 we have a solution to this crises by using inline


warning.
Inline Warning allows you to explicitly suppress and restore
compiler warnings using the #pragma warning directive.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
709
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Inline Warning
Example
#pragma warning disable 169

public class MyClass


{
int m_Number;
}
#pragma warning restore 169

Note that you cannot programmatically override the project settings, meaning you
cannot use the pragma warning directive to restore a warning that is suppressed
globally.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
710
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Refactoring Support Under
Visual Studio 2005

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Defining the Refactoring Process
Refactoring is a formal and mechanical process, used
to modify existing code in such a way that it does
indeed become 'better' while preserving the
program's intended functionality. In addition to
improving a program's overall design, the refactoring
process tends to yield code which is far easier to
maintain and extend in the long run.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
712
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Refactoring Support Under Visual Studio 2005

In the bad old days, refactoring typically involved a


ton of manual labor. Once developers identified the
code to modify, they tended to make substantial use
of copy, paste, find, replace, compile, test (repeat)
techniques. This was time-intensive difficult and
error prone.

With Visual Studio 2005 you can automate the


refactoring process. Using the Refactoring menu you
can dramatically reshape your code with minimal
fuss and trouble.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
713
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Studio 2005 refactorings.
Refactoring Technique What it does

Extract Method This allows you to define a new method


based on a selection of code statements.

Encapsulate Field Turns a public field into a private field


encapsulated by a .NET property.

Extract Interface Defines a new interface type based on a set


of existing type members.

Reorder Parameters Provides a way to reorder member


arguments.

Remove Parameters As you would expect, this refactoring


removes a given argument from the current list
of parameters.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
714
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Studio 2005 refactorings.
Refactoring Technique What it does

Rename This allows you to rename a code token


(method name, field, local variable, and so on)
throughout a project.

Promote Local Variable to Parameter Moves a local variable to the parameter set
of the defining method.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
715
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough - Extract Method

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
716
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough - Extract Method

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
717
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough - Extract Method

At this point, you will be


presented with a dialog
box that allows you to
enter the name of the
new method to be
generated

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
718
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough - Extract Method

Notice that the new method is


automatically defined as
private and static, as the code
statements did not refer to
any instance level variables
(generally speaking, extracted
methods will be given the
most restrictive modifiers
possible).

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
719
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Encapsulate Field

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
720
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Encapsulate Field
If you have checked the 'Preview
Reference Changes' checkbox, you
will then be presented with a final
dialog that documents the full
results of the proposed change

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
721
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Encapsulate Field

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
722
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Encapsulate Field

Here is the end result of this


Encapsulate Field
refactoring.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
723
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Extract Interface

The Extract Interface


refactoring allows you to select
a group of existing type
members to yield a new
interface abstraction.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
724
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Extract Interface

Note   You can also extract an interface by simply highlighting the name of


the class (or structure) and activating the Refactoring menu, rather than
selecting a set of type members.
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
725
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Extract Interface

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
726
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Local Variable to Parameter

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
727
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Local Variable to Parameter

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
728
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Reorder Parameters

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
729
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Reorder Parameters
Like other Visual Studio 2005
refactoring options, you are next
presented with a configuration dialog
box. In this case, you are able move a
particular argument up or down the
chain

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
730
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Reorder Parameters

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
731
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Rename Parameters

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
732
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Rename Parameters

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
733
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Rename Parameters

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
734
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Remove Parameters

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
735
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Walkthrough – Remove Parameters

At this point, you will be


presented with a configuration
dialog where you are able to
select the parameters you wish
to remove

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
736
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thank You

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Programming
with
.NET Framework

COE – Current Technologies


Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Assembly and CLR

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
740
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Assemblies
• Assemblies are the .NET unit of reuse,versioning and
deployment.
• Self describing components that have no
dependencies on registry entries.
• Assemblies are a unique feature of .NET applications
that simplify application deployment
• Assemblies solve the versioning problems that can
occur with component based applications.
• To the user an assembly appears as a single .dll
(Collections of classes and methods that are linked
into the program at runtime) or .exe.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
741
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
An end to DLL Hell
An end to “DLL Hell” : Occurred due to version conflicts
where installing one application can break an existing
application because the existing dll was not fully
backward compatible with a previous version.
Assemblies provide a solution to this nightmare by
the unique identification through version number.

As a result of assemblies different versions of .NET


applications can co-exist on the same machine
independently without interference.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
742
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Assemblies
Structure of an Assembly:
In general an assembly can consist of four elements:
• The assembly manifest which contains assembly metadata.
• Type manifest.
• MSIL(Microsoft Intermediate Language) that implements the
types.
• A set of resources.
These resources can be grouped into an assembly in the form of
• Single-file assembly.
Figure 1

Assembly
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 files required by the application.
Assembly
metadata Type
metadata
Type MSIL Code
metadata

MSIL .
Code
netmodul
Resources
e
MyAssembly.
Graphic.b
dll
mp
Fig 2: Elements of a multifile Assembly

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
744
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Mutimodule Assemblies(Contd..)
Advantage of a Mutimodule Assembly:
• The .NET framework downloads a file only when
referenced keeping infrequently referenced code in a
separate file.
• The files that make up a multimodule assembly are
not physically linked by the file system .
• These files are linked through an assembly manifest
and the CLR manages them as a unit.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
745
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Metadata and Manifest
On disk,assemblies are Portable Executables(PE)
implemented as .dll or .exe and contain a single
entry point(DLLMain, WinMain, Main).
Metadata:
• Is the information stored in the assembly that
describes the types and methods of an assembly.
• Assemlies are self descriptive because metadata fully
describes the contents of each module.
Manifest:
• Is a block of metadata that describes the types and
methods of the assembly.
• Assemblies are self descibing due to the metadata.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
746
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Types of Manifest
Is of 2 types:
(1) Assembly manifest : Contains information about
• Version
• Security
• Dependency of an assembly
(2) Type manifest:
• Contains information about the types within the
assembly.This includes the user defined types e.g. classes,
structs and the build in types.
• .NET maintains a strong type checking before executing
any type.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
747
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Assemblies
Examining the manifest: The structure of manifest can be examined
using the ILDASM.exe which is provided as part of .NET framework.
On the Visual Studio .NET Command Prompt type ILDASM.In the file
menu open the dll or exe of a project. The file will look like this.

Figure 3
The figure shows a tree view that allows inspection of the
manifest,various classes and methods contained within the
assembly.On clicking the manifest,it is revealed as in Figure 4.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
748
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating a Multimodule
Assembly(Contd..)

Figure 4

Manifest of an
assembly

Modules in the manifest:


• A module is a non executable code with .netmodule extension.
• Assemblies can contain one or more such netmodules which in
turn contains the manifest describing that module.
• The module manifest lists the assemblies and types referenced
by that module.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
749
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating a Multimodule Assembly
A single module assembly has a single file (exe / dll).This single
module contains all the types and implementations for the
application.The Assembly manifest is contained within this
module.
Creating a multi module Assembly:
Step 1: Compiling files with Namespaces referenced with other files
using System;
namespace myNamespace
{
public class MultiMod
{
public void multiMod()
{
System.Console.WriteLine("This is a line from mutiMod
method");
}
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
750
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating a Multimodule Assembly
Use the following command to compile this file
csc /t:module MultiMod.cs
Specifying the /t option indicates that the file should be compiled
as a module rather than an assembly.The compiler produces a
module MultiMod.netmodule,which can be added to the
assembly.
Step 2: Compiling modules with reference to other modules
using System;
using myNamespace; //The namespace created in the
MultiMod.netmodule
class myMultiMod {
//Static method Main is the entry point method.
public static void Main()
{
MultiMod mod=new MultiMod();
Console.WriteLine("Client code executes");
//Calling the multiMod method from the MultiMod class
mod.multiMod();
}©2007
} Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
751
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating a Multimodule Assembly
Use the following command to compile this code
csc /addmodule:MultiMod.netmodule /t:module myMultiMod.cs
This module references a method from the
MultiMod.netmodule.The /t:module option specifies to create a
module that would be later added to the assembly.
Step 3: Creating a Multifile assembly using the Assembly linker
You can use the Assembly Linker(Al.exe) to create an assembly
from a collection of compiled netmodules
At the Visual Studio .NET command prompt type the following:
al myMultiMod.netmodule MultiMod.netmodule
/main:myMultiMod.Main /out:myAssembly.exe /target:exe

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
752
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating a Multimodule Assembly

When the resulting dll is examined with MSIL


Disassembler(ILDasm.exe), it shows the following screen.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
753
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Assemblies
Assemblies are of 2 types based upon their accessibilty
1. Private Assemblies:
• Used by single application.
• Created by default after a .Net application is compiled.
• Can be redeployed on another machine just by copying the files
contained with the application folder.
2. Shared Assemblies:
• Shared by other applications.
• Such an assembly needs to be installed into an area of
filesystem set aside by CLR for Shared assemblies called Global
Assembly Cache(GAC) .
• Before the assembly can be installed into the GAC it needs to be
signed with a unique ID called strong name.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
754
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Global Assembly Cache
Global Asssembly Cache:
• Each computer which has the CLR has a machine
wide code cache called the GAC .
• GAC stores the assemblies to be shared by several
applications on the computer.
• Each assembly installed into the GAC is uniquely
identified by its name and version.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
755
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Assembly Version
Assembly Versions:
• The GAC allows “side by side versions where the older version
may co-exist with the newer version.T
• The assemblies version number together with the assembly
name and culture information is part of the assembly’s identity.
The version number is physically represented as part of the
assembly manifest in form of a four part string in the following
format.
<major version>:<minor version>:<build number>:<revision>
The version checking by the CLR ensures that only the assembly
with the right version number is loaded at runtime.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
756
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Strong named Assemblies and Signcode:

Signing an assembly with a strong name ensures a


• Globally unique name for the assembly
• Prevent tampering of the assembly by providing
digital signatures and public key encryption.
• The correct assembly authored by the actual creator
is loaded.
All the above is ensured by giving an assembly a Strong
Name using
sn –k utility.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
757
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Strong named Assemblies and Signcode:

To ensure greater security , an assembly can be signcoded ( with


Signcode.exe) using digital certificates purchased from a third
party vendor.
Strong naming and digital certificates guarantee foolproof integrity.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
758
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Installing an Assembly into the GAC
Assemblies can be shared by installing them into GAC by
any of the ways:
1. Using a Developer tool called Global Assembl Cache
tool (GacUtil.exe).
2. Using Windows explorer to drag the assembly.
Step 1: Strong naming an Assembly:
On the Visual Studio .NET comand prompt type
sn –k myStrongName.snk
The –k option along with sn(strong name utilty)
indicates to create a file containing the key value pair.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
759
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Installing an Assembly into the GAC
Step 2: Associate the Strong name with the assembly(if using a VS
IDE)
You can associate this strong name with your assembly in the
assemblyinfo.cs file in the predefined attribute
using System.Runtime.CompilerServices;
[assembly:AssemblyKeyFile(“.\myStrongName.key ”)]
If not using a VS IDE associate the strong name with the exe/dll
using
al /out:MyAssembly.dll myMultiMod.netmodule /keyfile: myStrongName.snk

Step 3: Installing to the GAC.


On the VS.NET command prompt type
gacutil –i myAssembly.dll
“ Assembly successfully added to the cache” message id displayed on
the command prompt.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
760
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Installing an Assembly into the GAC
Assemblies can also be installed into GAC using
windows explorer like utility.
Open C:\Winnt \assembly or C:\Windows\assembly
The window changes to a GAC explorer displaying the
name,type,version,culture and public key token no of
all assembles installed into GAC. Drag and drop
your .dll into the window.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
761
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Installing an Assembly into the GAC
Each assembly is uniquely identified with a public key token number
assigned by the CLR.This number can be seen for any assembly by
writing on the VS.Net command prompt.
sn -Tp myAssembly.dll
Sample output is:

Public key is
0024000004800000940000000602000000240000525341310004000001000
1004dcc7b5243839e5789e1f12bbd817daf20a55fe22bc0a29e7c245137f22
7c2980cf0415356154221111c37e2ce33ff666526a35dd08f1b7e5ca6235ab
d156f702243df4e86b29a37213cc8105a9cb774fba036d4b7ac116b8f2a1d4
1bb73f5644771eefb359fdecd7059437bedbfd0cf7e2092ddf0bf3ad200b1c5
547fa7cbb4
Public key token is a179f8bc5bfc3463

DIY:
Create a mutlimodule assembly, signcode it and install it into the Global
Assembly Cache (GAC).

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
762
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Application Domains

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
• Understanding Application Domains.
• Benefits of Application Domains.
• Creating Application Domains.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
764
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Application Domains
The operating system creates separate process boundaries for
each application.Each Win32 application runs in its own process
along with a 4GB virtual address space.Additional libraries or
components share this address space.
Understanding Application Domains
• Application domains provide a secure and versatile unit of
processing .
• The common language runtime can use Application Domains to
provide isolation between applications.
• You can run several application domains in a single process
with the same level of isolation that would exist in separate
processes.
• Application Domains run without incurring the additional
overhead of making cross-process calls or switching between
processes.
• The ability to run multiple applications within a single process
dramatically increases server scalability.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
765
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Application Domains

EXE EXE EXE

DL DL DL
L L DLL L

Process A Process Process B


Figure 1: The Win32 Process boundary.Separate
C
Processes
PROCESS
A

DLL EXE DLL

EXE EXE EXE

App Domain App Domain App Domain


Figure 2 : A PROCESS DIVIDED INTO
APPLICATION DOMAINS
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
766
Benefits of Application Domains
The isolation provided by application domains has the following
benefits:
1) Faults in one application cannot affect other applications. Because
type-safe code cannot cause memory faults, using application
domains ensures that code running in one domain cannot affect
other applications in the process.
2) Individual applications can be stopped without stopping the entire
process. Using application domains enables you to unload the code
running in a single application.
3) Code running in one application cannot directly access code or
resources from another application. The common language
runtime enforces this isolation by preventing direct calls between
objects in different application domains. Objects that pass
between domains are either copied or accessed by proxy.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
767
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Benefits of Application Domains(Contd..)

4) The behavior of code is scoped by the application in


which it runs. In other words, the application
domain provides configuration settings such as
application version policies, the location of any
remote assemblies it accesses, and information
about where to locate assemblies that are loaded
into the domain.
5) Permissions granted to code can be controlled by
the application domain in which the code is running.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
768
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Application Domains
A new Application Domain can be created by calling the static
method CreateDomain() on the AppDomain class.
AppDomain ad =
AppDomain.CreateDomain(“Our Domain", null, null);
Where the first parameter passed to the CreateDomain method
is the friendlyname,second parameter is the securityinfo
while the last parameter is info belonging to the
System.AppDomainSetup.
You can check the friendly name of the domain you're working
in with the property
System.AppDomain.CurrentDomain.FriendlyName.
Once you have instantiated an AppDomain object, you can
create instances of classes, interfaces, and so forth using its
CreateInstance( ) method. Here's the signature:

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
769
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating Application Domains
public ObjectHandle CreateInstance(
string assemblyName,
string typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
object[] args,
CultureInfo culture,
object[] activationAttributes,
Evidence securityAttributes
);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
770
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Threads

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion

• About Threads
• Creating and starting threads.
• Understanding Threads.
• Thread Lifecycle.
• Suspending a Thread.
• Joining Threads.
• Thread States.
• Thread Priorities.
• Thread Synchronization.
• Race Condition and deadlocks.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
772
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Threads
• Threads are lightweight processes responsible for multitasking
within a single application.
• Threads are typically created when you want a program to do
two things at once.
• The System.Threading namespace provides classes and
interfaces to manage multithreaded programming.
• Threads are closely related to multitasking and are used by
the CLR to manage multiple tasks.
• In .NET , the CLR encapsulates the functionality of Threading
into classes that greatly simplify most threading tasks.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
773
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating and Starting Threads
• Create a new instance of the Thread class. The constructor of the Thread
class takes a single argument- a delegate type called ThreadStart which
points to a method that we create. The method passed to the delegate
must take no parameters and returns void.
• Public delegate void ThreadStart(); // Predeclared delegate
The method to be attached to this delegate must take no parameters
and must return void.
• Thread myThread=new Thread(new ThreadStart (myFunc));
Even though the Thread instance is created,it will not start.To start the
thread call the Start method on the Thread object.
myThread.Start();

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
774
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Understanding Threads
public class ThreadsDemo
{ public void testThread() {
Thread t1=new Thread(new ThreadStart (incrementer));
t1.Start();
Thread t2=new Thread(new ThreadStart (decrementer));
t2.Start(); }
public void incrementer() {
for(int x=2;x<=50;x++)
{Console.WriteLine("Good Morning {0}",x); }
}
public void decrementer()
{ for(int y=50;y>=1;y--)
{
Console.WriteLine("Good Evening {0}",y);
}
}
public static void Main()
{ ThreadsDemo td=new ThreadsDemo();
td.testThread();
} }
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
775
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thread LifeCycle
A Thread, as previously discussed is started with Thread.Start() method.
A started Thread may be paused or suspended for a period of time.
Suspending Threads:
Calling the Thread.Sleep() method causes the current thread to suspend for
the given time, passed as milliseconds ,yielding the remainder of its time
slice to another thread.
Thread.Sleep() is a public static method and has 2 overloads, one accepts
a timespan and the second the time in milliseconds for which the thread
should be allowed to sleep.The threads resumes after the given time has
lapsed.
Calling Thread.Sleep(Timeout.Infinite) causes a thread to sleep until it is
interrupted by another thread that calls Thread.Interrupt or is aborted by
Thread.Abort.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
776
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thread LifeCycle
Pausing a Thread: A thread can be paused by calling
the static method
Thread.Suspend.The thread remains suspended until
another threads calls the Thread.Resume on the
suspended thread.
Killing Threads:
The Thread.Abort method is used to stop a logical
thread permanently. When you call Abort, the
common language runtime throws a
ThreadAbortException, which the thread can catch.
Thread.Interrupt wakes a thread out of any wait it
might be in and causes a ThreadInterruptedException
to be thrown in the destination thread.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
777
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Suspending a Thread
public class ThreadInterruptDemo {
public static void Main(){
ThreadInterruptDemo thd=new ThreadInterruptDemo();
thd.testInterrupt();}
public void testInterrupt(){
Thread th1=new Thread(new ThreadStart(moveUp));
th1.Start();
Thread.Sleep(5000);//Causes the Thread to sleep for 5 seconds befor
starting the other Thread.
Thread th2=new Thread(new ThreadStart(moveDown));
th2.Start(); }
public void moveUp(){
for(int k=0;k<100;k++)
{
Console.WriteLine("Up {0}",k);
}}
public void moveDown(){
for(int m=100;m>1;m--)
{
Console.WriteLine("Down {0}",m);
}
}}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
778
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Joining Threads
Blocks the calling thread until a thread terminates.
When you tell a thread to stop processing and wait until a
second thread
completes its work, you are said to be joining the first
thread to the second. To join thread 1 (t1) onto thread 2
(t2), you write:
t2.Join( );
If this statement is executed in a method in thread t1, t1
will halt and wait until t2 completes and exits.
Blocks the calling thread until a thread terminates or the
specified time elapses. public bool Join(int);
Blocks the calling thread until a thread terminates or the
specified time elapses. public bool Join(TimeSpan);

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
779
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Joining Threads(Demo)
The following example uses the Join() method to wait
for the new thread to terminate. If the Join() method
were not called by the main thread of this sample, a
race condition would occur between the two threads. If
this were to happen, the second thread may not be
able to finish processing before the application exits.
using System;
using System.Threading;
class App {
static void MyThreadMethod() {
Console.WriteLine("This is the secondary thread running.");
}
static void Main() {
Console.WriteLine("This is the primary thread running.");
// MyThreadMethod is the secondary thread's entry point.
Thread t = new Thread(new ThreadStart(MyThreadMethod));
// Start the thread
t.Start();
// Wait for the thread to exit
t.Join();
Console.WriteLine("The secondary thread has terminated.");
} }
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
780
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thread States
The property Thread.ThreadState provides a bit mask that indicates the thread's
current state. A thread is always in at least one of the possible states in the
ThreadState enumeration, and can be in multiple states at the same time.
Action New State
The thread responds to Thread.Start and starts running. Running
The thread calls Thread.Sleep.WaitSleep Join
The thread calls Monitor.Wait on another object. WaitSleepJoin
The thread calls Thread.Join on another thread. WaitSleepJoin
Another thread calls Thread.Suspend. SuspendRequested
The thread responds to a Thread.Suspend request. Suspended
Another thread calls Thread.Resume. Running
Another thread calls Thread.Interrupt. Running
Another thread calls Thread.Abort. AbortRequested
The thread responds to a Thread.Abort. Aborted

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
781
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thread Priorities
Threads are scheduled for execution based on their priority. The scheduling
algorithm used to determine the order of thread execution varies with
each operating system .
ThreadPriority defines the set of all possible values for a thread priority.
Thread priorities specify the relative priority of one thread versus another.

1. AboveNormal : The Thread can be scheduled after threads with Highest


priority and before those with Normal priority.
2. BelowNormal : The Thread can be scheduled after threads with Normal
priority and before those with Lowest priority.
3. Highest : The Thread can be scheduled before threads with any other
priority.
4. Lowest : The Thread can be scheduled after threads with any other
priority.
5. Normal : The Thread can be scheduled after threads with AboveNormal
priority and before those with BelowNormal priority. Threads have Normal
priority by default.Requirements.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
782
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Understanding Threads
public class ThreadsJoin{
public static void Main(){
ThreadsJoin tj=new ThreadsJoin();
tj.workThreads(); }
public void workThreads() { Thread[] th=
{
new Thread(new ThreadStart(goodMorning)),
new Thread(new ThreadStart(goodNoon)),
new Thread(new ThreadStart(goodEvening)) };
for(int i=0;i<3;i++){
th[i].Start(); }
Thread.Sleep(3000);
th[1].Interrupt();
Console.WriteLine("Good Noon interrupted");
th[2].Join();
Console.WriteLine("All the threads have
finished"); }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
783
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Understanding Threads
public void goodMorning()
{ for(int x=0;x<50;x++) {
Console.WriteLine("Good Morning
{0}",x); }
}
public void goodNoon()
{ for(int y=50;y>1;y--) {
Console.WriteLine("Good Noon
{0}",y); }
}
public void goodEvening()
{ for(int m=50;m<100;m++) {
Console.WriteLine("Good Evening
{0}",m);
}}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
784
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Thread Synchronization
Thread Synchronization is the mechanism to control access to
a shared resource by simultaneous Threads so that the
other threads do not interfere while the resource is held by
the first thread hs finished with it. It is achieved through:
1. Interlock class,
2. the C# lock statement,
3. the Monitor class.
Interlock: C# offers a special class, Interlocked to offer
synchronization protection for common tasks such as
incrementing and decrementing.
The following example makes the point clear

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
785
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Synchronization(Contd..)
using System;
using System.Threading;
class Tester {
private int counter = 0;
static void Main( ) { // make an instance of this class
Tester t = new Tester( ); // run outside static Main
t.DoTest( ); }
public void DoTest( ){
Thread t1 = new Thread( new ThreadStart(Incrementer) );
t1.IsBackground=true;
t1.Name = "ThreadOne";
t1.Start( );
Console.WriteLine("Started thread {0}", t1.Name);
Thread t2 = new Thread( new ThreadStart(Incrementer) );
t2.IsBackground=true;
t2.Name = "ThreadTwo";
t2.Start( );
Console.WriteLine("Started thread {0}",t2.Name);
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
786
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Synchronization(Contd..)
t1.Join( ); t2.Join( ); // after all threads end, print a message
Console.WriteLine("All my threads are done."); }
// demo function, counts up to 1K
public void Incrementer( )
{ try {
while (counter < 1000){
Interlocked.Increment(ref counter); // simulate some work in this
method
Thread.Sleep(1); // assign the decremented value and display the
results
Console.WriteLine("Thread {0}. Incrementer:
{1}",Thread.CurrentThread.Name,counter); } } }
catch (ThreadInterruptedException) {
Console.WriteLine("Thread {0} interrupted! Cleaning
{Console.WriteLine("Thread {0} Exiting.
",Thread.CurrentThread.Name);}}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
787
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Synchronization
Synchronization can also be achieved through the use of
lock.
Lock is a more general synchronization mechanism.
• A lock marks a critical section of your code, providing
synchronization to an object you designate while the
lock is in effect.
• The syntax of using a Lock is to request a lock on an
object and then to execute a statement or block of
statements.
• The lock is removed at the end of the statement block.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
788
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Synchronization
public void Incrementer( )
{ Try
{
while (counter < 1000) {
lock (this) {
int temp = counter;
temp ++;
Thread.Sleep(1);
counter = temp;
}
// assign the decremented value and display the results
Console.WriteLine( "Thread {0}. Incrementer:
{1}",Thread.CurrentThread.Name,counter); } }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
789
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Race Condition
Race condition
• Exists when the success of your program depends on
the uncontrolled order of completion of two
independent threads.
• Eg while opening a file using a thread the other
thread would not start writing to the file until the first
thread has finished opening the file.
• This is race condition which can be avoided by the
use of Monitor and Wait() method before starting
Thread2.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
790
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
DeadLock
DeadLocks:
• Deadlock condition ,also called deadly embrace is
caused when two threads.
• These threads try to access a resource which has
already been locked by the other thread.
• Each thread waits for the other to release the lock on
the resource. In turn neither of the threads would
be able to get access to the resource being held by
the other thread.
• This condition is resolved when either of the threads,
part of the deadlock relinquishes the resource.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
791
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Do it yourself (DIY)
(1)Create a “stop watch” application using Threads. It
should contains 2 buttons to start and stop the
watch. Also time should be depicted in Hrs:
Min:Sec:MilliSecs.
(2)Create a multithreaded application in which the
Principal ,Rate of interest and time for leasing the
loan should be accepted from the console. The
amount to be repaid should be calculated and
displayed using one thread. The other thread should
display the current time and date whenever the
amount is displayed.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
792
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
File Handling

Australia | Canada | France | India | New Zealand | Singapore | Switzerland | United Arab Emirates | United Kingdom | United States

www.keane.com. ©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to
Keane. Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
• Streams
• Working with Directories.
• Methods of Directory class.
• Methods of Directory and DirectoryInfo class.
• Working with Directories.
• Creating and Deleting subdirectories.
• Finding the No. of subdirectories within specified directory.
• Moving Directories.
• Working with Files.
• Synchronous and Asynchronous IO.
• FileMode enumeration members.
• Exploring the File Class
• Working with File Class methods

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
794
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Topics of Discussion
• Readers and Writers.
• Working with BinaryReader and BinaryWriter.
• Working with StreamReader and StreamWriter.
• Working with TextReader and TextWriter.
• Working with Buffered Streams.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
795
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Streams
Stream can be defined as a sequential flow of bytes travelling from a
source to a destination along a communication path. The end point
of a stream is a backing source which might be a disk file, a network
connection or a memory buffer. The source and destination of a
stream may change depending upon the condition.
The classes needed for reading from files or writing data to files as
present within the System.IO namespace.
The .NET Framework provides both buffered and unbuffered streams,
and provides classes for asynchronous I/O as well.
To create a stream of data, your object must be serialized, or written
to the stream as a series of bits.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
796
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Working with Directories
The Directory class represents a directory and contains
static methods for creating, moving and exploring
directories. The directory class being static, the
methods are invoked using the class name and not its
instance.

The DirectoryInfo class is another class which has


instance members and are invoked through the class
instance. DirectoryInfo derives from FileSystemInfo,
which in turn derives from MarshalByRefObject

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
797
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Methods of Directory class
Method Description
CreateDirectory() Creates Directory/SubDirectory specified by the path argument.

Delete() Deletes the directory and its contents.

Exists() Returns a true value if the directory specified in the path


parameter exists else false.
GetFiles() Returns an array of strings with filenames within the specified
directory.
GetDirectoryRoot Gets the root of the specified directory.
GetCurrentDirectory() Returns or Sets the current Directory.
SetCurrentDirectory()

GetLogicalDrives Returns an array indicating the logical drives on the hard disk.

GetDirectories Gets an array of subdirectories within the specified directory.


GetLastAccessTime() Gets or sets the last time the specified directory was accessed.
SetLastAccessTime()

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
798
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Methods of DirectoryInfo class
The prominent attributes and methods of DirectoryInfo class are :
Method/Property Description
Attributes Gets or sets the attributes of the current file.
CreationTime Gets or sets the creation time of the current file.
Exists Returns a boolean value true if the specified file exists.
LastAccessTime Gets or sets the last access time of a directory.
CreateSubDirectory() Creates a subdirectory on the specified path.

Delete() Deletes the specified directory with all its contents.


GetDirectories() Returns an array of subdirectories within a specified
directory.
GetFiles() Method that returns a list of files in the given directory.

MoveTo() Public method that moves the directory along with its
contents to the new path.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
799
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Working with Directories
using System;
using System.IO;
class Test {
public static void Main() {
// Specify the directories you want to manipulate.
DirectoryInfo di = new DirectoryInfo(@“D:\MyDir");
try {
// Determine whether the directory exists.
if (di.Exists){
// Indicate that it already exists.
Console.WriteLine("That path exists already.");
return; }
// Try to create the directory.
di.Create();
Console.WriteLine("The directory was created successfully.");
// Delete the directory.
di.Delete();
Console.WriteLine("The directory was deleted successfully.");}
catch (Exception e){
Console.WriteLine("The process failed: {0}", e.ToString());
} finally {} }}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
800
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Creating and Deleting Subdirectories

using System;
using System.IO;
public class CreateSubTest {
public static void Main() {
// Create a reference to a directory.
DirectoryInfo di = new DirectoryInfo("TempDir");
// Create the directory only if it does not already exist.
if (di.Exists == false)
di.Create();
Console.WriteLine("Directory "+di.Name+"successfully created");
// Create a subdirectory in the directory just created.
Console.WriteLine("Sub directory "+dis.Name +" created within
"+di.Name+" directory ");
DirectoryInfo dis = di.CreateSubdirectory("SubDir");
// Delete the subdirectory.
dis.Delete(true);
//To view the subdirectories comment out the delete statements
// Delete the directory.
di.Delete(true);
}}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
801
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Finding the No. of subdirectories within specfied
directory
using System;
using System.IO;
class Test {
public static void Main() {
try {
DirectoryInfo di = new DirectoryInfo(@"c:\");
// Get only subdirectories that contain the letter "p."
DirectoryInfo[] dirs = di.GetDirectories("*p*");
Console.WriteLine("The number of directories containing the
letter p is {0}.", dirs.Length);
foreach (DirectoryInfo diNext in dirs) {
Console.WriteLine("The number of files in {0} is {1}",
diNext,
diNext.GetFiles().Length); } }
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}}
©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
802
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Moving Directories
using System;
using System.IO;
public class MoveToTest
{ public static void Main()
{ // Make a reference to a directory.
DirectoryInfo di = new DirectoryInfo("TempDir");
// Create the directory only if it does not already
exist.
if (di.Exists == false)
di.Create();
// Create a subdirectory in the directory just created.
DirectoryInfo dis = di.CreateSubdirectory("SubDir");
// Move the main directory. Note that the contents move with the
directory.
if (Directory.Exists("NewTempDir") == false)
di.MoveTo("NewTempDir");
try {
// Delete the subdirectory.It has been moved, an exception is
thrown.
dis.Delete(true); }

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
803
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Moving Directories
catch (Exception) {
// Handle this exception in some way, such as with the
following code:
Console.WriteLine("That directory does not exist."); }
// Point the DirectoryInfo reference to the new
directory.
//di = new DirectoryInfo("NewTempDir");
// Delete the directory.
//di.Delete(true);
}
}

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
804
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Working with Files
File class and the FileInfo class are used for typical operations such as copying,
moving, renaming, creating, opening, deleting, and appending to files.
Like the methods of Directory, all the File methods are static; and like
DirectoryInfo, all the methods of FileInfo are instance methods.
To customize the behavour of various file methods, the following enumerations are
used:
FileAccess Specifies read and write access to a file. Can have
Read(Numeric Value 1) ,Write (Numeric Value 2) and
ReadWrite (Numeric Value 3) members.

FileShare Specifies the level of access permitted for a file that is


already in use. Can have Inheritable (Numeric value 16)
,None (Numeric value 0),Read (Numeric value 1)
,ReadWrite (Numeric value 3),Write (Numeric value 2)
members
FileMode Specifies whether the contents of an existing file are
preserved or overwritten, and whether requests to create
an existing file cause an exception.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
805
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Synchronous and Asynchronous IO

Synchronous I/O means that the method is blocked until the I/O
operation is complete, and then the method returns its data.
With asynchronous I/O, a user can call BeginRead() or
BeginWrite(). The main thread can continue doing other work,
and later the user will be able to process the data. Also,
multiple I/O requests can be pending simultaneously.
With large files, or when reading or writing across the network,
you'll want asynchronous I/O,which allows you to begin a
read and then turn your attention to other matters while the
CommonLanguage Runtime (CLR) fulfills your request. The
.NET Framework provides asynchronous I/O through the
BeginRead( ) and BeginWrite( ) methods of Stream.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
806
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
FileMode enumeration members
Member Name Description
Append Opens the file if it exists and seeks to the end of the file, or
creates a new file. FileMode.Append can only be used in
conjunction with FileAccess.Write. Any attempt to read fails
and throws an ArgumentException.
Create Specifies that the operating system should create a new file.
If the file already exists, it will be overwritten.

CreateNew Specifies that the operating system should create a new file.
If the file already exists, an IOException is thrown.

Open Specifies that the operating system should open an existing


file. The ability to open the file is dependent on the the value
specified by FileAccess.
OpenOrCreate Specifies that the operating system should open a file if it
exists; otherwise, a new file should be created

Truncate Specifies that the operating system should open an existing


file. Once opened, the file should be truncated so that its size
is zero bytes.

©2007 Keane. All rights reserved. Confidentiality: The concepts and methodologies contained herein are proprietary to Keane.
807
Duplication, reproduction or disclosure of information in this document without the expressed written permission of Keane is prohibited.
Exploring the File Class
Method Description
Create() Creates a new file at the specified path.

CreateText() Creates a StreamWriter to append text to a specified file.

Delete() Deletes a specified file.


Copy() Copies the contents of an existing file to a new file.
Exists() Returns a boolean value true if the given file exists.

OpenRead() Opens a file using FileStream.

OpenWrite() Opens the file for writing using the FileStream.

GetLastAccessTime() Returns or sets the last time the specified file was accessed.
SetLastAccessTime()
GetLastWriteTime() Returns or sets the last time the specified file was written to.
SetLastWriteTime()

©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