1672

Click here to load reader

Dotnet Stream

Embed Size (px)

Citation preview

Page 1: Dotnet Stream

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.

DOTNETDOTNET

Page 2: Dotnet Stream

2©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

Page 3: Dotnet Stream

3©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

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

Page 4: Dotnet Stream

4©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 ContentsPage 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

Page 5: Dotnet Stream

5©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

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

Page 6: Dotnet Stream

6©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

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

Page 7: Dotnet Stream

7©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

780 Web Site Management

829 Best Practices with .Net Framework

Page 8: Dotnet Stream

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.

Generic ModulesGeneric Modules

Page 9: Dotnet Stream

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 PracticesCoding Best Practices

Page 10: Dotnet Stream

10©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

Page 11: Dotnet Stream

11©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.

Target Audience

• SE• SSE

Page 12: Dotnet Stream

12©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

• Familiarity in writing, debugging and running simple programs in C will be helpful

Page 13: Dotnet Stream

13©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.

H/w & S/w Required

None

Page 14: Dotnet Stream

14©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.

Session Plan

Day 1• Coding Best Practices

Page 15: Dotnet Stream

15©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. 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

Page 16: Dotnet Stream

16©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

• 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

Page 17: Dotnet Stream

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.

Construction Construction Coding & DebuggingCoding & Debugging

Page 18: Dotnet Stream

18©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

Page 19: Dotnet Stream

19©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

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

Page 20: Dotnet Stream

20©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.

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

Page 21: Dotnet Stream

21©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.

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

Page 22: Dotnet Stream

22©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.

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.

Page 23: Dotnet Stream

23©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 Standards

Good Naming Convention• Use full English descriptors that accurately describe the

variable/field/classExample:

firstNamegrandTotalCorporateCustomer

• 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

Page 24: Dotnet Stream

24©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 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?

Page 25: Dotnet Stream

25©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 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 understandIt'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 areCode broken into modulesEach module has one and only one functionThere is one and only one logical entry and exit to each moduleModules are loosely coupledNo GOTO statements

Page 26: Dotnet Stream

26©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 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;}

Page 27: Dotnet Stream

27©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 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 numbersMany 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}

Page 28: Dotnet Stream

28©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 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 )

Page 29: Dotnet Stream

29©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 Standards

• Do not hardcode error messages, instead try to read it from Database.

• Avoid redundant coding, Example

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

Instead of following exampleString strName = new String();Statement 1strName = getName();

This will unnecessarily occupy two memory locations

Page 30: Dotnet Stream

30©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 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

Page 31: Dotnet Stream

31©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.

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.

Page 32: Dotnet Stream

32©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.

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.

Page 33: Dotnet Stream

33©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.

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

Page 34: Dotnet Stream

34©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.

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 memoryExample:

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.

Page 35: Dotnet Stream

35©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.

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.

Page 36: Dotnet Stream

36©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.

Code Optimization Techniques

LoopsBecause loops are executed many times, the hot spots in program are often inside loops. The technique is to make the loop itself faster.

UnswitchingSwitching 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 Loopfor (int I = 0; I < count; I++){

if ( SumType == Net )NetSum = NetSum + Amount [ I ];

elseGrossSum = GrossSum + Amount [ I ]

}

Page 37: Dotnet Stream

37©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.

Code Optimization Techniques

Example of Unswitched Loopif ( 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.

Page 38: Dotnet Stream

38©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.

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 Jammedfor (int I = 1; I < num; I++ ) {{

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

EmployeeEarnings[ I ] = 0;}

Page 39: Dotnet Stream

39©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.

Code Optimization Techniques

Example of a Jammed Loop

for (int I = 1; I < num; I++ ) {

EmployeeName [ I ] = “”;EmployeeEarnings[ I ] = 0;

}

Page 40: Dotnet Stream

40©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.

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;

}

Page 41: Dotnet Stream

41©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.

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;

Page 42: Dotnet Stream

42©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.

Code Optimization Techniques

Minimizing the Work Inside LoopsOne 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 Loopfor ( int I = 0; I < num ; I ++) {

NetRate [ I ] = BaseRate [ I ] * Rates -> Discounts -> Factors - > Net;

}

Example of Simplifying a Complicated Pinter ExpressionQuantityDiscount = Rates -> Discounts -> Factors - > Net;

for ( int I = 0; I < num ; I ++) {NetRate [ I ] = BaseRate [ I ] * QuantityDiscount;

}

Page 43: Dotnet Stream

43©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.

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 Improvedfor ( 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

Page 44: Dotnet Stream

44©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.

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++){

….}

Page 45: Dotnet Stream

45©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.

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.

Page 46: Dotnet Stream

46©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.

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;

}}

Page 47: Dotnet Stream

47©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.

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 clauseIf there is a need to use multiple IF, look for some other logical statements like ‘switch’ – ‘case’

Page 48: Dotnet Stream

48©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

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.

Page 49: Dotnet Stream

49©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

Log4j Supports following projects• Log4Cxx (c++)• Log4j• Log4Net• Log4Perl • Log4PLSQL • JDK1.4's util.logging framework

Page 50: Dotnet Stream

50©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.

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.

Page 51: Dotnet Stream

51©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.

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

Page 52: Dotnet Stream

52©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.

Application Security

Application Level SecurityMost 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

Page 53: Dotnet Stream

53©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.

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 information2. Same way, all customers can access customer related

information but not the supply related information.

Page 54: Dotnet Stream

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.

Construction - DesignConstruction - Design

Page 55: Dotnet Stream

55©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 applicationLayering 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

Page 56: Dotnet Stream

56©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

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.

Page 57: Dotnet Stream

57©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.

Routines/ ModulesWhat is Routines?

A set of instructions that perform a specific task for a program.

The major activities are• Designing the routine• Checking the design• Coding the routine• Checking the code

Begin

Design the routine

Check the design

Check the code

Code the routine

Repeat if necessary

Done

Page 58: Dotnet Stream

58©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.

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 function2. A function like inputAll() has lower cohesion, because it tries to do

more than one thing.

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

AdvantagesThe payoff is higher reliability.

Page 59: Dotnet Stream

59©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.

Characteristics of Routine (Modules)

Loose CouplingThe 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.

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

Page 60: Dotnet Stream

60©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.

A good developer knows that there

is more to development than programming.

A great developer knows that there

is more to development than development.

Page 61: Dotnet Stream

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.

RDBMSRDBMS

COE – Current Technologies

Page 62: Dotnet Stream

62©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 DefinitionPurpose of DBMSData ModelsInstances, SchemasData IndependenceDBMS Users Single & Multi User SystemsDatabase System Components & Architecture

Page 63: Dotnet Stream

63©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

E-R ModelRelational ModelObject Oriented ModelNormalization

Page 64: Dotnet Stream

64©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.

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

Page 65: Dotnet Stream

65©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.

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).

Page 66: Dotnet Stream

66©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.

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.

Page 67: Dotnet Stream

67©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.

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 storedStructures defined in detail

• Conceptual LevelDescribes what data is storedDescribes the relationships among data

• View Level Describes part of Database for particular users

Page 68: Dotnet Stream

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

Data 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

Page 69: Dotnet Stream

69©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 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.

Page 70: Dotnet Stream

70©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 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.

Page 71: Dotnet Stream

71©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.

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.

Page 72: Dotnet Stream

72©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.

Record Based Logical Models

The Relational ModelData and relationships are represented by a collection of tables.Each table has a number of columns with unique names, e.g. customer, account.

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

Page 73: Dotnet Stream

73©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.

Record Based Logical Models

Network ModelsData 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

Page 74: Dotnet Stream

74©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.

Record Based Logical Models

Hierarchical ModelsOrganization 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

Page 75: Dotnet Stream

75©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.

Instances , Schemas

Databases changes over timeInstance:

Information in a database at a particular point in timeSchema:

The overall design of the databaseAnalogy with programming languages:

Data type definition - SchemaValue of a variable - Instance

Page 76: Dotnet Stream

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

Data Independence

Ability to modify a schema definition in one level without affecting a schema definition in a higher levelPhysical data independence:

Ability to modify the physical schema without causing application programs to be rewrittenModifications 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

Page 77: Dotnet Stream

77©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.

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 UserWho 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.

Page 78: Dotnet Stream

78©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.

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.

Page 79: Dotnet Stream

79©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.

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

Page 80: Dotnet Stream

80©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.

Database System Components & Architecture

USERS DBAApplication Programs

Query Database Schema

DML Pre-compilerQuery Processor

Database Manager

DDL compiler

Object Code

File Manager

Data Files

Data Dictionary

Disk Storage

Page 81: Dotnet Stream

81©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.

Database System Components & Architecture

External Schema

(User View)

Conceptual Schema

Internal Schema

(Physical View)

User 1 User 2 User 3

(Logical View)

Page 82: Dotnet Stream

82©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.

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).

Page 83: Dotnet Stream

83©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.

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, NameBook 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

Page 84: Dotnet Stream

84©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.

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

Page 85: Dotnet Stream

85©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.

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

Page 86: Dotnet Stream

86©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.

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.

Page 87: Dotnet Stream

87©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.

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.

Page 88: Dotnet Stream

88©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.

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.

Page 89: Dotnet Stream

89©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.

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.

Page 90: Dotnet Stream

90©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.

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.

Page 91: Dotnet Stream

91©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.

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

Page 92: Dotnet Stream

92©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.

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.

Page 93: Dotnet Stream

93©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.

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

Page 94: Dotnet Stream

94©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.

Relational ModelUnion

• 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.

Page 95: Dotnet Stream

95©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.

Codd's RDBMS Rules

1. Information RepresentationThe 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.

Page 96: Dotnet Stream

96©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.

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.

Page 97: Dotnet Stream

97©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.

Codd's RDBMS Rules

8. Physical Data Independence

9. Logical Data Independence10. 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.

Page 98: Dotnet Stream

98©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 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.

Page 99: Dotnet Stream

99©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 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.

Page 100: Dotnet Stream

100©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 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.

Page 101: Dotnet Stream

101©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 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.

Page 102: Dotnet Stream

102©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 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.

Page 103: Dotnet Stream

103©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 Oriented Data ModelInheritance:

• 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.

Page 104: Dotnet Stream

104©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 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

Page 105: Dotnet Stream

105©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 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.

Page 106: Dotnet Stream

106©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.

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.

Page 107: Dotnet Stream

107©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.

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

Page 108: Dotnet Stream

108©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.

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.

Page 109: Dotnet Stream

109©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.

Normalization

Page 110: Dotnet Stream

110©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.

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.

Page 111: Dotnet Stream

111©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.

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.

Page 112: Dotnet Stream

112©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.

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.

Page 113: Dotnet Stream

113©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.

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

Page 114: Dotnet Stream

114©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.

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.

Page 115: Dotnet Stream

115©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.

Normalization

Ist Normal Form

ecode dept projcode hours hodE01 systems p10 60 E11E01 systems p25 55 E11E01 systems p35 100 E11E02 sales p20 75 E22E03 admin p30 90 E33E03 admin p40 80 E33

Page 116: Dotnet Stream

116©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.

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.

Page 117: Dotnet Stream

117©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.

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

Page 118: Dotnet Stream

118©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.

ecode projcode hours

E01

E01

E01

E02

E03

E03

P10

p25

p35

p20

p30

p40

60

55

100

75

90

80

ecode dept

E01

E02

E03

systems

sales

admin

Non-loss decomposition

Table in 2NF

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.

hod

E11

E22

E33

Page 119: Dotnet Stream

119©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.

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

Normalization

Page 120: Dotnet Stream

120©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.

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

Normalization

Page 121: Dotnet Stream

121©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.

dept hod

systems

sales

admin

E11

E22

E33

ecode dept

E01

E02

E03

systems

sales

admin

Table in 3NF

Third Normal Form

A relation is in third normal form if it is in 2NF and has no transitive dependencies (no mutual dependencies)

Page 122: Dotnet Stream

122©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.

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.

Page 123: Dotnet Stream

123©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.

NormalizationUNF To BCNF (Unnormalized FormTo BCNF)

Page 124: Dotnet Stream

124©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.

Normalization

UNF To BCNF

Page 125: Dotnet Stream

125©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.

Normalization

UNF To BCNF

Page 126: Dotnet Stream

126©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.

Normalizationecode name projcode hoursE01 Miller p10 60E01 Miller p25 55E01 Miller p35 100E02 Jones p20 75E03 Smith p30 90E03 Smith p40 80• Normal Formecode projcode hours ecode nameE01 p10 60 E01 MillerE01 p25 55 E02 JonesE01 p35 100 E03 SmithE02 p20 75E03 p30 90E03 p40 80

Page 127: Dotnet Stream

127©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.

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

Page 128: Dotnet Stream

128©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.

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.

Page 129: Dotnet Stream

129©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.

Normalization

Fourth Normal Form ( 4 NF)

Page 130: Dotnet Stream

130©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.

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.

Page 131: Dotnet Stream

131©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.

Normalization

Fifth Normal Form ( 5 NF)

Page 132: Dotnet Stream

132©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.

Normalization

Fifth Normal Form ( 5 NF)

Page 133: Dotnet Stream

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 in SQL Programming in SQL Server Server

For Internal Use Only

Page 134: Dotnet Stream

134©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

Page 135: Dotnet Stream

135©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 (Continued) Temporary Tables Error Handling DB Coding Standards Case Studies

For Internal Use Only

Page 136: Dotnet Stream

136©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 Databases

DBMS vs RDBMS Normalization

Codd’s 12 Rules Introduction to SQL Server

For Internal Use Only

Page 137: Dotnet Stream

137©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 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 RuleAll 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 ValuesA 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

Page 138: Dotnet Stream

138©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 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 RuleData 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 DeleteData 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 IndependenceThe 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

Page 139: Dotnet Stream

139©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 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 IndependenceThe 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 IndependenceA 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 RuleThere 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

Page 140: Dotnet Stream

140©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 Databases (Continued)Introduction to SQL Server

Relational DatabaseManagement System

SQL Server

Transact-SQLTransact-SQLTransact-SQLTransact-SQL

ApplicationApplicationClient

ResultsResultsResultsResults

For Internal Use Only

Page 141: Dotnet Stream

141©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.

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

Page 142: Dotnet Stream

142©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.

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

Page 143: Dotnet Stream

143©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.

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

Page 144: Dotnet Stream

144©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.

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

Page 145: Dotnet Stream

145©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.

DML Statements (Continued) DELETE

Syntax :delete [from] {database name}.{owner}.{table name}{where clause}

Example:delete from WebLog.dbo.TB_ARTICLE_STATISTICSwhere ARTICLE_ID = @pArticleId

For Internal Use Only

Page 146: Dotnet Stream

146©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.

DCL Statements

GRANT Syntax:

GRANT { ALL | statement [ ,...n ] }

TO security_account [ ,...n ] DENY Syntax:

DENY { ALL | statement [ ,...n ] } TO security_account [ ,...n ]

REVOKESyntax : REVOKE { ALL | statement [ ,...n ] } FROM security_account

[ ,...n ]

For Internal Use Only

Page 147: Dotnet Stream

147©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.

DDL Statements

CREATEPartial Syntax : CREATE <Object Name>

ALTERPartial Syntax : ALTER <Object Name>

DROPPartial Syntax : DROP <Object Name>

For Internal Use Only

Page 148: Dotnet Stream

148©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.

Operators

Arithmetic Bit-wise Comparison Logical Concatenation Unary

For Internal Use Only

Page 149: Dotnet Stream

149©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.

Operators(Continued) Arithmetic

= assignment operator + addition - subtraction * multiplication / divide % modulo or remainder from division

For Internal Use Only

Page 150: Dotnet Stream

150©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.

Operators(Continued) Bit-Wise

& (AND) | (OR) ^ (Exclusive OR) ~ (NOT)

For Internal Use Only

Page 151: Dotnet Stream

151©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.

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

Page 152: Dotnet Stream

152©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.

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

Page 153: Dotnet Stream

153©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.

Functions

Aggregate Functions Date and Time Functions Mathematical Functions String Functions System Functions

For Internal Use Only

Page 154: Dotnet Stream

154©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.

Functions (Continued) Aggregate Functions

AVG COUNT MAX MIN SUM

For Internal Use Only

Page 155: Dotnet Stream

155©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.

Functions (Continued) Date and Time Functions

DATEADD DATEDIFF DATENAME DATEPART GETDATE

For Internal Use Only

Page 156: Dotnet Stream

156©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.

Functions (Continued) Mathematical

Functions ABS

ACOS ASIN ATAN ATN2 CEILING COS COT DEGREES EXP FLOOR

For Internal Use Only

LOG LOG10 PI POWER RADIANS RAND ROUND SIGN SIN SQRT TAN

Page 157: Dotnet Stream

157©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.

Functions (Continued) String Functions NCHAR CHARINDEX LEN LOWER LTRIM PATINDEX REPLACE REPLICATE RTRIM SPACE

For Internal Use Only

STR STUFF SUBSTRING UNICODE

UPPER

Page 158: Dotnet Stream

158©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.

Functions (Continued) System Functions CASE COALESCE CONVERT DATALENGTH NEWID

For Internal Use Only

Page 159: Dotnet Stream

159©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.

Control of Flow Language Elements

Statement Level Row Level

For Internal Use Only

Page 160: Dotnet Stream

160©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.

Control of Flow Language Elements (Continued) Statement Level

Begin … End Block IF … ELSE Block WHILE constructs

For Internal Use Only

Page 161: Dotnet Stream

161©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.

Control of Flow Language Elements (Continued)

Row Level CASE Expression

For Internal Use Only

Page 162: Dotnet Stream

162©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.

Control of Flow Language Elements (Continued) Begin … End BlockSyntax:

BEGIN{ sql_statement | statement_block } END

For Internal Use Only

Page 163: Dotnet Stream

163©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.

Control of Flow Language Elements (Continued)

IF … ELSE BlockSyntax

IF Boolean_expression { sql_statement | statement_block } [ ELSE { sql_statement | statement_block } ]

For Internal Use Only

Page 164: Dotnet Stream

164©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.

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

Page 165: Dotnet Stream

165©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.

Control of Flow Language Elements (Continued)

CASE ExpressionSyntax:

CASE input_expression WHEN when_expression THEN result_expression [ ...n ] [ ELSE else_result_expression ] END

For Internal Use Only

Page 166: Dotnet Stream

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

Data Types

Limited character Unlimited character Binary Binary large object Integer Approximate numeric Exact numeric Date and time Currency Other

For Internal Use Only

Page 167: Dotnet Stream

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

Data 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

Page 168: Dotnet Stream

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

Data 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

Page 169: Dotnet Stream

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

Data 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

Page 170: Dotnet Stream

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

Data 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

Page 171: Dotnet Stream

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

Data Tables

Creating Table Dropping Table Adding and Dropping Columns

For Internal Use Only

Page 172: Dotnet Stream

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

Data 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

Page 173: Dotnet Stream

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

Data Tables (Continued) Dropping Table

Syntax :

DROP TABLE table_name

For Internal Use Only

Page 174: Dotnet Stream

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

Data Tables (Continued)Adding and Dropping ColumnsPartial 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

Page 175: Dotnet Stream

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

Data Integrity

Types of Integrity and Constraints Domain

DEFAULT

CHECK

Entity PRIMARY KEY

UNIQUE

Referential FOREIGN KEY

CHECK

For Internal Use Only

Page 176: Dotnet Stream

176©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.

Indexes

PROS and CONS of Index. Types of Indexes Creating and Dropping Indexes Indexing Guidelines

For Internal Use Only

Page 177: Dotnet Stream

177©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.

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

Page 178: Dotnet Stream

178©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.

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

Page 179: Dotnet Stream

179©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.

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

Page 180: Dotnet Stream

180©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.

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

Page 181: Dotnet Stream

181©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.

Querying Techniques

Joins Unions Sub Queries

For Internal Use Only

Page 182: Dotnet Stream

182©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.

Querying Techniques (Continued)

Joins Types of Joins

Inner Join Outer Join Cross Join Self Join

Partial SyntaxSELECT 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

Page 183: Dotnet Stream

183©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.

Querying Techniques (Continued)

Unions UNION UNION ALL

For Internal Use Only

Page 184: Dotnet Stream

184©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.

Querying Techniques (Continued)Sub Queries Nested Sub queries Correlated Sub queries

For Internal Use Only

Page 185: Dotnet Stream

185©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.

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

Page 186: Dotnet Stream

186©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.

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

Page 187: Dotnet Stream

187©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.

Stored Procedures (Continued)

Initial Processing

Entries into sysobjects and syscomments tables

Entries into sysobjects and syscomments tables

Compiled plan placed inprocedure cache

Compiled plan placed inprocedure cache

CompilationCompilation

OptimizationOptimization

CreationCreationCreationCreation

ExecutionExecution(first time(first time

or recompile)or recompile)

ExecutionExecution(first time(first time

or recompile)or recompile)

ParsingParsing

For Internal Use Only

Page 188: Dotnet Stream

188©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.

Stored Procedures (Continued)Subsequent Process

Environment Remains the Same

Objects Do Not Require Name Resolution

ExecutionExecution(subsequent times)(subsequent times)

ExecutionExecution(subsequent times)(subsequent times)

Compiled plan retrieved from procedure cache

Compiled plan retrieved from procedure cache

LRU

Least recently used (LRU) plan is replaced

Least recently used (LRU) plan is replaced

For Internal Use Only

Page 189: Dotnet Stream

189©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.

Stored Procedures (Continued)

Advantages of Stored procedures Share Application Logic Provide Security Mechanisms Execute Automatically Increase Performance Reduce Network Traffic

For Internal Use Only

Page 190: Dotnet Stream

190©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.

Stored Procedures (Continued)

Creating , Executing, Altering and Dropping Stored Procedures

Creating ProcedureSyntax:CREATE PROC [ EDURE ] procedure_name [ ; number ] [ { @parameter data_type } [ VARYING ] [ = default ] [ OUTPUT ] ] [ ,...n ]

Executing Stored ProceduresExecuting a Stored Procedure by Itself

Syntax:

Execute <SP_Name>

For Internal Use Only

Page 191: Dotnet Stream

191©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.

Stored Procedures (Continued)

Creating , Executing, Altering and Dropping Stored Procedures

Altering Stored ProceduresPartial SyntaxALTER PROC [ EDURE ] procedure_name [ ; number ] [ { @parameter data_type } [ VARYING ] [ = default ] [ OUTPUT ] ] [ ,...n ] AS sql_statement [ ...n ]

Dropping Stored ProceduresPartial SyntaxDROP PROCEDURE { procedure } [ ,...n ]

For Internal Use Only

Page 192: Dotnet Stream

192©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.

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

Page 193: Dotnet Stream

193©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.

Stored Procedures (Continued)

Using Input Parameters

Trap Missing or Invalid Parameter Values First

Provide Appropriate Default Values

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

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

Page 194: Dotnet Stream

194©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.

Stored Procedures (Continued)

Executing Stored Procedures with Input Parameters Passing Values by Reference

Passing Values by Position

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

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

EXEC addadult @firstname = 'Linda', @lastname = 'LaBrie', @street = 'Dogwood Drive', @city = 'Sacramento', @state = 'CA', @zip = '94203'

EXEC addadult @firstname = 'Linda', @lastname = 'LaBrie', @street = 'Dogwood Drive', @city = 'Sacramento', @state = 'CA', @zip = '94203'

Page 195: Dotnet Stream

195©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.

Stored Procedures (Continued)

Returning Values with Output Parameters

CREATE PROCEDURE dbo.mathtutor@m1 smallint,

@m2 smallint,@result smallint OUTPUT

ASSET @result = @m1 * @m2

DECLARE @answer smallintEXECUTE mathtutor 5, 6, @answer OUTPUTSELECT 'The result is: ' , @answer

The result is: 30

CREATE PROCEDURE dbo.mathtutor@m1 smallint,

@m2 smallint,@result smallint OUTPUT

ASSET @result = @m1 * @m2

DECLARE @answer smallintEXECUTE mathtutor 5, 6, @answer OUTPUTSELECT 'The result is: ' , @answer

The result is: 30

Results of StoredResults of StoredProcedureProcedure

Results of StoredResults of StoredProcedureProcedure

Executing StoredExecuting StoredProcedureProcedure

Executing StoredExecuting StoredProcedureProcedure

Creating Stored Creating Stored ProcedureProcedure

Creating Stored Creating Stored ProcedureProcedure

Page 196: Dotnet Stream

196©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.

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

Page 197: Dotnet Stream

197©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.

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'

Page 198: Dotnet Stream

198©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.

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

Page 199: Dotnet Stream

199©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.

Views

Introduction to Views Advantages of Views Defining Views Modifying Data Through Views Performance Considerations

For Internal Use Only

Page 200: Dotnet Stream

200©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 Views

TitleViewTitleViewTitleViewTitleView

title title author author

Last of the MohicansThe Village Watch-TowerPoems

Last of the MohicansThe Village Watch-TowerPoems

James Fenimore CooperKate Douglas WigginWilfred Owen

James Fenimore CooperKate Douglas WigginWilfred Owen

titletitletitletitle

title_notitle_no title title author author synopsissynopsis

123

123

Last of the MohicansThe Village Watch-TowerPoems

Last of the MohicansThe Village Watch-TowerPoems

James Fenimore CooperKate Douglas WigginWilfred Owen

James Fenimore CooperKate Douglas WigginWilfred Owen

~~~~~~~~~

~~~~~~~~~

User’s ViewUser’s ViewUser’s ViewUser’s View

CREATE VIEW dbo.TitleViewAS SELECT title, authorFROM title

CREATE VIEW dbo.TitleViewAS SELECT title, authorFROM title

For Internal Use Only

Page 201: Dotnet Stream

201©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.

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

Page 202: Dotnet Stream

202©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 Views

Creating Views Altering and Dropping Views

For Internal Use Only

Page 203: Dotnet Stream

203©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.

Creating Views

Creating a View

Restrictions on View Definitions ORDER BY, COMPUTE, or COMPUTE BY clauses INTO keyword

USE libraryGoCREATE VIEW dbo.UnpaidFinesView (Member, TotalUnpaidFines)ASSELECT member_no, (sum(fine_assessed-fine_paid))FROM loanhistGROUP BY member_noHAVING SUM(fine_assessed-fine_paid) > 0GO

USE libraryGoCREATE VIEW dbo.UnpaidFinesView (Member, TotalUnpaidFines)ASSELECT member_no, (sum(fine_assessed-fine_paid))FROM loanhistGROUP BY member_noHAVING SUM(fine_assessed-fine_paid) > 0GO

For Internal Use Only

Page 204: Dotnet Stream

204©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.

Creating Views (Continued)

Example : View of Joined Tables

member_nomember_nomember_nomember_no

11121314

11121314

lastnamelastnamelastnamelastname

ThomasThomasFunk Rudd

ThomasThomasFunk Rudd

firstnamefirstnamefirstnamefirstname

GaryClairFrankClair

GaryClairFrankClair

middleinitialmiddleinitialmiddleinitialmiddleinitial

~~~~~~~~~~~~

~~~~~~~~~~~~

photographphotographphotographphotograph

~~~~~~~~~~~~

~~~~~~~~~~~~

LastnameLastnameLastnameLastname

ThomasFunk

ThomasFunk

FirstnameFirstnameFirstnameFirstname

ClairFrank

ClairFrank

Birth DateBirth DateBirth DateBirth Date

92.01.1684.01.18

92.01.1684.01.18

BirthdayViewUSE libraryGOCREATE VIEW dbo.BirthdayView

(Lastname, Firstname, Birthdate)ASSELECT lastname, firstname,

CONVERT(char(8), birth_date, 2)FROM member JOIN juvenileON member.member_no = juvenile.member_no

USE libraryGOCREATE VIEW dbo.BirthdayView

(Lastname, Firstname, Birthdate)ASSELECT lastname, firstname,

CONVERT(char(8), birth_date, 2)FROM member JOIN juvenileON member.member_no = juvenile.member_no

member_nomember_nomember_nomember_no

1213

1213

adult_noadult_noadult_noadult_no

116

116

birth_datebirth_datebirth_datebirth_date

1992-01-16 00:00:00.0001984-01-18 00:00:00.000

1992-01-16 00:00:00.0001984-01-18 00:00:00.000

For Internal Use Only

Page 205: Dotnet Stream

205©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.

Altering and Dropping Views

Altering Views

Dropping Views

DROP VIEW UnpaidFinesViewDROP VIEW UnpaidFinesView

ALTER VIEW dbo.TitleViewAS SELECT title, authors, synopsisFROM title

ALTER VIEW dbo.TitleViewAS SELECT title, authors, synopsisFROM title

For Internal Use Only

Page 206: Dotnet Stream

206©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.

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

Page 207: Dotnet Stream

207©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.

Performance Considerations

USE libraryGOCREATE VIEW dbo.LoanableViewAS SELECT *FROM CopywideViewWHERE loanable = 'y'

USE libraryGOCREATE VIEW dbo.LoanableViewAS SELECT *FROM CopywideViewWHERE loanable = 'y'

titletitletitletitle

11 ~~ ~~ ~~ nn

22 ~~ ~~ ~~ nn

33 ~~ ~~ ~~ yy

44 ~~ ~~ ~~ yy

55 ~~ ~~ ~~ nn

66 ~~ ~~ ~~ yy

CopywideViewCopywideViewCopywideViewCopywideView

11 ~~ ~~ ~~ nn

22 ~~ ~~ ~~ nn

33 ~~ ~~ ~~ yy

44 ~~ ~~ ~~ yy

55 ~~ ~~ ~~ nn

66 ~~ ~~ ~~ yy

LoanableViewLoanableViewLoanableViewLoanableView

33 ~~ ~~ ~~

44 ~~ ~~ ~~

66 ~~ ~~ ~~

itemitemitemitem

11 ~~ ~~ ~~ nn

22 ~~ ~~ ~~ nn

33 ~~ ~~ ~~ yy

44 ~~ ~~ ~~ yy

55 ~~ ~~ ~~ nn

66 ~~ ~~ ~~ yy

copycopycopycopy

11 ~~ ~~ ~~ nn

22 ~~ ~~ ~~ nn

33 ~~ ~~ ~~ yy

44 ~~ ~~ ~~ yy

55 ~~ ~~ ~~ nn

66 ~~ ~~ ~~ yy

SELECT DISTINCT isbn, title, authorFROM LoanableViewWHERE language = 'french'

SELECT DISTINCT isbn, title, authorFROM LoanableViewWHERE language = 'french'

yy

yy

yy

For Internal Use Only

Page 208: Dotnet Stream

208©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.

Triggers

Introduction to Triggers Defining Triggers How Triggers Work Examples of Triggers Performance Considerations

For Internal Use Only

Page 209: Dotnet Stream

209©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 Triggers

Overview of Trigger Uses of Triggers Considerations for Using Triggers

For Internal Use Only

Page 210: Dotnet Stream

210©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 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

Page 211: Dotnet Stream

211©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 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

Page 212: Dotnet Stream

212©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 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

Page 213: Dotnet Stream

213©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 Triggers

Creating Triggers Altering and Dropping Triggers

Page 214: Dotnet Stream

214©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 Triggers(Continued)

Creating Triggers Requires Appropriate Permissions Cannot Contain Certain Statements

Use NorthwindGOCREATE TRIGGER Empl_Delete ON EmployeesFOR DELETE ASIF (SELECT COUNT(*) FROM Deleted) > 1BEGIN RAISERROR( 'You cannot delete more than one employee at a time.', 16, 1) ROLLBACK TRANSACTIONEND

Use NorthwindGOCREATE TRIGGER Empl_Delete ON EmployeesFOR DELETE ASIF (SELECT COUNT(*) FROM Deleted) > 1BEGIN RAISERROR( 'You cannot delete more than one employee at a time.', 16, 1) ROLLBACK TRANSACTIONEND

Page 215: Dotnet Stream

215©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 Triggers(Continued)

Altering and Dropping Triggers Changes the definition without dropping the trigger Can disable or enable a trigger

USE NorthwindGOALTER TRIGGER Empl_Delete ON EmployeesFOR DELETE ASIF (SELECT COUNT(*) FROM Deleted) > 6BEGIN RAISERROR( 'You cannot delete more than six employees at a time.', 16, 1) ROLLBACK TRANSACTIONEND

USE NorthwindGOALTER TRIGGER Empl_Delete ON EmployeesFOR DELETE ASIF (SELECT COUNT(*) FROM Deleted) > 6BEGIN RAISERROR( 'You cannot delete more than six employees at a time.', 16, 1) ROLLBACK TRANSACTIONEND

Page 216: Dotnet Stream

216©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.

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

Page 217: Dotnet Stream

217©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.

How an INSERT Trigger Works

INSERT statement to a table with an INSERT Trigger Defined

INSERT [Order Details] VALUES(10525, 2, 19.00, 5, 0.2)

INSERT [Order Details] VALUES(10525, 2, 19.00, 5, 0.2)

Order DetailsOrder DetailsOrder DetailsOrder Details

OrderIDOrderID

105221052310524

105221052310524

ProductIDProductID

10417

10417

UnitPriceUnitPrice

31.009.6530.00

31.009.6530.00

QuantityQuantity

7924

7924

DiscountDiscount

0.20.150.0

0.20.150.0

5 19.002 0.210523

Insert statement logged

insertedinsertedinsertedinserted

1052310523 22 19.0019.00 55 0.20.2

TRIGGER Actions Execute

Order DetailsOrder DetailsOrder DetailsOrder Details

OrderIDOrderID

105221052310524

105221052310524

ProductIDProductID

10417

10417

UnitPriceUnitPrice

31.009.6530.00

31.009.6530.00

QuantityQuantity

7924

7924

DiscountDiscount

0.20.150.0

0.20.150.0

5 19.002 0.210523

Trigger Code:USE NorthwindCREATE TRIGGER OrdDet_InsertON [Order Details]FOR INSERTASUPDATE P SET UnitsInStock = (P.UnitsInStock – I.Quantity)FROM Products AS P INNER JOIN Inserted AS ION P.ProductID = I.ProductID

Trigger Code:USE NorthwindCREATE TRIGGER OrdDet_InsertON [Order Details]FOR INSERTASUPDATE P SET UnitsInStock = (P.UnitsInStock – I.Quantity)FROM Products AS P INNER JOIN Inserted AS ION P.ProductID = I.ProductID

UPDATE P SET UnitsInStock = (P.UnitsInStock – I.Quantity)FROM Products AS P INNER JOIN Inserted AS ION P.ProductID = I.ProductID

ProductsProductsProductsProducts

ProductIDProductID UnitsInStockUnitsInStock …… ……

1234

1234

15106520

15106520

2 15

INSERT Statement to a Table with an INSERTTrigger Defined

INSERT Statement Logged

Trigger Actions Executed

1111

2222

3333

Page 218: Dotnet Stream

218©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.

How an Update Trigger works

UPDATE Statement to a table with an UPDATE Trigger Defined

UPDATE EmployeesSET EmployeeID = 17WHERE EmployeeID = 2

UPDATE EmployeesSET EmployeeID = 17WHERE EmployeeID = 2

UPDATE Statement logged as INSERT and DELETE Statements

EmployeesEmployeesEmployeesEmployees

EmployeeIDEmployeeID LastNameLastName FirstNameFirstName TitleTitle HireDateHireDate

1234

1234

DavolioBarrLeverlingPeacock

DavolioBarrLeverlingPeacock

NancyAndrewJanetMargaret

NancyAndrewJanetMargaret

Sales Rep.RSales Rep.Sales Rep.

Sales Rep.RSales Rep.Sales Rep.

~~~~~~~~~~~~

~~~~~~~~~~~~

2 Fuller Andrew Vice Pres. ~~~

insertedinsertedinsertedinserted

1717 FullerFuller AndrewAndrew Vice Pres.Vice Pres. ~~~~~~

deleteddeleteddeleteddeleted

22 FullerFuller AndrewAndrew Vice Pres.Vice Pres. ~~~~~~

TRIGGER Actions Execute

USE NorthwindGOCREATE TRIGGER Employee_Update

ON EmployeesFOR UPDATE

ASIF UPDATE (EmployeeID)BEGIN TRANSACTION

RAISERROR ('Transaction cannot be processed.\***** Employee ID number cannot be modified.', 10, 1)ROLLBACK TRANSACTION

USE NorthwindGOCREATE TRIGGER Employee_Update

ON EmployeesFOR UPDATE

ASIF UPDATE (EmployeeID)BEGIN TRANSACTION

RAISERROR ('Transaction cannot be processed.\***** Employee ID number cannot be modified.', 10, 1)ROLLBACK TRANSACTION

ASIF UPDATE (EmployeeID)BEGIN TRANSACTIONRAISERROR ('Transaction cannot be processed.\***** Employee ID number cannot be modified.', 10, 1)ROLLBACK TRANSACTION

Transaction cannot be processed. ***** Member number cannot be modified Transaction cannot be processed. ***** Member number cannot be modified

EmployeesEmployeesEmployeesEmployees

EmployeeIDEmployeeID LastNameLastName FirstNameFirstName TitleTitle HireDateHireDate

1234

1234

DavolioBarrLeverlingPeacock

DavolioBarrLeverlingPeacock

NancyAndrewJanetMargaret

NancyAndrewJanetMargaret

Sales Rep.RSales Rep.Sales Rep.

Sales Rep.RSales Rep.Sales Rep.

~~~~~~~~~~~~

~~~~~~~~~~~~

2 Fuller Andrew Vice Pres. ~~~

UPDATE Statement to a Table with an UPDATETrigger Defined

UPDATE Statement Logged as INSERT andDELETE Statements

Trigger Actions Executed

1111

2222

3333

Page 219: Dotnet Stream

219©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.

How Delete Trigger Works

DELETE Statement to a table with a DELETE Trigger DefinedDELETE Statement to a table with a DELETE Trigger Defined

DeletedDeletedDeletedDeleted

44 Dairy ProductsDairy Products CheesesCheeses 0x15…0x15…

DELETE statement logged

CategoriesCategoriesCategoriesCategories

CategoryIDCategoryID

123

123

CategoryNameCategoryName

BeveragesCondimentsConfections

BeveragesCondimentsConfections

DescriptionDescription

Soft drinks, coffees…Sweet and savory …Desserts, candies, …

Soft drinks, coffees…Sweet and savory …Desserts, candies, …

PicturePicture

0x15…0x15…0x15…

0x15…0x15…0x15… 0x15…CheesesDairy Products4

DELETE CategoriesWHERE CategoryID = 4

DELETE CategoriesWHERE CategoryID = 4

USE NorthwindCREATE TRIGGER Category_Delete

ON CategoriesFOR DELETE

ASUPDATE P SET Discontinued = 1FROM Products AS P INNER JOIN deleted AS dON P.CategoryID = d.CategoryID

USE NorthwindCREATE TRIGGER Category_Delete

ON CategoriesFOR DELETE

ASUPDATE P SET Discontinued = 1FROM Products AS P INNER JOIN deleted AS dON P.CategoryID = d.CategoryID

ProductsProductsProductsProducts

ProductIDProductID DiscontinuedDiscontinued …… ……

1234

1234

0000

0000

Trigger Actions Execute

2 1

UPDATE P SET Discontinued = 1FROM Products AS P INNER JOIN deleted AS dON P.CategoryID = d.CategoryID

DELETE Statement to a Table with a DELETEStatement Defined

DELETE Statement Logged

Trigger Actions Executed

1111

2222

3333

Page 220: Dotnet Stream

220©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.

How Instead of Trigger Works

Create a View That Combines Two or More Tables

CREATE VIEW Customers ASSELECT * FROM CustomersMexUNIONSELECT * FROM CustomersGer

CREATE VIEW Customers ASSELECT * FROM CustomersMexUNIONSELECT * FROM CustomersGer

CustomersMexCustomersMexCustomersMexCustomersMex

CustomerIDCustomerID CompanyNameCompanyName CountryCountry PhonePhone ……

ANATRANTONCENTC

ANATRANTONCENTC

Ana Trujill…Antonio M…Centro Co…

Ana Trujill…Antonio M…Centro Co…

MexicoMexicoMexico

MexicoMexicoMexico

(5) 555-4729(5) 555-3932(5) 555-3392

(5) 555-4729(5) 555-3932(5) 555-3392

~~~~~~~~~

~~~~~~~~~

CustomersGerCustomersGerCustomersGerCustomersGer

CustomerIDCustomerID CompanyNameCompanyName CountryCountry PhonePhone ……

ALFKIBLAUSDRACD

ALFKIBLAUSDRACD

Alfreds Fu…Blauer Se…Drachenb…

Alfreds Fu…Blauer Se…Drachenb…

GermanyGermanyGermany

GermanyGermanyGermany

030-00743210621-084600241-039123

030-00743210621-084600241-039123

~~~~~~~~~

~~~~~~~~~

INSTEAD OF trigger directs the update to the base table

CustomersCustomersCustomersCustomers

CustomerIDCustomerID CompanyNameCompanyName CountryCountry PhonePhone ……

ALFKIANATRANTON

ALFKIANATRANTON

Alfreds Fu…Ana Trujill…Antonio M…

Alfreds Fu…Ana Trujill…Antonio M…

GermanyMexicoMexico

GermanyMexicoMexico

030-0074321(5) 555-4729(5) 555-3932

030-0074321(5) 555-4729(5) 555-3932

~~~~~~~~~

~~~~~~~~~

Original Insert to the Customers View Does Not Occur

UPDATE is Made to the View

ALFKI Alfreds Fu… Germany 030-0074321 ~~~

ALFKI Alfreds Fu… Germany 030-0074321 ~~~

INSTEAD OF Trigger Can Be on a Table or View

The Action That Initiates the Trigger Does NOT Occur

Allows Updates to Views Not Previously Updateable

1111

2222

3333

Page 221: Dotnet Stream

221©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.

How Nested Triggers Work

UnitsInStock + UnitsOnOrder is < ReorderLevel for ProductID 2

OrDe_UpdateOrDe_Update

Placing an order causes the OrDe_Update trigger to execute

Executes an UPDATE statement on the Products table

InStock_UpdateInStock_Update ProductsProductsProductsProducts

ProductIDProductID UnitsInStockUnitsInStock …… ……

1

34

1

34

15106520

15106520

2 15

InStock_Update trigger executes

Sends message

Order_DetailsOrder_DetailsOrder_DetailsOrder_Details

OrderIDOrderID

105221052310524

105221052310524

ProductIDProductID

10417

10417

UnitPriceUnitPrice

31.009.6530.00

31.009.6530.00

QuantityQuantity

7924

7924

DiscountDiscount

0.20.150.0

0.20.150.0

10525 19.002 0.25

Page 222: Dotnet Stream

222©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.

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

Page 223: Dotnet Stream

223©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.

Examples of Triggers

Enforcing Data Integrity Enforcing Business Rules

Page 224: Dotnet Stream

224©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.

Enforcing Data Integrity

CREATE TRIGGER BackOrderList_DeleteON Products FOR UPDATE

ASIF (SELECT BO.ProductID FROM BackOrders AS BO JOIN

Inserted AS I ON BO.ProductID = I.Product_ID) > 0

BEGINDELETE BO FROM BackOrders AS BO INNER JOIN Inserted AS I ON BO.ProductID = I.ProductID

END

CREATE TRIGGER BackOrderList_DeleteON Products FOR UPDATE

ASIF (SELECT BO.ProductID FROM BackOrders AS BO JOIN

Inserted AS I ON BO.ProductID = I.Product_ID) > 0

BEGINDELETE BO FROM BackOrders AS BO INNER JOIN Inserted AS I ON BO.ProductID = I.ProductID

END

ProductsProductsProductsProducts

ProductIDProductID UnitsInStockUnitsInStock …… ……

1

34

1

34

15106520

15106520

2 15 UpdatedUpdated

BackOrdersBackOrdersBackOrdersBackOrders

ProductIDProductID UnitsOnOrderUnitsOnOrder ……

1123

1123

151065

151065

2 15 Trigger Deletes RowTrigger Deletes Row

Page 225: Dotnet Stream

225©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.

Enforcing Business Rules

ProductsProductsProductsProducts

ProductIDProductID UnitsInStockUnitsInStock …… ……

1234

1234

15106520

15106520

Products with Outstanding Orders Cannot Be Deleted

IF (Select Count (*) FROM [Order Details] INNER JOIN deleted ON [Order Details].ProductID = deleted.ProductID ) > 0ROLLBACK TRANSACTION

IF (Select Count (*) FROM [Order Details] INNER JOIN deleted ON [Order Details].ProductID = deleted.ProductID ) > 0ROLLBACK TRANSACTION

DELETE statement executed on Product table

Trigger codechecks the Order Detailstable

Order DetailsOrder DetailsOrder DetailsOrder Details

OrderIDOrderID

10522105231052410525

10522105231052410525

ProductIDProductID

102417

102417

UnitPriceUnitPrice

31.0019.009.6530.00

31.0019.009.6530.00

QuantityQuantity

7924

7924

DiscountDiscount

0.20.150.0

0.20.150.0

9

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

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

Transactionrolled back

ProductsProductsProductsProducts

ProductIDProductID UnitsInStockUnitsInStock …… ……

1

34

1

34

15106520

15106520

2 0

Page 226: Dotnet Stream

226©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.

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

Page 227: Dotnet Stream

227©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.

Transact-SQL Cursors

Overview of Cursor Uses of Cursors How Cursors work Types of Cursors Cursor Characteristics Cursor Syntax

Page 228: Dotnet Stream

228©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.

Overview of Cursor

Points to a Specific Row Retrieves and Modifies Rows based on Current

Position Can be Sensitive to Changes in Underlying

Data

Page 229: Dotnet Stream

229©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.

Uses of Cursors

Building Command String for Execution Increasing Script Readability Performing Multiple Unrelated Manipulation

with Data Compensating for Database and Application

Limitations

Page 230: Dotnet Stream

230©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.

How Cursors Work

DECLARE @tablename nvarchar(256)DECLARE tnames_cursor CURSOR

FOR SELECT name FROM sysobjectsWHERE objectproprty(id, ‘IsUserTable’)=1ORDER BY name

OPEN tnames_cursorFETCH NEXT FROM tnames_cursor INTO @tablenameWHILE (@@FETCH_STATUS = 0)BEGIN

EXEC sp_spaceused @tablenameFETCH NEXT FROM tnames_cursor INTO @tablename

END

CLOSE tnames_cursorDEALLOCATE tnames_cursor

Page 231: Dotnet Stream

231©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.

Types of Cursors

Forward-Only Static Dynamic Keyset-driven

Page 232: Dotnet Stream

232©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.

Cursor Characteristics

Scrollability Sensitivity Locking

Page 233: Dotnet Stream

233©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.

Cursor Syntax

DECLARE CURSOROPENFETCHCLOSEDEALLOCATE

Page 234: Dotnet Stream

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

Page 235: Dotnet Stream

235©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 Oriented Programming Experience

Prerequisites for the course

Target Audience

AnalystsDesignersReviewers

Page 236: Dotnet Stream

236©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.

Session Plan

IntroductionElements Of Object Orientation

• Object• Class• Abstraction• Encapsulation• Identity• Object Structuring• Object Interactions

Page 237: Dotnet Stream

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.

IntroductionIntroduction

Page 238: Dotnet Stream

238©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

Page 239: Dotnet Stream

239©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 (cont…)

Section

Subsection 0..*

1 1 0..*

Buyer

Respondant Survey 0..* 0..*

0..* 0..* 0..* 1 creates

0..* 0..*

responds to Evaluator Response 0..* 1 0..* 1 0..*

0..* 0..*

0..* evaluates

1 0..*

0..* 0..*

Question 0..* 1 0..* 1

0..* 1 0..* 1 Answer

0..* 1 0..* 1

0..* 1 1 0..* has

has

Designer

objBuyer : Buyer objSurvey : Survey

objSection : Section

objSubsection : Subsection

objQuestion : Question

load( )

load( )

load( )load( )

load( )

Analyst

Developer

Buyer

createSurvey()

Section

addSubsection()addQuestion()

Subsection

addQuestion()

0..*

1

Respondant

respondToSurvey()answerQuestion()

Survey

addSection()

0..*

1

0..*

0..*

Evaluator

evaluateResponse()

Question

0..*0..1

0..*

0..1

Response

0..*1

Answer0..*1

0..*

1

0..*

1

0..*

0..*

1 0..*

0..*0..1

0..1

0..*

0..*11

0..*

0..*

1

creates responds to creates evaluates

has

has

Object

Oriented

Thinking

Presentation Layer

Va

lue

Ob

jec

ts

Controller Layer

Business Layer

Data Access Layer

AccessManagementComponent

Facade

Business

Objects

DataAccessObjects

CSD TemplateComponent

Facade

Business

Objects

DataAccessObjects

CSDComponent

Facade

Business

Objects

DataAccessObjects

PropagationComponent

Facade

Business

Objects

DataAccessObjects

MasterMaintenenceComponent

Facade

Business

Objects

DataAccessObjects

JSPs

Service Locator

Action Servlet

Form Beans

Action Classes

Architect

Page 240: Dotnet Stream

240©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 – 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

Page 241: Dotnet Stream

241©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 – Analyst’s View

Interactions

Objects

Relationships

Dependencies

Behavior

Software

Manager

Hardware

Infra team

Server

Problem

Employee

SoftwareRequest HardwareRequestJobRequest

EmployeeManager

InfraTeamMember ServiceRequest

CreatesReview

Complete

Page 242: Dotnet Stream

242©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 – 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

Page 243: Dotnet Stream

243©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 – 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

Page 244: Dotnet Stream

244©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.

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

Page 245: Dotnet Stream

245©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.

Paradigm Shift – Procedural Vs Object Oriented

Main program/subroutine Object-oriented

Components modules objects

Connectors Procedure calls messages

Properties Hierarchical control main program Single thread of control

Execution from start to end

Global data on files/databases

Main program instantiates objects

Parallel threads of control possible

Execution never ends

Objects responsible for own data

 

Page 246: Dotnet Stream

246©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.

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 • Shift of mindset

 

Procedural Mindset Object-oriented Mindset

What does the system do? Of what objects is the system composed?

What is its purpose?How do I design and code to achieve this functional behaviour?

How can I model the system dynamically using objects, their behaviour, and other objects they use?

Focus on algorithms Algorithmic functions deferred

Page 247: Dotnet Stream

247©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.

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

Page 248: Dotnet Stream

248©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.

Pitfalls of Object Orientation

• There is no ‘best’ object decomposition for a system of any size

• Chances of over-designing

Page 249: Dotnet Stream

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.

Elements of Object Elements of Object OrientationOrientation

Page 250: Dotnet Stream

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.

ObjectObject

Page 251: Dotnet Stream

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 LookObject-Orientation - A Conceptual Look

Page 252: Dotnet Stream

252©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

Page 253: Dotnet Stream

253©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.

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 uponthe 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

Page 254: Dotnet Stream

254©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.

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 thesolution adapt to

change?

How would I solvethis problem?

Page 255: Dotnet Stream

255©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.

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

Page 256: Dotnet Stream

256©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.

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

Which solution feels more natural?

Page 257: Dotnet Stream

257©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.

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!

Page 258: Dotnet Stream

258©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.

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

Page 259: Dotnet Stream

259©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

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

Page 260: Dotnet Stream

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 - Basic Object-Orientation - Basic PrinciplesPrinciples

Page 261: Dotnet Stream

261©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

Page 262: Dotnet Stream

262©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.

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

Page 263: Dotnet Stream

263©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.

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

Page 264: Dotnet Stream

264©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.

BehaviorOperations specify what an object can do

• Call operations to activate object responsibilities• “Student object, goToNextClass( )”

Parameters may be passed into operations• Defined by the operation signature

Operations may return information

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 interfaceObjects collaborate with other objects by sending

messages• Called object receives the message

Invokes the appropriate operation

Operations are identified with ( ) at the

end of the operation name

Page 265: Dotnet Stream

265©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

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

Page 266: Dotnet Stream

266©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.

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

Page 267: Dotnet Stream

267©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.

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

Page 268: Dotnet Stream

268©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.

Objects in Action

A sneak peakat UML notation!

Student

name : Stringaddress : Stringgpa : float

goToClass( )Student(name: String)

Class

Attributes

Operations

s1:Student

name = “Chris”

Constructor

s2:Student

name = “Mike”

s3:Student

name = “Chris”

Obj

ects

<<instanceof>> <<instanceof>> <<instanceof>>

class Student {String name;String address;float gpa;

public void goToClass( ) { // code here }

public Student(String argName) { name = argName;

}}

Student s1 = new Student(“Chris”);Student s2 = new Student(“Mike”);Student s3 = new Student(“Chris”);

Here’s someJava. Notice how concept

maps to code.

Page 269: Dotnet Stream

269©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.

Objects in Action

A sneak peakat UML notation!

Student

name : Stringaddress : Stringgpa : float

goToClass( )Student(name: String)

Class

Attributes

Operations

s1:Student

name = “Chris”

Constructor

s2:Student

name = “Mike”

s3:Student

name = “Chris”

Obj

ects

<<instanceof>> <<instanceof>> <<instanceof>>

class Student {string name;string address;float gpa;

public void goToClass( ) { // code here }

public Student(string argName) { name = argName;

}}

Student s1 = new Student(“Chris”);Student s2 = new Student(“Mike”);Student s3 = new Student(“Chris”);

Same thing in C#. Notice how concept

maps to code.

Page 270: Dotnet Stream

270©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

Inheritance is a relationship between classes• 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

Inheritance is also known as Generalization

Page 271: Dotnet Stream

271©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.

Subclasses are also called:• Children• Descendant• Specializations

Superclasses are also called:• Parent• Ancestor• Base class

Inheritance in Action

Student

goToClass()

“is-a”

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

StudentList slist = new StudentList();slist.addStudent(s1);slist.addStudent(s2);slist.addStudent(s3);

s1.goToClass();s2.goToClass();s3.goToClass();

StudentList

addStudent(Student)getNextStudent() : Student

Subclassesinherit goToClass( )

behavior

A subclass instance may be used wherever superclass is expected!

This will also work

PayingStudent KeaneStudent

Page 272: Dotnet Stream

272©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.

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

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

Student s = slist.getNextStudent();s.goToClass();

Page 273: Dotnet Stream

273©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.

Dynamic Behavior

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

StudentList slist = new StudentList();slist.addStudent(s1);slist.addStudent(s2);

Student

goToClass()

PayingStudent

goToClass()

KeaneStudent

goToClass()

Override goToClass(). Goes directly to

next class

Override goToClass(). Collects evals first

:StudentList

s1:PayingStudent

s2:KeaneStudent

while(still students in the list)Student s = slist.getNextStudent();s.goToClass();

}

Class is over!

goToClass() :Student

:StudentgoToClass()

Sign the students into class

Goes directlyto next class

Collects evalsfirst

Page 274: Dotnet Stream

274©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.

PolymorphismFormal Definition

• 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”

"Many Forms"

Page 275: Dotnet Stream

275©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.

Requirements Change

Changing requirements have little impact

Student

goToClass()

PayingStudent

goToClass()

KeaneStudent

goToClass()

AuditStudent

goToClass()

A new type of studentis added with its ownimplementation of

goToClass().

PayingStudent s1 = new PayingStudent(“Mike”);KeaneStudent s2 = new KeaneStudent(“Chris”);AuditStudent s3 = new AuditStudent(“Jeff”);

StudentList slist = new StudentList();slist.addStudent(s1);slist.addStudent(s2);slist.addStudent(s3):

while(still students on the list)Student s = slist.getNextStudent();s.goToClass();

}

New class instantiated and added to the list

Inheritance at work.

No Changes needed!Polymorphism at work!

Page 276: Dotnet Stream

276©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.

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

Page 277: Dotnet Stream

277©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.

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

goToClass()

PayingStudent

goToClass()

KeaneStudent

goToClass()

AuditStudent

goToClass()

No behavior implemented.

Page 278: Dotnet Stream

278©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.

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?

Page 279: Dotnet Stream

279©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.

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

Page 280: Dotnet Stream

280©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

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

Page 281: Dotnet Stream

281©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.

Quiz - Encapsulation

If you know a subclass will need to access your classes attributes, is it OK to declare them as protected?

Page 282: Dotnet Stream

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.

ClassClass

Page 283: Dotnet Stream

283©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

Employee

PropertiesEmployee ID

Name

Department

Address

Graduation

….

Classjoin()

leave()

retire()

changeDetails()

Behavior

Engineer

Executive

Manager

Page 284: Dotnet Stream

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.

AbstractionAbstraction

Page 285: Dotnet Stream

285©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

Service Request

Instantiation

Software Request Hardware Request Job Request email Request

Page 286: Dotnet Stream

286©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.

Benefits of Abstraction

• Supports modeling• Reduces code redundancy• Encourages reusability • Encourages extensibility• It allows us to take a high level view

Page 287: Dotnet Stream

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.

EncapsulationEncapsulation

Page 288: Dotnet Stream

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

Encapsulation

• Is capturing attributes and operations together in an object for effective re-use

• Provides sense of ownership to the object and distributes responsibility

Service Request

Request No

Location

Cubical

…..

approve()

reject()

….

Employee

Employee Id

Name

…..

join()

assignGroup()

retire()

….

Page 289: Dotnet Stream

289©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.

Benefits of Encapsulation

• Modularity• Information Hiding• Program independence

Page 290: Dotnet Stream

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.

IdentityIdentity

Page 291: Dotnet Stream

291©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 referenceEmployee Id: 123

Employee Id: 2345

Employee Id: 2343Employee Id: 6748 Employee Id: 5436

Identity: Employee IdName:Deepa

Name: Deepak Name:Raj

Name:Raj

Name:Riya

Identity: Employee Name

Page 292: Dotnet Stream

292©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

Object

Employee Employee Id: 2543 Join, AssigntoGroup Project delivery Group

Software Request

Request No: BLR/Jan04/1232

Approve, Reject, Assign

For Approval

Identity Behaviour State

Page 293: Dotnet Stream

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 RelationshipsObject Relationships

Page 294: Dotnet Stream

294©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

Example :

Data Cables

BIOS

Computer

Monitor Base Unit Keyboard

Hard Disk Power SupplyMotherboard

CPURAM

Page 295: Dotnet Stream

295©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

• A property that allows subordinate class objects to use (inherit) the data and methods of a parent class

• Building up new data types from existing ones• A reuse mechanism

Service Request

Request No

Location

Cubical

…..

approve()

reject()

….

Hardware Service Request

CPU Speed

RAM

HDD

…..

.

Software Service Request

Project Specific

Non-Project Specific

…..

.

Page 296: Dotnet Stream

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.

Thank You !!Thank You !!

Page 297: Dotnet Stream

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 Introduction to .Net FrameworkFramework

COE – Current Technologies

Page 298: Dotnet Stream

298©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

ERP & BillingCustomerService

Sales

UsersAny device,Any place,Any time

XML Web ServicesIntegrate business applications and processes

Back OfficeHeterogeneous application and server infrastructure

SchedulingAuthentication

Notification

Page 299: Dotnet Stream

299©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 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 frameworkIncludes a common runtime

.NET Framework

Page 300: Dotnet Stream

300©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 model for .NETPlatform for running .NET managed code in a virtual machineProvides a very good environment to develop networked applications and Web ServicesProvides programming API and unified language-independent development framework

.NET Framework

Page 301: Dotnet Stream

301©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.

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.

Page 302: Dotnet Stream

302©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 Framework Common Language Runtime

Operating SystemOperating System

Common Language RuntimeCommon Language Runtime

• CLR manages code execution at runtime• Memory management, thread management, etc.

Page 303: Dotnet Stream

303©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 Framework Base Class Library

Operating SystemOperating System

Common Language RuntimeCommon Language Runtime

.NET Framework (Base Class Library).NET Framework (Base Class Library)

• Object-oriented collection of reusable types• Collections, I/O, Strings, …

Page 304: Dotnet Stream

304©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 Framework Data Access Layer

Operating SystemOperating System

Common Language RuntimeCommon Language Runtime

.NET Framework (Base Class Library).NET Framework (Base Class Library)

ADO .NET and XMLADO .NET and XML

• Access relational databases• Disconnected data model• Work with XML

Page 305: Dotnet Stream

305©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 Framework ASP.NET & Windows Forms

Operating SystemOperating System

Common Language RuntimeCommon Language Runtime

.NET Framework (Base Class Library).NET Framework (Base Class Library)

ADO .NET and XMLADO .NET and XML

ASP .NETASP .NETWeb Forms Web ServicesWeb Forms Web Services

Mobile Internet ToolkitMobile Internet Toolkit

WindowsWindowsFormsForms

• Create application’s front-end – Web-based user interface, Windows GUI, Web services, …

Page 306: Dotnet Stream

306©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 Framework Programming Languages

Operating SystemOperating System

Common Language RuntimeCommon Language Runtime

.NET Framework (Base Class Library).NET Framework (Base Class Library)

ADO .NET and XMLADO .NET and XML

ASP .NETASP .NETWeb Forms Web ServicesWeb Forms Web Services

Mobile Internet ToolkitMobile Internet Toolkit

WindowsWindowsFormsForms

C++C++ C#C# VB.NETVB.NET PerlPerl J#J# ……

• Use your favorite language

Page 307: Dotnet Stream

307©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 Framework Common Language Specification

Operating SystemOperating System

Common Language RuntimeCommon Language Runtime

.NET Framework (Base Class Library).NET Framework (Base Class Library)

ADO .NET and XMLADO .NET and XML

ASP .NETASP .NETWeb Forms Web ServicesWeb Forms Web Services

Mobile Internet ToolkitMobile Internet Toolkit

WindowsWindowsFormsForms

Common Language SpecificationCommon Language SpecificationC++C++ C#C# VBVB PerlPerl J#J# ……

Page 308: Dotnet Stream

308©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 Framework Visual Studio .NET

Operating SystemOperating System

Common Language RuntimeCommon Language Runtime

.NET Framework (Base Class Library).NET Framework (Base Class Library)

ADO .NET and XMLADO .NET and XML

ASP .NETASP .NETWeb Forms Web ServicesWeb Forms Web Services

Mobile Internet ToolkitMobile Internet Toolkit

WindowsWindowsFormsForms

Common Language SpecificationCommon Language Specification

C++C++ C#C# VBVB PerlPerl J#J# ……V

isua

l Stu

dio

.NE

TV

isua

l Stu

dio

.NE

T

Page 309: Dotnet Stream

309©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.

Operating SystemOperating System

Common Language RuntimeCommon Language Runtime

.NET Framework (Base Class Library).NET Framework (Base Class Library)

ADO .NET and XMLADO .NET and XML

ASP .NETASP .NETWeb Services Web FormsWeb Services Web Forms

Mobile Internet ToolkitMobile Internet Toolkit

WindowsWindowsFormsForms

Common Language SpecificationCommon Language Specification

C++C++ C#C# VBVB PerlPerl J#J# ……V

isua

l Stu

dio

.NE

TV

isua

l Stu

dio

.NE

T

Open LanguageOpen LanguageSpecificationSpecification

C# Language – C# Language – Submitted to ECMASubmitted to ECMA

XML-basedXML-baseddata accessdata access

Web services –Web services –XML, SOAP-basedXML, SOAP-based

.NET Framework Standards Compliance

Page 310: Dotnet Stream

310©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.

Manages running code – like a virtual machineThreadingMemory managementNo interpreter: JIT-compiler produces native code – during the program installation or at run time

Fine-grained evidence-based securityCode access security

Code can be verified to guarantee type safetyNo unsafe casts, no un-initialized variables and no out-of-bounds array indexing

Role-based security

.NET Framework

Page 311: Dotnet Stream

311©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.

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)

.NET Framework – Managed Code

Page 312: Dotnet Stream

312©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 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

Page 313: Dotnet Stream

313©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 Framework - Multiple Language Support

IL (MSIL or CIL) – Intermediate LanguageIL (MSIL or CIL) – Intermediate Language It is low-level (machine) language, like Assembler, but is Object-It is low-level (machine) language, like Assembler, but is Object-

oriented oriented CTS is a rich type system built into the CLRCTS is a rich type system built into the CLR

Implements various types (Implements various types (intint, float, string, …), float, string, …) And operations on those typesAnd operations on those types

CLS is a set of specifications that all languages and libraries need to CLS is a set of specifications that all languages and libraries need to followfollow

This will ensure interoperability between languagesThis will ensure interoperability between languages

Page 314: Dotnet Stream

314©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 Framework - Multiple Language Support

.NET languages are compiled to an Intermediate Language (IL)

IL is also known as MSIL or CILCLR 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

Page 315: Dotnet Stream

315©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 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

Page 316: Dotnet Stream

316©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 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

Page 317: Dotnet Stream

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.

Thank You !Thank You !

Page 318: Dotnet Stream

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 C# 2.0 on Visual Studio 20052005

COE – Current Technologies

Page 319: Dotnet Stream

319©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 language4) Data Types5) Variables6) Enumeration Types7) Operators8) Statements9) Arrays10)Class11)Structures12)Debugging In Visual Studio 2005

Page 320: Dotnet Stream

320©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.

13) Visual Studio Class Designer 14) Classes & Object15) Properties16) Property visibility 17) Partial Classes 18) Static Class 19) Structures20) Inheritance21) Abstract methods and Classes.22) Operator Overloading & Type Conversion23) Interface24) Indexers

Topics

Page 321: Dotnet Stream

321©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.

25) Nested Classes26) Generics 27) Callbacks & Delegate28) Anonymous methods 29) Events30) Exception Handling31) Inline Warning 32) Refactoring - Visual Studio 2005

Topics

Page 322: Dotnet Stream

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 C#Introduction to C#

Page 323: Dotnet Stream

323©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 objectNext generation robust and durable

softwarePreservation of investment

Page 324: Dotnet Stream

324©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.

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

Page 325: Dotnet Stream

325©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.

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

Page 326: Dotnet Stream

326©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.

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

Page 327: Dotnet Stream

327©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.

Hello World

using System;using System;

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

Page 328: Dotnet Stream

328©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# 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

Page 329: Dotnet Stream

329©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# 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; } }}

Page 330: Dotnet Stream

330©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.

Type System

Value types• Directly contain data• Cannot be null

Reference types• Contain references to objects• May be null

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

123123ii

ss "Hello world""Hello world"

Page 331: Dotnet Stream

331©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.

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();

Page 332: Dotnet Stream

332©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.

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

Page 333: Dotnet Stream

333©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.

Classes

Single inheritanceMultiple interface implementationClass members

• Constants, fields, methods, properties, indexers, events, operators, constructors, destructors

• Static and instance members• Nested types

Member access• public, protected, internal, private

Page 334: Dotnet Stream

334©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.

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

Page 335: Dotnet Stream

335©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.

Interfaces

Multiple inheritanceCan contain methods, properties, indexers, and

eventsPrivate interface implementations

interface IDataBound{ void Bind(IDataBinder binder);}

class EditBox: Control, IDataBound{ void IDataBound.Bind(IDataBinder binder) {...}}

Page 336: Dotnet Stream

336©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.

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,}

Page 337: Dotnet Stream

337©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.

Delegates

Object oriented function pointersMultiple 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);

Page 338: Dotnet Stream

338©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.

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

Stream

MemoryStream FileStream

Hashtable doubleint

object

Page 339: Dotnet Stream

339©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.

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

Page 340: Dotnet Stream

340©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

Properties are “smart fields”

public class Button: Control{ private string caption;

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

Page 341: Dotnet Stream

341©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.

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

Page 342: Dotnet Stream

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

XML Comments

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

Page 343: Dotnet Stream

343©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

First class user-defined data typesUsed 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…

Page 344: Dotnet Stream

344©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.

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)

Page 345: Dotnet Stream

345©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.

Versioning

class Derived: Baseclass Derived: Base // version 1// version 1{{ public virtual void Foo() {public virtual void Foo() { Console.WriteLine("Derived.Foo"); Console.WriteLine("Derived.Foo"); }}}}

class Derived: Baseclass Derived: Base // version 2a// version 2a{{ new public virtual void Foo() {new public virtual void Foo() { Console.WriteLine("Derived.Foo"); Console.WriteLine("Derived.Foo"); }}}}

class Derived: Baseclass Derived: Base // version 2b// version 2b{{ public override void Foo() {public override void Foo() { base.Foo();base.Foo(); Console.WriteLine("Derived.Foo"); Console.WriteLine("Derived.Foo"); }}}}

class Baseclass Base // version 1// version 1{{}}

class Base class Base // version 2 // version 2 {{ public virtual void Foo() {public virtual void Foo() { Console.WriteLine("Base.Foo"); Console.WriteLine("Base.Foo"); }}}}

Page 346: Dotnet Stream

346©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.

Conditional Compilation

#define, #undef#if, #elif, #else, #endif

• Simple boolean logic

Conditional methods

public class Debugpublic class Debug{{ [Conditional("Debug")][Conditional("Debug")] public static void Assert(bool cond, String s) {public static void Assert(bool cond, String s) { if (!cond) {if (!cond) { throw new AssertionException(s);throw new AssertionException(s); }} }}}}

Page 347: Dotnet Stream

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 - IDEVisual Studio 2005 - IDE

Page 348: Dotnet Stream

348©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

Page 349: Dotnet Stream

349©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

ToolBox

Form Designer

Code Defnision Window

Soluition Explorer

Properties

Page 350: Dotnet Stream

350©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

Page 351: Dotnet Stream

351©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

Page 352: Dotnet Stream

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# Programming C# Programming languagelanguage

Page 353: Dotnet Stream

353©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

Page 354: Dotnet Stream

354©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.

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

Page 355: Dotnet Stream

355©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.

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]);

}}

}}

Page 356: Dotnet Stream

356©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.

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

Page 357: Dotnet Stream

357©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.

Setting Command line arguments

Thru Project -> <Proj Name> Properties menu

Page 358: Dotnet Stream

358©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.

Output of Command line program

Page 359: Dotnet Stream

359©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.

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

Page 360: Dotnet Stream

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

Data 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

Page 361: Dotnet Stream

361©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.

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)

Page 362: Dotnet Stream

362©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.

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

Page 363: Dotnet Stream

363©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.

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

Page 364: Dotnet Stream

364©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.

Built In Data typesbyte 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 precisionUsed in Financial calculations

long 8 byte System.Int64 Signed

ulong 8 byte System.Uint64 Unsigned

Page 365: Dotnet Stream

365©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.

• 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

Variables

Page 366: Dotnet Stream

366©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.

Variables definitionFormat

Datatype var1, var2, var3….. ;

e.g. int x, y;

float interest;

Variables can take an initial valuee.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

Page 367: Dotnet Stream

367©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.

Variables definition - Quiz

1. These thing mean the same. Why there are 2 types?

int x = 10; System.Int32 x = 10;

Page 368: Dotnet Stream

368©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.

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

Page 369: Dotnet Stream

369©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.

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 developere.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

Page 370: Dotnet Stream

370©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.

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

Page 371: Dotnet Stream

371©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.

Formatting numeric types

CurrencyConsole.Write("{0:C}", 2.5); // $2.50 Console.Write("{0:C}", -2.5); // ($2.50)

DecimalConsole.Write("{0:D5}", 25); // 00025

ScientificConsole.Write("{0:E}", 250000); // 2.500000E+005

Fixed PointConsole.Write("{0:F2}", 25); // 25.00Console.Write("{0:F0}", 25); // 25

GeneralConsole.Write("{0:G}", 2.5); // 2.5

Number Console.Write("{0:N}", 2500000); //2,500,000.00

HexaDecimalConsole.Write("{0:X}", 250); // FA

Page 372: Dotnet Stream

372©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.

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

Page 373: Dotnet Stream

373©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.

Constants

A Constant is a variable whose value cannot be changedconst float PI = 3.14F;

General form const datatype Constant-name = value;

(e.g)

const int Sunday = 1;

const int Monday = 2; //etc.

Page 374: Dotnet Stream

374©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.

Enumerations

• A new data type of named integer constants• Variable defined of this type can take a value

from a predefined setenum 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

Page 375: Dotnet Stream

375©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.

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 constantsLayerType layer = 0; //not allowed

Enumeration type variables can be assigned only values defined with in the enum leading to Strong type checking

Page 376: Dotnet Stream

376©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.

Enumerations – values

• Enumerations need not take zero based values alwaysenum TemperatureLimits {

FreezingPoint = 32,

BoilingPoint = 212

}

enum CrazySet {

FirstVal, //value 0

SecondVal = 3, //value 3

ThirdVal, //value 4

FourthVal = 10, //value 10

FifthVal //value 11

}

Page 377: Dotnet Stream

377©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.

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 5Y = x = 5;

Sets variable x with value 5 and then y with value 5

Page 378: Dotnet Stream

378©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.

Operators & Assignment

• Assignment with expressionint 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 decrementx += 1; //increment x i.e. x gets 6

• Can be written asx++; or ++x;

• Similarly decrement is byx--; or --x

Page 379: Dotnet Stream

379©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.

Operators & Assignment

• Post Incrementint x = 5;

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

• Pre Incrementint x = 5;

int y = ++x; //x becomes 6 and y gets 6

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

Page 380: Dotnet Stream

380©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.

Statements

Statement is a complete program instructionApart from Simple assignment statements we

have• Selection or Conditional statements• Iteration Statements• Jump Statements• Exception statements (Covered separately)

Page 381: Dotnet Stream

381©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.

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

Page 382: Dotnet Stream

382©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.

Relational OperatorsAssume 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 Equals

x >= 5 true

y >= 11 false

Less than x < y true

Less than or Equals

x <= y true

y <= 6 false

Page 383: Dotnet Stream

383©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.

Conditional Operators

Work on Relational expressionsAssume 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

Page 384: Dotnet Stream

384©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.

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

Page 385: Dotnet Stream

385©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.

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.");

} }

Page 386: Dotnet Stream

386©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.

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

Page 387: Dotnet Stream

387©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.

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."); }

Page 388: Dotnet Stream

388©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.

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

Page 389: Dotnet Stream

389©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.

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

Page 390: Dotnet Stream

390©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.

switch case Sample …

switch(n) {

case 1: cost += 25; // Add 25 Centsbreak;

case 2: cost += 25; // Add 25 centsgoto case 1; // Add another 25 thru case 1

case 3:

cost += 50; // Add 50 centsgoto 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:’ )

Page 391: Dotnet Stream

391©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.

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;

}

Page 392: Dotnet Stream

392©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.

Ternary Operator

A conditional operator Involves 3 operandsSyntaxConditional Expression ? expr1 : expr2

Returns expr1 if condition is true expr2 otherwise

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

Page 393: Dotnet Stream

393©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.

Bitwise operators

For all above binary operators except “~”Short hand notation is applicable as

x &= 2; //same as x = x & 2

& 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 ShiftOperand << count

Empty bits on the low order are filled with zeros

>> Right ShiftOperand >> count

Empty bits on the high order filled with sign bit for uint and ulong, zeros for int and long

Page 394: Dotnet Stream

394©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.

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;}

Page 395: Dotnet Stream

395©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.

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

Page 396: Dotnet Stream

396©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.

Iteration StatementsUsed to execute statement(s) repeatedly (a.k.a. loops)The statements executed in order unless a jump statement or

selection statement is encounteredEvery 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 conditionJump statements could be used to exit out of a loop

Page 397: Dotnet Stream

397©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.

while loop

Syntaxwhile ( Condition )

{

//statements to be executed repeatedly

}

Condition is evaluated before the loop startsIf condition evaluates to true then the statements

executed onceThis is repeated each timeLoop stops once the condition becomes false, flow

jumps to statements after the loop end

Page 398: Dotnet Stream

398©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.

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

Page 399: Dotnet Stream

399©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.

do loop

SyntaxDo

{

//statements to be executed repeatedly

} while ( Condition );

Loop executes atleast onceIf condition evaluates to true then the statements

executed once againThis is repeated each timeLoop stops once the condition becomes false, flow

jumps to statements after the loop end

Page 400: Dotnet Stream

400©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.

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 sampleExecutes once even if n is initialized to 6

Page 401: Dotnet Stream

401©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.

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?

Page 402: Dotnet Stream

402©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.

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

Syntaxfor ([initializers]; [expression]; [iterators])

{//statements to be executed repeatedly

}

Order of execution1. intializers2. Conditional expressions (need to evaluate to true)3. Statements4. Iterators5. Steps 2 , 3, 4

Page 403: Dotnet Stream

403©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.

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 samplesPrints numbers from 1 to 5

Page 404: Dotnet Stream

404©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.

Jump StatementsIn 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

(will be covered in function topic)

Exit out of a function. return 0; inside Main function ends the program.

Page 405: Dotnet Stream

405©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.

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

Page 406: Dotnet Stream

406©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.

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

Page 407: Dotnet Stream

407©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.

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

Page 408: Dotnet Stream

408©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.

Single Dimensional Arrays

Declaring an Arraytype[] ArrayName;

• type can be any datatype (value or reference type)• ArrayName is the variable name to refer the arrayint[] Numbers; //Numbers is an array that can hold integers

Setting a sizeArrayName = new type[size];

• Size is a numberNumbers = new int[5]; //Numbers array can hold 5 integers

ShortCuttype[] ArrayName = new type[size];

int[] Numbers = new int[5]; //Both the steps above together

Page 409: Dotnet Stream

409©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.

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 arrayArrayName[n] where n is between 0 and array length -1

Page 410: Dotnet Stream

410©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.

Array Initialization

Arrays can be initialized with constant valuesThe 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;

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

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

Page 411: Dotnet Stream

411©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.

Multi Dimensional Arrays

Arrays can have more than one dimensionFor 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}};

• Orint[,] myArray = {{1,2}, {3,4}, {5,6}, {7,8}};

Page 412: Dotnet Stream

412©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.

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 samplemyArray.GetUpperBound(0)

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

SimilarlymyArray.GetUpperBound(1)

gives 1

Page 413: Dotnet Stream

413©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.

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.

Page 414: Dotnet Stream

414©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.

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 arraysint[][] myJaggedArray = new int[3][];

• Create child arrays and set values latermyJaggedArray[0] = new int[5];

myJaggedArray[1] = new int[4];

myJaggedArray[2] = new int[2];

• Or Initialize child arraysmyJaggedArray[0] = new int[] {1,3,5,7,9};

myJaggedArray[1] = new int[] {0,2,4,6};

myJaggedArray[2] = new int[] {11,22};

Page 415: Dotnet Stream

415©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.

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}

};

ORint[][] 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

Page 416: Dotnet Stream

416©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.

Quiz

Print the jagged array on the console

Page 417: Dotnet Stream

417©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.

Arrays – Special loop construct

Syntaxforeach (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

Page 418: Dotnet Stream

418©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.

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

Page 419: Dotnet Stream

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 In Visual Studio Debugging In Visual Studio 2005 2005

Page 420: Dotnet Stream

420©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

Page 421: Dotnet Stream

421©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

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.

Page 422: Dotnet Stream

422©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

There are three ways to start a debugging session in Visual Studio.NET

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

Time debugging to step in during an application crash.

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.

Page 423: Dotnet Stream

423©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.

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.

Debugging Features In Visual Studio 2005

Page 424: Dotnet Stream

424©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.

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

Time debugging to step in during an application crash.

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

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.

Debugging Features In Visual Studio 2005

Page 425: Dotnet Stream

425©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.

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.

Page 426: Dotnet Stream

426©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.

When execution reaches a breakpoint, the debugger

pauses all of the application’s threads and allows you to inspect the

state of your application

Breakpoints

Page 427: Dotnet Stream

427©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.

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.

Breakpoints

Page 428: Dotnet Stream

428©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.

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.

Breakpoints

Page 429: Dotnet Stream

429©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.

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

You can also combine logical clauses to set a

condition

Breakpoints

Page 430: Dotnet Stream

430©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.

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.

Breakpoints

Page 431: Dotnet Stream

431©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.

By using Immediate window you can check a value of a variable or a output of a function dynamically at runtime.

Best suted for handling bugs in code

Immediate Window

Page 432: Dotnet Stream

432©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.

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 to see what happens

inside a method call

Step Over if you only want to execute the entire

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

Page 433: Dotnet Stream

433©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.

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.

You can add a variable to the watch window by right

clicking a variable and selecting “Add Watch”.

Watch Window

Page 434: Dotnet Stream

434©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.

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.

Page 435: Dotnet Stream

435©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.

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

Wrap Up

Page 436: Dotnet Stream

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 Visual Studio Class DesignerDesigner

Page 437: Dotnet Stream

437©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.

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.

Visual Studio Class Designer

Page 438: Dotnet Stream

438©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.

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.

Features of Visual Studio Class Designer

Page 439: Dotnet Stream

439©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.

Components of Visual Studio 2005 Class Designer

The Class View

Page 440: Dotnet Stream

440©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.

ToolBox

Class Details Window

Components of Visual Studio 2005 Class Designer

Page 441: Dotnet Stream

441©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.

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.

Page 442: Dotnet Stream

442©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.

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.

Page 443: Dotnet Stream

443©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.

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

Page 444: Dotnet Stream

444©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.

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.

Summary

Page 445: Dotnet Stream

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 & ObjectClass & Object

Page 446: Dotnet Stream

446©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

Page 447: Dotnet Stream

447©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 classes

[attributes] [modifiers] class identifier [:base-list] { class-body

}[;] Items in square brackets are optionalClass 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 classinternal or no modifier – visible only with in current dll or exe , more on this later

attributes & base-list are deferred to a later time

Page 448: Dotnet Stream

448©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 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 variablesThe Syntax is not complete. New modifiers will be

introduced as necessary

Page 449: Dotnet Stream

449©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 class members - behavior

Behavior of the class are defined by functionsFunctions are the very first encapsulation in the

field of programmingThe 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 …

Page 450: Dotnet Stream

450©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.

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

Page 451: Dotnet Stream

451©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.

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 OSBut the functions that are used internally by the

application return data which are used by the code which called the function.

Page 452: Dotnet Stream

452©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.

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

Page 453: Dotnet Stream

453©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.

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

Page 454: Dotnet Stream

454©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.

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 differenceSee 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

Page 455: Dotnet Stream

455©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.

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.

Page 456: Dotnet Stream

456©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.

Changing Parameter value – ref – Two way

Ref parameters are used as two way parametersA value is passed into the function and another

value got out thru the same parameterConsider 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

Page 457: Dotnet Stream

457©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.

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.

Page 458: Dotnet Stream

458©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.

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);

}

Page 459: Dotnet Stream

459©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.

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

Page 460: Dotnet Stream

460©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.

Creating classes

class Kid

{

public int age;

public string name;

// Printing method:

public void PrintKid()

{

Console.WriteLine("{0}, {1} years old.", name, age);

}

}

Page 461: Dotnet Stream

461©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.

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.

Page 462: Dotnet Stream

462©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.

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

Page 463: Dotnet Stream

463©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.

Constructors

• Adding a constructor to Kid classpublic 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

Page 464: Dotnet Stream

464©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.

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

Page 465: Dotnet Stream

465©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.

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

Page 466: Dotnet Stream

466©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 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."); }}

Page 467: Dotnet Stream

467©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.

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

Page 468: Dotnet Stream

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.

PropertiesProperties

Page 469: Dotnet Stream

469©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

Page 470: Dotnet Stream

470©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.

Adding Properties

• Make age and name , privateAdd the following code to Kid Classpublic 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 usingaKid.Age = 9;

Page 471: Dotnet Stream

471©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 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

Page 472: Dotnet Stream

472©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.

Read-Only property

• set block is omitted only get is provided• Or

• Member variable declared aspublic 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

Page 473: Dotnet Stream

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 visibilityProperty visibility

Page 474: Dotnet Stream

474©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

Page 475: Dotnet Stream

475©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.

Example

public class MyClass

{

public string getName

{

get

{

return name;

}

protected set

{

name = value;

}

}

string names; //Rest of the class

}

Page 476: Dotnet Stream

476©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.

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.

Property visibility Considerations

Page 477: Dotnet Stream

477©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.

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);}

Page 478: Dotnet Stream

478©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.

Kid – Complete Source …

public int Age {get { return age; } set {

if ((value < 12) && (value >= 0)) age = value;

elseage = 0;

}}public string Name{

get { return name; }set{

name = (value.Length != 0)? value : name;}

}} //End Class

Page 479: Dotnet Stream

479©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.

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.

}

Page 480: Dotnet Stream

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 ClassPartial Class

Page 481: Dotnet Stream

481©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 ClassesC# 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.

Page 482: Dotnet Stream

482©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.

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.

Partial Classes

Page 483: Dotnet Stream

483©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 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() {...}

}

Aspects of a partial Class

Page 484: Dotnet Stream

484©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.

The non-accumulative aspects are things that all the parts of a type must agree upon. Whether the type is a class or a struct,

public class MyBase{}

public class SomeOtherClass{}

public partial class MyClass : MyBase{}

public partial class MyClass : MyBase{

}

//Does not compile

public partial class MyClass : SomeOtherClass{}

The partial modifier is not available on delegate or enumeration declarations.

Aspects of a partial Class

Page 485: Dotnet Stream

485©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 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.

Partial Class Support

Page 486: Dotnet Stream

486©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.

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.

Advantages of Using Partial Class

Page 487: Dotnet Stream

487©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.

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() { } }}

Partial Class

Page 488: Dotnet Stream

488©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.

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{}

Partial Types

Page 489: Dotnet Stream

489©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.

The following are merged together from all the partial-type definitions: XML comments

interfacesgeneric-type parameter attributesclass attributesmembers

For example, the following declarations:

partial class Kid : Icomparable, Icomparer { }partial class Kid : IEnumerator { } are equivalent to:

class Kid : Icomparable, Icomparer , IEnumerator { }

Partial Types

Page 490: Dotnet Stream

490©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.

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.

Constraints for a partial Class

Page 491: Dotnet Stream

491©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.

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:

publicprivateprotectedinternalabstractsealedbase classnew modifier (nested parts)

generic constraints

Partial Types

Page 492: Dotnet Stream

492©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.

public partial class Kid

{

private string name;

private int age;

public Kid(string x, int y)

{

this.name = x;

this.age = y;

}

}

Partial Class Example

Page 493: Dotnet Stream

493©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.

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();

}}

Partial Class Example

Page 494: Dotnet Stream

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 ClassStatic Class

Page 495: Dotnet Stream

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

Static Class

Under C# 1.1, if you want to prevent people from instantiating objects of your class then you can provide a private default constructor.

Without any public constructors, no one can instantiate objects of your class:

public class Kid

{

private Kid()

{

}

static public object CreateObject()

{...}

}

Page 496: Dotnet Stream

496©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.

Have You Noticed ,C# compiler will still allow you to add instance

members, although they could never

be used.

It is still up to you to enforce the fact that only static members are defined on the class.

public class Kid

{

private Kid()

{

}

static public object CreateObject()

{...}

}

Static Class

Page 497: Dotnet Stream

497©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 adds support for static classes by allowing you to qualify your class as static

public static class Kid

{

private Kid()

{

}

static public T CreateObject<T>()

{...}

}

The C# 2.0 compiler will not allow you to add a non-static member to

a static class

What else…

Static Class

Page 498: Dotnet Stream

498©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.

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.

To Note…

Static Class

Page 499: Dotnet Stream

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.

StructuresStructures

Page 500: Dotnet Stream

500©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…

Page 501: Dotnet Stream

501©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.

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

Page 502: Dotnet Stream

502©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.

Structs …

Creating a Location variableLocation Loc1 = new Location(10,10);

We can also create a struct variable without new ( a characteristic of value type)

But with this sampleLocation 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

Page 503: Dotnet Stream

503©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.

Structs… exercise & Learn

Fix the Location struct so that the following code worksstatic 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 itCompact 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

Page 504: Dotnet Stream

504©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.

Structs sample codepublic 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);}

}

Page 505: Dotnet Stream

505©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.

Boxing & Un-Boxing

Value type variables are short lived and created in stackReference type variables are created in heap (Global

memory)Boxing : Converting a value type into a reference typeUnboxing : Converting reference type to a value typestatic 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

}

Page 506: Dotnet Stream

506©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.

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

Page 507: Dotnet Stream

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# Programming C# Programming languagelanguagePart 2Part 2

Page 508: Dotnet Stream

508©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. Inheritance2. 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. Delegates2. Events

10.Exception Handling.

Page 509: Dotnet Stream

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.

InheritanceInheritance

Page 510: Dotnet Stream

510©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.

InheritanceObjectives :• To build a family of related classes• Code reuse amongst related objectsHow ?• 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

Page 511: Dotnet Stream

511©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.

Simple Inheritance - SampleAssume a typical Payroll application with an

Employee classclass 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; }}

}

Page 512: Dotnet Stream

512©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.

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

Page 513: Dotnet Stream

513©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.

Access Modifiers

Public

Private

Protected

internal

Child Class

Child Class

Unrelated Class

Unrelated Class

Component

Client

Page 514: Dotnet Stream

514©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.

Simple Inheritance - SampleNow a Contractor class inherited from EmployeeThe pay for the contractor is based on overtime

(Specialization)class Contractor : Employee{

public int OverTime; //Additional Attributepublic decimal Rate; //Additional Attributepublic Contractor(int id, string fullName,

decimal baseSalary, int overTime, decimal rate){

EmployeeID = id; //Access base class MembersFullName = fullName; //Access base class MembersBaseSalary = baseSalary; //Access base class MembersOverTime = overTime;Rate = rate;

}public decimal computePay(){

return (BaseSalary + OverTime * Rate);}

}

Page 515: Dotnet Stream

515©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.

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);

}}

}

Page 516: Dotnet Stream

516©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.

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 ……………

Page 517: Dotnet Stream

517©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.

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

Page 518: Dotnet Stream

518©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.

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 belowpublic 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

Page 519: Dotnet Stream

519©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.

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)

Page 520: Dotnet Stream

520©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.

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 classpublic override decimal computePay()

• Now this in Main will print the correct pay for the contractors

foreach (Employee w in Employees)

Page 521: Dotnet Stream

521©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.

Revelation #2 : Inheritance taught by C# compiler

• Now happy compile and happy run• ExerciseMake 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

Page 522: Dotnet Stream

522©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.

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()

Page 523: Dotnet Stream

523©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.

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 signaturepublic void display()

• Compiler warns you to either override or hide display function

• So, to overridepublic override void display()

• Or to Hide public new void display()

Page 524: Dotnet Stream

524©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.

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

Page 525: Dotnet Stream

525©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.

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

Page 526: Dotnet Stream

526©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.

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

Page 527: Dotnet Stream

527©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.

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

Page 528: Dotnet Stream

528©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.

Abstract - Sample

Now the Employee class includes an abstract method

public abstract decimal computeExtraPay();

And a modified display methodpublic 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;}

Page 529: Dotnet Stream

529©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.

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 );}

}

Page 530: Dotnet Stream

530©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.

Contractor – Complete Sourceclass 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;}

}

Page 531: Dotnet Stream

531©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.

Main Function and more revelations

foreach(Employee e in Employees){

//invoke display of base classe.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

Page 532: Dotnet Stream

532©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.

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

Page 533: Dotnet Stream

533©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.

Sealed Classes

This is quite opposite to abstract That is if you don’t want people inheriting from

your class mark them as sealedsealed class MyClass

{

//fields, properties and methods

}

Class YourClass : MyClass //Not Allowed

{

}

Sealed classes logically can not contain any abstract method

Page 534: Dotnet Stream

534©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.

Multiple inheritance

C# permits inheritance from only one classMultiple inheritance is not allowedBut could be achieved indirectly with interface

(a.k.a Mixins)

Page 535: Dotnet Stream

535©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.

Structs & Inheritance

Structs cannot be base classesStructs cannot inherit from other classes

Page 536: Dotnet Stream

536©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 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

Page 537: Dotnet Stream

537©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.

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?

Page 538: Dotnet Stream

538©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.

EqualsRevisit 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))

Page 539: Dotnet Stream

539©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.

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 fieldsreturn(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.

Page 540: Dotnet Stream

540©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.

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

Page 541: Dotnet Stream

541©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.

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 printKid Craig is 11 years old.

Page 542: Dotnet Stream

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 & Operator Overloading & Type ConversionType Conversion

Page 543: Dotnet Stream

543©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…

Page 544: Dotnet Stream

544©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

Let us add this code to Kid classpublic 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

Page 545: Dotnet Stream

545©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.

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);}

Page 546: Dotnet Stream

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

Exercise

• 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

Page 547: Dotnet Stream

547©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.

Type ConversionType conversion (Casting) is also done thru operatorsWe 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

Page 548: Dotnet Stream

548©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.

Implicit Conversion

Add this method to Kid classpublic static implicit operator Human(Kid k)

{

return new Human(k.name, k.age);

}

So we can use this byKid kid1 = new Kid("Craig", 11);

Human h = kid1;

Provide an implicit conversion method only when you are sure of no data loss

Page 549: Dotnet Stream

549©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.

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 classpublic 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

Page 550: Dotnet Stream

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.

InterfaceInterface

Page 551: Dotnet Stream

551©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

Page 552: Dotnet Stream

552©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.

InterfacesThe .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;}

Page 553: Dotnet Stream

553©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.

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 byinterface ICloneable {

Object Clone();

}

Page 554: Dotnet Stream

554©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.

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);}

}

Page 555: Dotnet Stream

555©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.

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");

elseConsole.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

Page 556: Dotnet Stream

556©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.

Comparison - Sorting

Sorting built-in typesint[] 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 objectsProduct[] 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!!!

Page 557: Dotnet Stream

557©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.

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

Page 558: Dotnet Stream

558©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.

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 Productif (this.SKU < p.SKU)

return -1;if (this.SKU > p.SKU)

return 1;return 0;

}}

Page 559: Dotnet Stream

559©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.

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?

Page 560: Dotnet Stream

560©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.

Bit of Interface theoryYou 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 IComparableThis is called Explicit implementationBut note that the comparable could be implemented

implicitly alsoWhy we have not done that is anybody who is holding a

reference to Product object should not access the method just like that!

Page 561: Dotnet Stream

561©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.

CompareTo - rewrittenYou 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 interfacesSo, 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 !

Page 562: Dotnet Stream

562©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.

IComparable - Used

Enough of theory!static void Main(string[] args){

Product[] prods = new Product[5];//Initialize product array, create productsprods[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);}

}

Page 563: Dotnet Stream

563©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.

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 itThen 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}

Page 564: Dotnet Stream

564©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.

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 interfaceand if the object does not implement the interface it

returns null

as operator is efficient than is operator

Page 565: Dotnet Stream

565©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.

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{}

…}

Page 566: Dotnet Stream

566©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.

Enumeration

To iterate over custom collection classesThere are 2 interfaces involved • IEnumerable

• IEnumerator GetEnumerator()

• IEnumerator• void Reset()• object Current {get;} //Property• bool MoveNext()

Page 567: Dotnet Stream

567©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.

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);

}

Page 568: Dotnet Stream

568©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.

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

Page 569: Dotnet Stream

569©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.

Using – Step 3ProductCollection 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 drawbacksTry 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.

Page 570: Dotnet Stream

570©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.

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();}

}

Page 571: Dotnet Stream

571©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.

Using List based CollectionProductList 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);

}

Page 572: Dotnet Stream

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.

IndexersIndexers

Page 573: Dotnet Stream

573©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 arraysAppropriate to add this capability to collection classes

ArrayList is a collection class not a fixed size ArrayWhile 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 ?

Page 574: Dotnet Stream

574©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.

Indexer - Sample

Indexer is like a property the signature ispublic 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?

Page 575: Dotnet Stream

575©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.

Indexer - Sample

Indexer is like a property the signature ispublic 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;

}

}

Page 576: Dotnet Stream

576©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.

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);

}

Page 577: Dotnet Stream

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.

Nested ClassesNested Classes

Page 578: Dotnet Stream

578©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 Interfaceint 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

Page 579: Dotnet Stream

579©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.

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?

Page 580: Dotnet Stream

580©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.

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

Page 581: Dotnet Stream

581©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.

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?

Page 582: Dotnet Stream

582©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.

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.

Page 583: Dotnet Stream

583©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.

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();

Page 584: Dotnet Stream

584©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.

Comparer - SolutionProduct[] 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

Page 585: Dotnet Stream

585©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.

Creating Enumerator

You got it!IEnumerator must be implemented as an inner

classLet 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

Page 586: Dotnet Stream

586©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.

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;

}}

Page 587: Dotnet Stream

587©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.

Enumerator- Solution

Now the outer class ProductCollection implements only IEnumerable

public class ProductCollection : IEnumerable{

private Product[] products;//Constructor//Inner ClassIEnumerator IEnumerable.GetEnumerator(){

//Pass a reference of self //so that the inner class can access the arrayProductEnumerator pe = new ProductEnumerator(this);return((IEnumerator) pe);

}}

The Main MethodProductCollection pc = new ProductCollection();foreach (Product p in pc){

Console.WriteLine("Collections1 - > {0}, {1}, {2:C}", p.SKU, p.Name, p.Price);

}

Page 588: Dotnet Stream

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.

UML For BeginnersUML For Beginners

Page 589: Dotnet Stream

589©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

Page 590: Dotnet Stream

590©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.

Target Audience

• Software Engineer Trainees• SEs/SSEs looking for a basic understanding of

UML

Page 591: Dotnet Stream

591©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

• Understanding of OOPs and basic coding skills

Page 592: Dotnet Stream

592©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.

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

Page 593: Dotnet Stream

593©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 not covered

• Not a full fledged UML course• Advanced concepts in most diagrams are not

covered

Page 594: Dotnet Stream

594©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 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

Page 595: Dotnet Stream

595©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.

Where is UML Used?

Requirements Analysis

•Use Case Diagram•Class diagram•Activity Diagram•State Diagram•Sequence Diagram

•Use Case Diagram•Class diagram•Activity Diagram•State Diagram•Sequence Diagram

How people interact with the system.

Conceptual perspective -A good wayof building up a rigorous vocabulary of the domain.

Can show thecontext for use cases and also the details of how a complicated use case works.

Design

•Class Diagram•Sequence diagram•Package Diagram•State Diagram•Deployment Diagram

•Class Diagram•Sequence diagram•Package Diagram•State Diagram•Deployment Diagram

Show the classes in thesoftware and how they interrelate

To figure out what happens in the software for the use case scenarios

Show the large-scale organization of the softwareFor classes with complex life

histories.Show the physical layout of the software

Used to explain complex use cases

Can be useful if a concept has an interesting life cycle,with various states and events that change that state.

Page 596: Dotnet Stream

596©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.

Types of UML Diagrams and Artifacts

Page 597: Dotnet Stream

597©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.

Purpose of the Diagrams

Diagram PurposeActivity Procedural & Parallel BehavioralClass Class, Features & RelationshipsCommunication Interactions between objects; emphasis on LinksComponent Structure and Connections of ComponentsComposite Structure Runtime Composition of a new classDeployment Deployment of artifacts to nodesInteraction Overview Mix of sequence and Activity DiagramObject Example configurations of instancesPackage Compile Time Hierarchy of StructureSequence Interactions between objects; emphasis on SequencesState Machine How events change an object over its lifeTiming Interactions between objects; Emphasis on timingUse Case How users interact with a system

Page 598: Dotnet Stream

598©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.

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

Page 599: Dotnet Stream

599©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.

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

Page 600: Dotnet Stream

600©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.

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 secondThus 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

Page 601: Dotnet Stream

601©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.

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

Page 602: Dotnet Stream

602©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.

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

Page 603: Dotnet Stream

603©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 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

Page 604: Dotnet Stream

604©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 Diagrams

Page 605: Dotnet Stream

605©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 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

Page 606: Dotnet Stream

606©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.

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

Page 607: Dotnet Stream

607©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.

Constituents of Class Diagram - Properties

Properties appear in two quite distinct notations: attributes and associations

AttributesA 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.

Page 608: Dotnet Stream

608©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.

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:

Page 609: Dotnet Stream

609©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.

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[*].

Page 610: Dotnet Stream

610©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.

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

Page 611: Dotnet Stream

611©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.

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

Page 612: Dotnet Stream

612©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.

Constituents of Class Diagram – Aggregation & …

Page 613: Dotnet Stream

613©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.

Constituents of Class Diagram - Generalization

A relationship where the generalized behavior is segregated into

a parent class.Ex:

Page 614: Dotnet Stream

614©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 Diagrams - Dependencies

•Changes to the definition of one element (the supplier) may cause changes to the other (the client)

Keyword Meaning

«call» The source calls an operation in the target.

«create» The source creates instances of the target.

«derive» The source is derived from the target.

«instantiate» The source is an instance of the target. (Note that if the source isa 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.

Page 615: Dotnet Stream

615©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 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

Page 616: Dotnet Stream

616©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.

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.

Page 617: Dotnet Stream

617©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.

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.

Page 618: Dotnet Stream

618©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.

Sequence Diagrams ...

Another possible approach to this scenario is given.

Page 619: Dotnet Stream

619©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.

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 lifelineshows a participant deleting itself

Page 620: Dotnet Stream

620©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.

Sequence Diagrams – Loops & Conditionals

The image to the left implements the following pseudo code:

procedure dispatchforeach (lineitem)

if (product.value > $10K)careful.dispatch

elseregular.dispatch

end ifend for

if (needsConfirmation) messenger.confirm

end procedure

Page 621: Dotnet Stream

621©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.

Sequence Diagrams – Loops & Conditionals

Loop Operator

Meaning

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 guardindicates the basis of iteration

Page 622: Dotnet Stream

622©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.

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

Page 623: Dotnet Stream

623©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.

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)

Page 624: Dotnet Stream

624©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.

Package Diagrams ...

• Each package represents a namespace

• Every class must have a unique name within its owning package

• Use a fully qualified name that shows the owning package structureE.g. System::Date and MartinFowler::Util::Date

Different ways to represent Packages

Page 625: Dotnet Stream

625©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.

Package Diagrams - Dependencies

•A package diagram shows packages and their dependencies•Interpackage dependencies summarize the dependencies between their contents

Page 626: Dotnet Stream

626©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.

Package Diagrams – Implementing Packages

Page 627: Dotnet Stream

627©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.

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

Page 628: Dotnet Stream

628©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.

Deployment Diagrams

Deployment diagrams show a system's physical layout, revealing which pieces of software run on what pieces of hardware.

Page 629: Dotnet Stream

629©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.

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

Page 630: Dotnet Stream

630©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.

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

Page 631: Dotnet Stream

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.

Thank YouThank You

Page 632: Dotnet Stream

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.

GenericsGenerics

Page 633: Dotnet Stream

633©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 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.

Generics

Page 634: Dotnet Stream

634©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.

Through Generics we can create classes which work on classesYou don’t have to give the types of the classes when you write the codeInstead you use placeholders which are “filled in” at runtime in a type safemanner

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

Generics are new in Version 2.0

Page 635: Dotnet Stream

635©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.

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); }

Avoiding run time exceptions using Generics

Page 636: Dotnet Stream

636©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.

public void PrintKid() { foreach (string k in kids) { Console.WriteLine(k); }

}static void Main(string[]

args){

Kid myKid = new Kid(“Roy", 9); myKid.PrintKid(); } }}

The Program compiles with no Error but at runtime it throws an

invalid cast exception.

It would be better if you can spot these errors at compile time itself.

Avoiding run time exceptions using Generics

Page 637: Dotnet Stream

637©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.

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); }

Generic List

Page 638: Dotnet Stream

638©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.

public void PrintKid() { foreach (string k in kids) { Console.WriteLine(k); }

}

static void Main(string[] args){

Kid myKid = new Kid("Ruby", 9); myKid.PrintKid(); } }}

Now this code generates an error and warns you before u go to runtime.

What’s More…

Generic List

Page 639: Dotnet Stream

639©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.

Using an Arraylist with our Kid class was convenient but this convenience comes at a cost. Any reference or value type that is added to an ArrayList is implicitly upcast to Object. If the items are value types, they must be boxed when added to the list, and unboxed when they are retrieved. Both the casting and the boxing and unboxing operations degrade performance

Hence it is better to implement the kid code like this

List<string> list1 = new List<string>(); //Noboxing,No casting:list1.Add(“Ruby”); list1.Add(9); // Compile-time error:

For client code, the only added syntax with List<T> compared to ArrayList is the type argument in the declaration and instantiation. In return for this slightly greater coding complexity, you can create a list that is not only safer than ArrayList, but also significantly faster, especially when the list items are value types.

Generics

Page 640: Dotnet Stream

640©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.

• Instantiated at run-time, not compile-time

• Checked at declaration, not instantiation

• Work for both reference and value types

• Exact run-time type information

How are C# generics implemented?

Generics increases the performance of your code by eliminating Boxing and UnBoxing.

Page 641: Dotnet Stream

641©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.

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; } }}

Now lets create a method called AddKids to add more Kid objects to the Kid class.

Generics

Page 642: Dotnet Stream

642©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.

public class Kid{ private object[] KidObj; private int count;

public void AddKids(object K) { KidObj[count++] = K; }

public int Count { get { return count; } }}

Generics

Page 643: Dotnet Stream

643©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 KidMain

{

public static void Main()

{

Kid mykid=new Kid();

mykid.AddKids(1);

mykid.AddKids(2);

mykid.AddKids("Three");

}

}

intList.Add(1); // Argument is boxedintList.Add(2); // Argument is boxedintList.Add("Three");

Generics

Page 644: Dotnet Stream

644©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.

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; } }}

Now using Generic Type

Page 645: Dotnet Stream

645©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 KidMain { public static void Main() { Kid<int> mykid = new Kid<int>();

mykid.AddKids(1); mykid.AddKids(2); mykid.AddKids("Three");

}

}

intList.Add(1); // No boxingintList.Add(2); // No boxingintList.Add("Three"); // Compile time error

Now using Generic Type

Page 646: Dotnet Stream

646©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.

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>();

Generic Type Parameters

Page 647: Dotnet Stream

647©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.

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;

Generic Type Parameters

Page 648: Dotnet Stream

648©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

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);

Page 649: Dotnet Stream

649©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.

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> { }

Inheritance with generics

Page 650: Dotnet Stream

650©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.

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 {}

Inheritance with generics

Page 651: Dotnet Stream

651©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.

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> { }

Inheritance with generics

Page 652: Dotnet Stream

652©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.

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() { }

Inheritance with generics

Page 653: Dotnet Stream

653©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.

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>.

Page 654: Dotnet Stream

654©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.

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.

Use of Default Keyword in Generic Code

Page 655: Dotnet Stream

655©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.

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;

} }

Use of Default Keyword in Generic Code

Page 656: Dotnet Stream

656©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.

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

Page 657: Dotnet Stream

657©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.

public class Kid<ItemType>{ private ItemType[] KidObj=new T[5]; private int count;

public void AddKids(ItemType K) { if (count == KidObj.Length) Resize(count * 2); KidObj[count++] = K; }

public int Count { get { return count; } }}

public class Kid<T>{ private T[] KidObj=new T[5]; private int count;

public void AddKids(T K) { KidObj[count++] = K; }

public int Count { get { return count; } }}

Generic Collections

Page 658: Dotnet Stream

658©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.

public class KidCollection { public static void Main() { Kid<int> myKid = new Kid<int>();

myKid.AddKids(1); myKid.AddKids(2); myKid.AddKids("Three"); System.Console.WriteLine(myKid.Count); } }

intList.Add(1); // No boxingintList.Add(2); // No boxingintList.Add("Three"); // Compile time error

Generic Collections

Page 659: Dotnet Stream

659©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.

Collection classes

Collection interfaces

Collection base classes

Utility classes

Reflection

List<T>Dictionary<K,V>SortedDictionary<K,V>Stack<T>Queue<T>

IList<T>IDictionary<K,V>ICollection<T>IEnumerable<T>IEnumerator<T>IComparable<T>IComparer<T>

Collection<T>KeyedCollection<T>ReadOnlyCollection<T>

Nullable<T>EventHandler<T>Comparer<T>

Generic Collections

Page 660: Dotnet Stream

660©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.

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; }

}

Page 661: Dotnet Stream

661©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.

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);

Example (Generic List for Kid Class)

Page 662: Dotnet Stream

662©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.

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();

}

}

Example (Generic List for Kid Class)

Page 663: Dotnet Stream

663©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.

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.

Generics best practices.

Page 664: Dotnet Stream

664©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.

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.

Generics best practices.

Page 665: Dotnet Stream

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.

CallbacksCallbacks

Page 666: Dotnet Stream

666©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!

Page 667: Dotnet Stream

667©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

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!

Page 668: Dotnet Stream

668©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

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

Page 669: Dotnet Stream

669©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.

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

Page 670: Dotnet Stream

670©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.

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);

}

}

Page 671: Dotnet Stream

671©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.

Delegate - Implementingclass 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 methodNote here that the publisher does not have any clue of the

Subscriber class name or the method name which implements the delegate!

Page 672: Dotnet Stream

672©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.

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

Page 673: Dotnet Stream

673©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.

MultiCast Delegate

Attaching more than one function to a delegateWhen publisher calls the delegate all the

attached functions get invokedSince 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);

Page 674: Dotnet Stream

674©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.

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

Page 675: Dotnet Stream

675©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.

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 !

Page 676: Dotnet Stream

676©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.

MultiCasting…

Provide a Main method in another class which hasPersonal p1 = new Personal("David");Personal p2 = new Personal("Goliath");Personal p3 = new Personal("Henry");//Create 3 delegatesDelegateGreetings 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!

Page 677: Dotnet Stream

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 methodsAnonymous methods

Page 678: Dotnet Stream

678©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# supports delegates for invoking one or multiple methods. Delegates provide operators and methods for adding and removing target methods, and are used extensively throughout the .NET Framework for events, callbacks, asynchronous calls, and multithreading.

Anonymous methods is a new feature in C# 2.0 that lets you define an anonymous (that is, nameless) method called by a delegate.

Anonymous methods

Page 679: Dotnet Stream

679©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 Kid

{

delegate void KidDelegate();

public void InvokePrint()

{

KidDelegate del = new KidDelegate(PrintKid);

del();

}

void PrintKid()

{

System.Console.WriteLine ("Kid is printed");

}

}

Did you notice that you are forced to create a class or a method just for the sake of using a delegate.

static void Main(string[] args) { Kid k = new Kid(); k.InvokePrint(); }

Anonymous methods

Page 680: Dotnet Stream

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

You can define and implement the same in a better way with an anonymous method:

class Kid{ delegate void KidDelegate(); public void InvokePrint() { KidDelegate del = delegate() { System.Console.WriteLine ("Kid is printed");}; del(); }}

Now things are simple…

There is no need to invoke a method just to use a Delegate.

Anonymous methods

Page 681: Dotnet Stream

681©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 if you want to pass an anonymous method to a method that accepts an abstract Delegate parameter.

Likevoid KidDelegate(Delegate del);

Ans..cast the anonymous method to the specific delegate type.

Some Q & A

Anonymous methods

Page 682: Dotnet Stream

682©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 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");} } void InvokePrint(KidDelegate del) { del(); } }

static void Main(string[] args) { Kid k = new Kid(); k.PrintKid(); }

Anonymous methods

Page 683: Dotnet Stream

683©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.

Now Let’s take our Thread example using a Anonymous Method

public class Kid

{

public void KidThread()

{

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:

A anonymous method serves as the thread method, causing the

message to be displayed from the new thread.

Anonymous methods

Page 684: Dotnet Stream

684©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.

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”); }}

Passing Parameters to Anonymous Methods

Page 685: Dotnet Stream

685©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.

?

SomeDelegate del = delegate()

Anonymous methods without parametersAns

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(); }}

Anonymous methods

Page 686: Dotnet Stream

686©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.

?

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"); }}

Anonymous methods

Page 687: Dotnet Stream

687©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.

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.

But wait …..

Anonymous methods

Page 688: Dotnet Stream

688©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.

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.

Generic Anonymous Methods

Page 689: Dotnet Stream

689©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 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);

Ok lets sum up this.

Anonymous methods

Page 690: Dotnet Stream

690©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.

button1.Click += delegate(object sender, EventArgs args)

{

MessageBox.Show("Button Clicked !");

};

}

public static void Main()

{

Application.Run(new KidForm());

} }

Anonymous methods

Page 691: Dotnet Stream

691©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.

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

{

delegate void KidDelegate();

public void InvokePrint() {

KidDelegate del = new KidDelegate(PrintKid);

del();

}

void PrintKid() {...}}

In C# 1.1

Delegate Inference

Page 692: Dotnet Stream

692©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 Kid

{

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.

IN C# 2.0

Delegate Inference

Page 693: Dotnet Stream

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.

EventsEvents

Page 694: Dotnet Stream

694©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

Page 695: Dotnet Stream

695©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 Greeting

Let us rewrite the greetings application using eventspublic 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");

}

}

Page 696: Dotnet Stream

696©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 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 eventsp.GotGreetings += new GreetingsHandler(p1.GreetMe);p.GotGreetings += new GreetingsHandler(p2.GreetMe);p.Greet();

Page 697: Dotnet Stream

697©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 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; }}

}

Page 698: Dotnet Stream

698©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 Conventions

Change Publisher class :public delegate void GreetingsHandler

(object o, GreetingEventArgs e);public class Publisher{

public event GreetingsHandler GotGreetings; //Eventpublic Publisher() { }//Wrapper to invoke events – Best Practiceprotected virtual void OnGotGreetings(string message){

if (GotGreetings != null) GotGreetings(this, new

GreetingEventArgs(message));}public void Greet() //Exercise Event Firing{

OnGotGreetings("Good morning");}

}

Page 699: Dotnet Stream

699©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.

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.

Page 700: Dotnet Stream

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 HandlingException Handling

Page 701: Dotnet Stream

701©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

Page 702: Dotnet Stream

702©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 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)>

Page 703: Dotnet Stream

703©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.

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");}

}

Page 704: Dotnet Stream

704©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.

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 executesIf we remove the BadMethod call in the try we can see that

finally is executed stillHere we have caught the exception using the generic base

class exceptionThis 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

Page 705: Dotnet Stream

705©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.

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

}

Page 706: Dotnet Stream

706©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.

User Defined ExceptionsCan 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

• Otherwisepublic myappException(string message)

• StackTrace is usefull here also

Page 707: Dotnet Stream

707©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.

Sample

public class EmployeeListNotFoundException: ApplicationException

{

public EmployeeListNotFoundException(string message)

: base(message)

{

}

public EmployeeListNotFoundException(string message, Exception inner): base(message, inner)

{

}

}

Page 708: Dotnet Stream

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 WarningInline Warning

Page 709: Dotnet Stream

709©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.

Page 710: Dotnet Stream

710©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.

#pragma warning disable 169

public class MyClass

{

int m_Number;

}

#pragma warning restore 169

Example

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.

Inline Warning

Page 711: Dotnet Stream

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.

Refactoring Support Under Refactoring Support Under Visual Studio 2005Visual Studio 2005

Page 712: Dotnet Stream

712©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.

Page 713: Dotnet Stream

713©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.

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.

Page 714: Dotnet Stream

714©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.

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.

Page 715: Dotnet Stream

715©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.

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.

Studio 2005 refactorings.

Page 716: Dotnet Stream

716©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.

Walkthrough - Extract Method

Page 717: Dotnet Stream

717©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.

Walkthrough - Extract Method

Page 718: Dotnet Stream

718©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.

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

Page 719: Dotnet Stream

719©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.

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).

Page 720: Dotnet Stream

720©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.

Walkthrough – Encapsulate Field

Page 721: Dotnet Stream

721©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.

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

Page 722: Dotnet Stream

722©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.

Walkthrough – Encapsulate Field

Page 723: Dotnet Stream

723©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.

Walkthrough – Encapsulate Field

Here is the end result of this Encapsulate Field refactoring.

Page 724: Dotnet Stream

724©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.

Walkthrough – Extract Interface

The Extract Interface refactoring allows you to select a group of existing type members to yield a new interface abstraction.

Page 725: Dotnet Stream

725©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.

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.

Page 726: Dotnet Stream

726©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.

Walkthrough – Extract Interface

Page 727: Dotnet Stream

727©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.

Walkthrough – Local Variable to Parameter

Page 728: Dotnet Stream

728©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.

Walkthrough – Local Variable to Parameter

Page 729: Dotnet Stream

729©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.

Walkthrough – Reorder Parameters

Page 730: Dotnet Stream

730©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.

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

Page 731: Dotnet Stream

731©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.

Walkthrough – Reorder Parameters

Page 732: Dotnet Stream

732©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.

Walkthrough – Rename Parameters

Page 733: Dotnet Stream

733©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.

Walkthrough – Rename Parameters

Page 734: Dotnet Stream

734©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.

Walkthrough – Rename Parameters

Page 735: Dotnet Stream

735©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.

Walkthrough – Remove Parameters

Page 736: Dotnet Stream

736©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.

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

Page 737: Dotnet Stream

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.

Thank YouThank You

Page 738: Dotnet Stream

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.

ProgrammingProgramming with with

.NET Framework.NET Framework

COE – Current Technologies

Page 739: Dotnet Stream

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 CLRAssembly and CLR

Page 740: Dotnet Stream

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

Topics of Discussion

• Understanding Assemblies.• Structure of an Assembly.• Single file, Multifile Assembly.• Metadata and Manifest.• Examining a manifest.• Creating a multimodule Assembly.• Private and Shared Assemblies.• Strong names and Signcode.• Installing an Assembly into Global Assembly Cache

(GAC).

Page 741: Dotnet Stream

741©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.

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.

Page 742: Dotnet Stream

742©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.

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.

Page 743: Dotnet Stream

743©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.

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

All constituents of an assembly are contained within the same physical file.

Assembly metadata

Type Metadata

MSIL Code

Resources

Page 744: Dotnet Stream

744©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.

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

MSIL Code

Type metadata

MSIL Code

Resources

.netmodule

Graphic.bmpMyAssembly.dll

Fig 2: Elements of a multifile Assembly

Page 745: Dotnet Stream

745©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.

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.

Page 746: Dotnet Stream

746©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.

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.

Page 747: Dotnet Stream

747©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.

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.

Page 748: Dotnet Stream

748©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.

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.

Page 749: Dotnet Stream

749©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.

Creating a Multimodule Assembly(Contd..)

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.

Figure 4

Manifest of an assembly

Page 750: Dotnet Stream

750©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.

Creating a Multimodule AssemblyA 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 filesusing System;namespace myNamespace{

public class MultiMod{

public void multiMod(){

System.Console.WriteLine("This is a line from mutiMod method");

}}

}

Page 751: Dotnet Stream

751©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.

Creating a Multimodule Assembly

Use the following command to compile this filecsc /t:module MultiMod.csSpecifying 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 modulesusing System;using myNamespace; //The namespace created in the

MultiMod.netmoduleclass 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 classmod.multiMod();

} }

Page 752: Dotnet Stream

752©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.

Creating a Multimodule AssemblyUse the following command to compile this codecsc /addmodule:MultiMod.netmodule /t:module myMultiMod.csThis 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 linkerYou can use the Assembly Linker(Al.exe) to create an assembly from

a collection of compiled netmodulesAt the Visual Studio .NET command prompt type the following:al myMultiMod.netmodule MultiMod.netmodule

/main:myMultiMod.Main /out:myAssembly.exe /target:exe

Page 753: Dotnet Stream

753©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.

Creating a Multimodule Assembly

When the resulting dll is examined with MSIL Disassembler(ILDasm.exe), it shows the following screen.

Page 754: Dotnet Stream

754©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.

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.

Page 755: Dotnet Stream

755©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.

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.

Page 756: Dotnet Stream

756©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 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.

Page 757: Dotnet Stream

757©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.

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.

Page 758: Dotnet Stream

758©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.

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.

Page 759: Dotnet Stream

759©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.

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.snkThe –k option along with sn(strong name utilty)

indicates to create a file containing the key value pair.

Page 760: Dotnet Stream

760©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.

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 usingal /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.

Page 761: Dotnet Stream

761©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.

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\assemblyThe 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.

Page 762: Dotnet Stream

762©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.

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.dllSample output is:

Public key is002400000480000094000000060200000024000052534131000400

00010001004dcc7b5243839e5789e1f12bbd817daf20a55fe22bc0a29e7c245137f227c2980cf0415356154221111c37e2ce33ff666526a35dd08f1b7e5ca6235abd156f702243df4e86b29a37213cc8105a9cb774fba036d4b7ac116b8f2a1d41bb73f5644771eefb359fdecd7059437bedbfd0cf7e2092ddf0bf3ad200b1c5547fa7cbb4

Public key token is a179f8bc5bfc3463

DIY:Create a mutlimodule assembly, signcode it and install it into the

Global Assembly Cache (GAC).

Page 763: Dotnet Stream

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.

Application DomainsApplication Domains

Page 764: Dotnet Stream

764©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.

Page 765: Dotnet Stream

765©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.

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.

Page 766: Dotnet Stream

766©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.

Application Domains

Process A Process B Process C

EXE

DLL DLL

EXE

DLL DLL

EXE

Figure 1: The Win32 Process boundary.Separate Processes

App Domain App Domain App Domain

DLL

EXE

EXE

EXE EXE

DLL

PROCESS A

Figure 2 : A PROCESS DIVIDED INTO APPLICATION DOMAINS

Page 767: Dotnet Stream

767©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.

Benefits of Application DomainsThe 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.

Page 768: Dotnet Stream

768©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.

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.

Page 769: Dotnet Stream

769©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.

Creating Application DomainsA 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:

Page 770: Dotnet Stream

770©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.

Creating Application Domains

public ObjectHandle CreateInstance(string assemblyName,string typeName,bool ignoreCase,BindingFlags bindingAttr,Binder binder,object[] args,CultureInfo culture,object[] activationAttributes,Evidence securityAttributes);

Page 771: Dotnet Stream

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.

ThreadsThreads

Page 772: Dotnet Stream

772©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.

Page 773: Dotnet Stream

773©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.

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.

Page 774: Dotnet Stream

774©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.

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();

Page 775: Dotnet Stream

775©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.

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();} }

Page 776: Dotnet Stream

776©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.

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.

Page 777: Dotnet Stream

777©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.

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.

Page 778: Dotnet Stream

778©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.

Suspending a Threadpublic class ThreadInterruptDemo { public static void Main(){

ThreadInterruptDemo thd=new ThreadInterruptDemo();thd.testInterrupt();}

public void testInterrupt(){Thread th1=new Thread(new ThreadStart(moveUp));th1.Start(); Thread.Sleep(5000);//Causes the Thread to sleep for

5 seconds before starting the other Thread.Thread th2=new Thread(new ThreadStart(moveDown)); th2.Start(); }

public void moveUp(){for(int k=0;k<100;k++){

Console.WriteLine("Up {0}",k); }}

public void moveDown(){for(int m=100;m>1;m--){

Console.WriteLine("Down {0}",m); }

}}

Page 779: Dotnet Stream

779©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.

Joining Threads

Blocks the calling thread until a thread terminates.When you tell a thread to stop processing and wait until

a second threadcompletes 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);

Page 780: Dotnet Stream

780©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.

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."); } }

Page 781: Dotnet Stream

781©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.

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 StateThe thread responds to Thread.Start and starts running. RunningThe thread calls Thread.Sleep.WaitSleep JoinThe thread calls Monitor.Wait on another object. WaitSleepJoinThe thread calls Thread.Join on another thread. WaitSleepJoinAnother thread calls Thread.Suspend. SuspendRequestedThe thread responds to a Thread.Suspend request. SuspendedAnother thread calls Thread.Resume. RunningAnother thread calls Thread.Interrupt. RunningAnother thread calls Thread.Abort. AbortRequestedThe thread responds to a Thread.Abort. Aborted

Page 782: Dotnet Stream

782©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.

Thread PrioritiesThreads 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.

Page 783: Dotnet Stream

783©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.

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"); }

Page 784: Dotnet Stream

784©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.

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);

}}}

Page 785: Dotnet Stream

785©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.

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

Page 786: Dotnet Stream

786©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.

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);

Page 787: Dotnet Stream

787©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.

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);}}

Page 788: Dotnet Stream

788©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.

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.

Page 789: Dotnet Stream

789©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.

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); } }

Page 790: Dotnet Stream

790©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.

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.

Page 791: Dotnet Stream

791©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.

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.

Page 792: Dotnet Stream

792©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.

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.

Page 793: Dotnet Stream

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.

File HandlingFile Handling

Page 794: Dotnet Stream

794©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

Page 795: Dotnet Stream

795©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

• Readers and Writers.• Working with BinaryReader and BinaryWriter.• Working with StreamReader and StreamWriter.• Working with TextReader and TextWriter.• Working with Buffered Streams.

Page 796: Dotnet Stream

796©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.

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.

Page 797: Dotnet Stream

797©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.

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

Page 798: Dotnet Stream

798©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.

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()SetCurrentDirectory()

Returns or Sets the current Directory.

GetLogicalDrives Returns an array indicating the logical drives on the hard disk.

GetDirectories Gets an array of subdirectories within the specified directory.

GetLastAccessTime()SetLastAccessTime()

Gets or sets the last time the specified directory was accessed.

Page 799: Dotnet Stream

799©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.

Methods of DirectoryInfo class

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.

The prominent attributes and methods of DirectoryInfo class are :

Page 800: Dotnet Stream

800©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.

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 {} }}

Working with Directories

Page 801: Dotnet Stream

801©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.

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); }}

Page 802: Dotnet Stream

802©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.

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()); } }}

Page 803: Dotnet Stream

803©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.

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); }

Page 804: Dotnet Stream

804©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.

Moving Directoriescatch (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);

}}

Page 805: Dotnet Stream

805©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.

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 likeDirectoryInfo, 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.

Page 806: Dotnet Stream

806©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.

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.

Page 807: Dotnet Stream

807©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.

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.

Page 808: Dotnet Stream

808©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.

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()SetLastAccessTime()

Returns or sets the last time the specified file was accessed.

GetLastWriteTime()SetLastWriteTime()

Returns or sets the last time the specified file was written to.

Page 809: Dotnet Stream

809©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.

Exploring the FileInfo class

Method/Property Description

Atrributes() Gets or sets the attributes of the current file.

Directory Returns the name of parent directory.

Length Gives the size of the current file.

Name Gives the name of the current file.

Extension Gives the file extension of the current file.

AppendText() Creates a StreamWriter that appends text to a file.

MoveTo() Moves a file to the new location.Used for renaming.

OpenRead() Creates a read only FileStream.

OpenText() Creates a StreamReader to read from an existing file.

OpenWrite() Creates a Read/Write FileStream.

Page 810: Dotnet Stream

810©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.

Working with Files

The following FileStream constructor opens an existing file (FileMode.Open).

[Visual Basic] Dim s2 As New FileStream(name, FileMode.Open,

FileAccess.Read, FileShare.Read)[C#] FileStream s2 = new FileStream(name, FileMode.Open,

FileAccess.Read, FileShare.Read);

Page 811: Dotnet Stream

811©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.

Working with File Class methodsusing System;using System.IO;class Test { public static void Main() { string path = "d:\\Testing.txt"; FileInfo fi1 = new FileInfo(path); if (!fi1.Exists) { //Create a file to write to. using (StreamWriter sw = fi1.CreateText()) { sw.WriteLine("Hello"); sw.WriteLine("And"); sw.WriteLine("Welcome"); } } //Open the file to read from. using (StreamReader sr = fi1.OpenText()) { string s = ""; while ((s = sr.ReadLine()) != null) { Console.WriteLine(s); } }

Page 812: Dotnet Stream

812©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.

Working with File class methods (Contd..) try { string path2 = path + "temp"; FileInfo fi2 = new FileInfo(path2); //Ensure that the target does not exist. fi2.Delete(); //Copy the file. fi1.CopyTo(path2); Console.WriteLine("{0} was copied to {1}.", path,

path2); //Delete the newly created file. fi2.Delete(); Console.WriteLine("{0} was successfully deleted.",

path2); } catch (Exception e) { Console.WriteLine("The process failed: {0}", e.ToString());

} }}

Page 813: Dotnet Stream

813©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.

Readers and WritersSystem.IO namespace provides reader and writer classes to read and

write data in different formats.The following type of reader and writer classes are available.

• BinaryReader andBinaryWriter: ** Reads and Writes primitive data types as binary values in a specific encoding.** Important methods are Read( ), Write( ),BeginRead( ), BeginWrite( ), and Flush( ).

• StreamReader and StreamWriter.** StreamReader is designed for character input in a particular encoding .** StreamReader is used for reading lines of information from a standard text file. **StreamWriter is designed for character output in a particular Encoding, whereas classes derived from Stream are designed for byte input and output.

Page 814: Dotnet Stream

814©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.

Readers and Writers (Contd..) TextReader and TextWriter.

** TextReader and TextWriter are the abstract base class of StringReader and StringWriter, which read characters from streams and strings, respectively.

** While TextReader opens a text file for reading a specified range of characters .

** An instance of TextWriter is used to write an object to a string, write strings to a file, or to serialize XML. BufferedStream –Read and Write :

** A buffered stream object allows the operating system to create its own internal buffer, and read bytes to and from the backing store.

** The buffer is filled from the in-memory buffer, not from the backing store.

** The net effect is that the input and output are more efficient and thus faster.

Page 815: Dotnet Stream

815©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.

Working with BinaryReader and BinaryWriter

using System;using System.IO;class MyStream { private const string FILE_NAME = "Test.data"; public static void Main(String[] args) { // Create the new, empty data file. if (File.Exists(FILE_NAME)){ Console.WriteLine("{0} already exists!", FILE_NAME); return; } FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew); // Create the writer for data. BinaryWriter w = new BinaryWriter(fs); // Write data to Test.data. for (int i = 0; i < 11; i++) { w.Write( (int) i); } w.Close(); fs.Close(); // Create the reader for data. fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader(fs); // Read data from Test.data. for (int i = 0; i < 11; i++) { Console.WriteLine(r.ReadInt32()); } w.Close(); }}

Page 816: Dotnet Stream

816©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.

Working with StreamReader and StreamWriter

using System;using System.IO;class Test { public static void Main() {

// Create an instance of StreamWriter to write text to a file.

StreamWriter sw = new StreamWriter("TestFile.txt");

// Add some text to the file.

sw.Write("This is the ");

sw.WriteLine("header for the file.");

sw.WriteLine("-------------------");

// Arbitrary objects can also be written to the file.

sw.Write("The date is: ");

sw.WriteLine(DateTime.Now);

sw.Close();

StreamReader sr=new StreamReader("TestFile.txt");

while(sr.Peek()> -1) {Console.WriteLine(sr.ReadToEnd()); }

} }

Page 817: Dotnet Stream

817©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.

Working with TextReader and TextWriter

using System;using System.IO;public class TextToFile { private const string FILE_NAME = "MyFile.txt"; public static void Main(String[] args) { if (File.Exists(FILE_NAME)){ Console.WriteLine("{0} already exists.", FILE_NAME); return; } StreamWriter sr = File.CreateText(FILE_NAME); sr.WriteLine ("This is my file.");

sr.WriteLine ("I can write ints {0} or floats {1}, and so on.", 1,4.2);

sr.Close();StreamReader sr = File.OpenText(FILE_NAME);

String input; while ((input=sr.ReadLine())!=null){ Console.WriteLine(input); } Console.WriteLine ("The end of the stream has been reached."); sr.Close(); }}

Page 818: Dotnet Stream

818©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.

using System;using System.IO;class Tester {const int SizeBuff = 1024;public static void Main( ) {// make an instance and run itTester t = new Tester( );t.Run( ); }// Set it running with a directory nameprivate void Run( ){ // create binary streamsStream inputStream = File.OpenRead(@"D:\testing.txt");Stream outputStream = File.OpenWrite(@"D:\testing.bak");// add buffered streams on top of the binary streamsBufferedStream bufferedInput =new BufferedStream(inputStream);BufferedStream bufferedOutput =new BufferedStream(outputStream);byte[] buffer = new Byte[SizeBuff];int bytesRead;while ( (bytesRead =bufferedInput.Read(buffer,0,SizeBuff)) > 0 ) {bufferedOutput.Write(buffer,0,bytesRead); }bufferedOutput.Flush( );bufferedInput.Close( );bufferedOutput.Close( ); } }

Working with Buffered Streams

Page 819: Dotnet Stream

819©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.

Do it yourself (DIY)

Create a menu driven console application to 1. Accept the employee detail such as

name,empNo,location,department and write the details to a file.

2. Search for a particular record based upon the empNo and display the specified record on the console else display a failure message.

3. Append details to the file.4. Delete a specified record based upon the empNo.5. Move the file to another specified location.

Page 820: Dotnet Stream

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.

SerializationSerialization

Page 821: Dotnet Stream

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

Topics of Discussion

• Understanding Serialization • Serialization-Default• Binary Serialization.• Soap / XML Serialization.• Selective Serialization.• Custom Serilaization.

Page 822: Dotnet Stream

822©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.

Serialization

Persisting the state of an object to a storage medium so that the object could be resurrected later

Used to pass objects (by value) from one app-domain to another (even across machines)

• Used for saving session state in ASP.Net• To copy object to and from clip board in windows

forms

Page 823: Dotnet Stream

823©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.

Serialization

Persisting the state of an object to a storage medium so that the object could be resurrected later

Used to pass objects (by value) from one app-domain to another (even across machines)

• Used for saving session state in ASP.Net• To copy object to and from clip board in windows

forms

Page 824: Dotnet Stream

824©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.

Serialization – Default

Any class that needs to be serialized must be marked with “Serializable” attribute[Serializable] //Attribute required

class Kid

{

//Other code - Unchanged

}

Two types of serialization• Binary • Soap (XML)

Based on the type a formatter is used (BinaryFormatter or SoapFormatter)

Page 825: Dotnet Stream

825©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.

Binary Formatter

Kid k1 = new Kid("George", 11);

//Write to the file

IFormatter formatter = new BinaryFormatter();

Stream stream = new FileStream("Kids.bin", FileMode.Create, FileAccess.Write, FileShare.None);

formatter.Serialize(stream,k1); //Write Kid to file

stream.Close();

//Reading from file

IFormatter formatterR = new BinaryFormatter();

Stream streamR = new FileStream("kids.bin", FileMode.Open, FileAccess.Read, FileShare.Read);

//Read Kid from file

Kid k2 = (Kid)formatterR.Deserialize(streamR);

streamR.Close();

Page 826: Dotnet Stream

826©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.

Serialization

For the code to work add the following namespaces :using System.IO;

using System.Runtime.Serialization;

using System.Runtime.Serialization.Formatters.Binary;

For Soap formatting ( XML ) the namespaces are :using System.IO;

using System.Runtime.Serialization;

using System.Runtime.Serialization.Formatters.Soap;

And reference to System.Runtime.Serialization.Formatters.Soap.dll

assembly

Page 827: Dotnet Stream

827©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.

Serialization – Soap / XML

Kid[] kids = { new Kid("Craig", 11), new Kid("David", 9)};

IFormatter formatter = new SoapFormatter();Stream stream = new FileStream("Kids.xml",

FileMode.Create, FileAccess.Write, FileShare.None);

formatter.Serialize(stream,kids);stream.Close();

IFormatter formatterR = new SoapFormatter();Stream streamR = new FileStream("kids.xml",

FileMode.Open, FileAccess.Read, FileShare.Read);

Kid[] kids2 = (Kid [])formatterR.Deserialize(streamR);streamR.Close();foreach (Kid k2 in kids2)

Console.WriteLine("{0}", k2);

Page 828: Dotnet Stream

828©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.

Selective Serialization

If you don’t want to store some state variables of the object mark the variables with

[NonSerialized] attribute

[Serializable]

public class MyObject

{

public int n1;

[NonSerialized] public int n2;

public String str;

}

Only n1 and str are stored and restored!

Page 829: Dotnet Stream

829©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.

Custom Serialization

The default serialization works using reflection and hence

It will access the private state variables and construct by not using the constructors

If we want to change the way objects are stored • With different field names (so that the files could be

viewed with another application)• A Different XML tag set ( interoperability of different

applications) Custom serialization needs to be used

Done by implementing ISerializable interface!public void GetObjectData(SerializationInfo info,

StreamingContext context)

Used while serializing the object.

Page 830: Dotnet Stream

830©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.

Custom Serialization

public void GetObjectData(SerializationInfo info, StreamingContext context)

{

info.AddValue("Name", this.name);

info.AddValue("Age", this.age);

}

To help DeSerialization provide a constructor :public Kid(SerializationInfo info, StreamingContext context)

{

this.Name = info.GetString("Name");

this.Age = info.GetInt32("Age");

}

Exercise : Provide custom serialization for the product class, Load products from a file in catalog’s private constructor

Page 831: Dotnet Stream

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.

Thank YouThank You

Page 832: Dotnet Stream

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.

COE – Current Technologies

DOTNET Part IIDOTNET Part II

Page 833: Dotnet Stream

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

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

ADO.NET 2.0ADO.NET 2.0

* For internal use only

COE – Current Technologies

Page 834: Dotnet Stream

834©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.

Index

1) Overview of ADO.NET2) ADO.NET Components3) ADO.NET and the .NET Framework4) ADO.NET Architecture5) A Simple DataGridView - Demo6) ADO.NET objects7) Execute Scalar8) The DataReader9) The DataSet10)DataSet Enhancements11)XML and the DataSet12)Using Data Set - Demo

Page 835: Dotnet Stream

835©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.

Index

13)The DataTable14)The DataRelation15)The DataView16)DataBinding17)DataSet Serialization 18)Bulk Copy Operation19)Batch Update20)Data Paging 21)DataTable's Load and Save Methods22)DbProvidersFactories Class23)Asynchronous Execution24)ADO.net Best Practices

Page 836: Dotnet Stream

836©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.

Overview of ADO.NET

ADO.NET provides consistent access to data sources such as Microsoft SQL Server and XML, as well as to data sources exposed through OLE DB and ODBC.

ADO.NET separates data access from data manipulation into discrete components that can be used separately or in tandem.

ADO.NET includes .NET Framework data providers for connecting to a database, executing commands, and retrieving results.

Those results are either processed directly, placed in an ADO.NET DataSet object in order to be exposed to the user in an ad hoc manner, combined with data from multiple sources, or remoted between tiers.

Page 837: Dotnet Stream

837©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.

Overview of ADO.NET

The ADO.NET DataSet object can also be used independently of a .NET Framework data provider to manage data local to the application or sourced from XML.

The ADO.NET classes are found in System.Data.dll, and are integrated with the XML classes found in System.Xml.dll. When compiling code that uses the System.Data namespace, reference both System.Data.dll and System.Xml.dll

ADO.NET provides functionality to developers writing managed code similar to the functionality provided to native component object model (COM) developers by ActiveX Data Objects (ADO).

Page 838: Dotnet Stream

838©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.

Features of ADO.NET

Disconnected Data AccessXML SerializableData source IndependenceXSDData Set as a “Relational Data Store”Transaction SupportThe Base-Class-Based Provider Model.Connection Pooling Enhancements.Asynchronous Commands.Bulk ImportProvider StatisticsAttachDbFileNameSQL Server 2005-Specific Features in SqlClient

Page 839: Dotnet Stream

839©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.

Database connectivity through ADO.NET

Traditional Data Access Architecture

ADO.Net Disconnected Data Access Architecture

Page 840: Dotnet Stream

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

ADO.NET Components

There are two components of ADO.NET that you can use to access and manipulate data:

.NET Framework data providers

The DataSet

Page 841: Dotnet Stream

841©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 Framework Data Providers

The .NET Framework Data Providers are components that have been explicitly designed for data manipulation and fast, forward-only, read-only access to data. The Connection object provides connectivity to a data source.

The Command object enables access to database commands to return data, modify data, run stored procedures, and send or retrieve parameter information.

The DataReader provides a high-performance stream of data from the data source. Finally, the DataAdapter provides the bridge between the DataSet object and the data source. The DataAdapter uses Command objects to execute SQL commands at the data source to both load the DataSet with data, and reconcile changes made to the data in the DataSet back to the data source.

Page 842: Dotnet Stream

842©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.

DataSet

The ADO.NET DataSet is explicitly designed for data access independent of any data source. As a result, it can be used with multiple and differing data sources, used with XML data, or used to manage data local to the application.

The DataSet contains a collection of one or more DataTable objects made up of rows and columns of data, as well as primary key, foreign key, constraint, and relation information about the data in the DataTable objects.

Page 843: Dotnet Stream

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

ADO.NET and the .NET Framework

Microsoft .NET Framework

Common Language Runtime

Base Classes

Web Services User Interface

Data and XML

ADO.NET XML ... ...

Page 844: Dotnet Stream

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

ADO.NET namespace hierarchy• Organizes the object model• Includes:

System.Data

System.Data.OleDb

System.Data.Common

System.Data.SqlClient

System.Data.SqlTypes

Page 845: Dotnet Stream

845©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.

System.Data Namespace

Contains the basis and bulk of ADO.NETData-centric namespaceProvides the means to work on and with

your data!

Classes and methods to manipulate your data

Ability to create views of your data

Means to logically represent your data

Enables the use of XML to view, share, and store

data

Page 846: Dotnet Stream

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

ADO.NET Architecture

Business TierBusiness Tier Data TierData Tier

Presentation TierPresentation Tier

Windows Forms

Web Forms

Business to Business

Data Object (Class)

DataSet

DataSetDataSet

InternetInternetIntranetIntranet

Data AdapterData Adapter

Data AdapterData Adapter

(BizTalk, for example)

XML

MyApp.Exe

IE

Page 847: Dotnet Stream

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

ADO.NET Architecture

A connection object establishes the connection for the application with the database. The command object provides direct execution of the command to the database. If the command returns more than a single value, the command object returns a DataReader to provide the data. Alternatively, the DataAdapter can be used to fill the Dataset object. The database can be updated using the command object or the DataAdapter.

Page 848: Dotnet Stream

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

ADO.NET objects

Basic ADO.NET objects

Page 849: Dotnet Stream

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

ADO.NET object Model

ADO.NET object Model

Page 850: Dotnet Stream

850©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.

A Simple DataGridView - Demo

Page 851: Dotnet Stream

851©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.

A Simple DataGridView - Demo

> Choose DataSource

Page 852: Dotnet Stream

852©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.

A Simple DataGridView - Demo

> View Button

Page 853: Dotnet Stream

853©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.

A Simple DataGridView - Demo

> Choose SqlServerDataSource

Page 854: Dotnet Stream

854©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.

A Simple DataGridView - Demo

Page 855: Dotnet Stream

855©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.

A Simple DataGridView - Demo

> View ServerExplorer

Page 856: Dotnet Stream

856©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.

A Simple DataGridView - Demo

> Set Identity

Page 857: Dotnet Stream

857©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.

A Simple DataGridView - Demo

> Save Table

Page 858: Dotnet Stream

858©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.

A Simple DataGridView - Demo

Page 859: Dotnet Stream

859©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.

A Simple DataGridView - Demo

> Include Password in ConectionString

Page 860: Dotnet Stream

860©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.

A Simple DataGridView - Demo

Page 861: Dotnet Stream

861©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.

A Simple DataGridView - Demo

Page 862: Dotnet Stream

862©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.

A Simple DataGridView - Demo

Page 863: Dotnet Stream

863©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.

A Simple DataGridView - Demo

> Auto Size Property

Page 864: Dotnet Stream

864©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.

A Simple DataGridView - Demo

Page 865: Dotnet Stream

865©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.

A Simple DataGridView - Demo

> Execute Query

Page 866: Dotnet Stream

866©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.

A Simple DataGridView - Demo

> Add New Record

Page 867: Dotnet Stream

867©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.

A Simple DataGridView - Demo

> Create a DataTable

Page 868: Dotnet Stream

868©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.

A Simple DataGridView - Demo

Page 869: Dotnet Stream

869©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.

A Simple DataGridView - Demo

> Choose DataType for Coloumn

Page 870: Dotnet Stream

870©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.

A Simple DataGridView - Demo

> Set RelationShip

Page 871: Dotnet Stream

871©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.

A Simple DataGridView - Demo

Page 872: Dotnet Stream

872©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.

Introducing the Objects…

Contains the “main” classes of

ADO.NET

In-memory cache of data

In-memory cache of a database

table

Used to manipulate a row in a

DataTable

Used to define the columns in a

DataTable

Used to relate 2 DataTables to each

other

Used to create views on DataSets

System.Data

DataTable

DataRow

DataRelation

DataColumn

DataViewManager

DataSet

Page 873: Dotnet Stream

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

ADO.NET objects

Core objects

Connection - Establishes a connection to a database.

Command - Represents an individual SQL statement that can be executed against the database.

Data reader - Provides read-only, forward-only access to the data in a database.

Data adapter - Provides the link between the command and connection objects and a dataset object

Page 874: Dotnet Stream

874©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.

Connection object

Specifies what data source to connect to

ConnectionString property

Database connections will directly affect

application scalability

Keep connection open for as little time as

possible

Connections are pooled automatically (can

override)

Make sure connection strings are spelled

exactly alike

Page 875: Dotnet Stream

875©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.

Connection code

public void DoConnect(){ String connectionString = “”; connectionString = “server=P3C20014;uid=sa;pwd=pwd;database=rOY” SqlConnection conn = new SqlConnection(connectionString); try { conn.Open(); } catch (Exception e) {

// Handle and log error } finally { conn.Close(); }}

Page 876: Dotnet Stream

876©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.

Command Object

Issues and executes commands on the data storeCommandText – Command to run against data sourceCommandType – Type of command (stored proc)Exposes overloaded constructors to allow customization

at initial object creationParameters collection – Pass in parameter objectsExecuteReader

Executes a query and returns a DataReaderUse CommandBehavior enum to close underlying connection

ExecuteNonQuery Executes a query but returns no data

ExecuteScalarExecutes and returns a single value

Page 877: Dotnet Stream

877©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.

Command Code

String connectionString = “”; connectionString = “server=localhost;uid=sa;pwd=pwd;database=Northwind” SqlConnection conn = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(“<SP Name>", conn); cmd.CommandType = CommandType.StoredProcedure; try { conn.Open(); cmd.ExecuteNonQuery(); } catch (Exception e) { // Handle and log error } finally { conn.Close(); }

Page 878: Dotnet Stream

878©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.

Command Parameters

String connectionString = “”; connectionString = “server=P3C20014;uid=sa;pwd=sa;database=Roy” SqlConnection conn = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(“sp_listproductsbycategory", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@categoryid", 1);

SqlParameter parm = New SqlParameter("@categoryid", 1) cmd.Parameters.Add(parm);

SqlParameter parm2 = new SqlParameter("@categoryid", SqlDbType.Int, 4);

parm2.Value = 5; cmd.Parameters.Add(parm2);

Page 879: Dotnet Stream

879©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.

DataReader Object

Fast, read-only, forward-only, connected method for

data extraction

Does not support scrolling or updating

Supports databinding to controls

DataReader is not creatable

It’s returned as the result of executing an

appropriate method of a Command object

Close connection automatically with

CommandBehavior enumeration

Page 880: Dotnet Stream

880©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.

DataReader Code

String connectionString = “”;connectionString = “server=p3c20014;uid=sa;pwd=sa;database=Roy”SqlConnection con = new new SqlConnection(connectionString);SqlCommand cmd = new SqlCommand("CustomerByCountry",con);cmd.CommandType = CommandType.StoredProcedure;cmd.Parameters.Add(new SqlParameter("@publications",SqlDbType.Int)).Value = 3;con.Open();ArrayList al = new ArrayList();SqlDataReader dr = cmd.ExecuteReader();while(dr.Read()) {

object[] values = new object[dr.FieldCount]; dr.GetValues(values); al.Add(values);} dr.Close();con.Close();

Page 881: Dotnet Stream

881©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.

DataAdapter Object

Knows how to load a table from a DataStore and write changes

Exposes two methods:Fill (DataSet and Table)Update (DataSet and Table)

Provides mappings between tables and columnsUsers can provide explicit insert/update/delete commands

Such as, specify stored procedures

Allows single DataSet to be populated from multiple data sourcesSupport for ADO RecordSet

SelectCommand

InsertCommand

DeleteCommand

ConnectionConnectionDataAdapterDataAdapter

ConnectionConnection

UpdateCommandUpdateCommand

SelectCommandSelectCommand

InsertCommandInsertCommand

DeleteCommandDeleteCommand

TableMappingsTableMappings

Page 882: Dotnet Stream

882©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.

DataSet ObjectDisconnected, feature-rich method for

data accessRelational views of data

Contains tables, columns, rows, constraints, views and relations

Read/Write XML/XSDDisconnected model

Has no knowledge of data source Strong typingSupports data binding Supports batch updatesConnects to data source via DataAdapter

DataSetDataSet

TablesTables

TableTable

ColumnsColumns

ColumnColumn

ConstraintsConstraints

ConstraintConstraint

RowsRows

RowRow

RelationsRelations

RelationRelation

Page 883: Dotnet Stream

883©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.

DataAdapter/DataSet Code

using System;Using System.Data;Using System.Data.SqlClient;Namespace CodeExample{ Class Example{ static void Main(string[] args){ SqlConnection conn = new SqlConnection("data source=p3c20014;initial catalog=Northwind;UserId = sa; pwd=sa;“ DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter("select * from Customers", conn); da.Fill(ds, “Customers"); }}

Page 884: Dotnet Stream

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

XML and ADO.NET

ADO.NET leverages the power of XML to provide disconnected access to data. ADO.NET was designed hand-in-hand with the XML classes in the .NET Framework both are components of a single architecture.

ADO.NET and the XML classes in the .NET Framework converge in the DataSet object.

The DataSet can be populated with data from an XML source, whether it is a file or an XML stream.

Page 885: Dotnet Stream

885©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.

Database connectivity through ADO.NET

ADO.NET: Data and XMLADO.NET: Data and XML

OleDbOleDb SqlClientSqlClient

CommonCommon SQLTypesSQLTypes

System.Data

XSLXSLSerializationSerialization

XPathXPath

System.Xml

Page 886: Dotnet Stream

886©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.

Putting the Objects Together…

DataSet Tables

DataTable

Relations

DataRelation

DataRelation

DataRow(s)

DataColumn

Constraint(s)

DataTable

DataTable

DataView

DataViewManager

Page 887: Dotnet Stream

887©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.

Putting the Objects Together…

Page 888: Dotnet Stream

888©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.

Execute Scalar Method 

Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

Page 889: Dotnet Stream

889©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.

Execute Scalar - Demo

private void CmdDisp_Click(object sender, System.EventArgs e){

string strConst ="Server=s2b21675;user id=sa;pwd=sa;Database=pubs";

SqlConnection objSql=new SqlConnection();objSql.ConnectionString=strConst;

string strQry="Select count(*) from titles where type ='"+TxtTitle.Text+"'";

SqlCommand objCmd=new SqlCommand(strQry,objSql);

objCmd.CommandType= CommandType.Text;int reportVal=0;try{

objCmd.Connection.Open();reportVal=(int )objCmd.ExecuteScalar();

}

Page 890: Dotnet Stream

890©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.

Execute Scalar - Demo

catch(SqlException exc){

MessageBox.Show(exc.Message);}finally{

if(objSql.State ==ConnectionState.Open){

objSql.Close();}

}MessageBox .Show("The title of type "+TxtTitle.Text+" are "+reportVal);

}

Page 891: Dotnet Stream

891©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.

The Data Reader

The DataReader provides a forward-only, read-only, connected stream recordset from a database.

Unlike other components of the Data Provider, DataReader objects cannot be directly instantiated. Rather, the DataReader is returned as the result of the Command object's ExecuteReader method.

The SqlCommand.ExecuteReader method returns a SqlDataReader object, and the OleDbCommand.ExecuteReader method returns an OleDbDataReader object.

The DataReader can provide rows of data directly to application logic when you do not need to keep the data cached in memory. Because only one row is in memory at a time, the DataReader provides the lowest overhead in terms of system performance but requires the exclusive use of an open Connection object for the lifetime of the DataReader.

Page 892: Dotnet Stream

892©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.

Using Data Reader - Demo

Page 893: Dotnet Stream

893©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.

Using Data Reader - Demo

private void Reader_Load(object sender, System.EventArgs e){

string strConn = "Data Source=p3c20037;uid=sa;pwd=sa;Initial Catalog=pubs";

SqlConnection objConn = new SqlConnection(strConn);

string str = "Select * from titles";

SqlCommand objCom = new SqlCommand(str,objConn);

objCom.CommandType=CommandType.Text;SqlDataReader dr = null;

Page 894: Dotnet Stream

894©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.

Using Data Reader - Demo

try{

if(objConn.State==ConnectionState.Closed){

objConn.Open();dr=objCom.ExecuteReader();while(dr.Read()){

comboBox1.Items.Add(dr["title_id"].ToString());

}dr.Close();

}}

Page 895: Dotnet Stream

895©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.

Using Data Reader - Demo

catch(SqlException objs){

throw objs;}finally{

dr.Close();if(objConn.State==ConnectionState.Open){

objConn.Close();}

}

}

Page 896: Dotnet Stream

896©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.

DataReader's Execute Methods

DataReader's Execute Methods

Besides the ExecuteNonQuery, ExecuteReader, ExecuteScaler, and ExecuteXmlReader, the new execute methods are ExecutePageReader, ExecuteResultSet, and ExecuteRow.

Page 897: Dotnet Stream

897©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.

The DataSet

An in-memory cache of data from a data source

Common way to represent and manipulate data

Universal data containerNot just for use with databases

Logical or physical representation of dataDesigned to be disconnected from the data

sourceConnect, execute query, disconnect

Can use XML To read and write data To read and write XMLSchema

Page 898: Dotnet Stream

898©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.

Typed vs. Untyped Datasets

Data can be loaded into a DataSet at runtime without having to specify the structure beforehand.Have to access fields by “string” that is, myDataSet.myTable[0][“SomeColumn”]This is called an Untyped DatasetAlternative is to use Visual Studio to predefine the structure and relationships (visually of course)This approach is called a Typed DataSet

Page 899: Dotnet Stream

899©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.

Typed Datasets

Typed Datasets are great!Means that the table, field and data types are

available at design time.This leads to huge benefits:

Compile time type checking – can’t put string in int field.Compiler will spot incorrect spellings as the type won’t existBest of all: tooltip/autocomplete in IDE

Page 900: Dotnet Stream

900©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.

Typed vs. Untyped - Example

Accessing data in an untyped dataset:

foreach ( DataRow row in myDataSet.Tables[ “MyTable” ] ){ myStringValue = (String)row[ “MyColumnName” ];}

Accessing data in a typed dataset:

Foreach ( MyTableRow row in myDataSet.MyTable ){ myStringvalue = row.MyColumnName;}

No casting necessary - Clearer to read

Page 901: Dotnet Stream

901©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.

DataSet Enhancements

Performance and scalability improvements• Internal Indexing of Rows

Inserts and deletes much fasterUpdates almost constantSelects are faster too

• Binary Serialization of ContentsV 1.x DataSet always serialized to XMLBinary serialization an option in V 2.0

Performance and scalability improvements• Internal Indexing of Rows

Inserts and deletes much fasterUpdates almost constantSelects are faster too

• Binary Serialization of ContentsV 1.x DataSet always serialized to XMLBinary serialization an option in V 2.0

Page 902: Dotnet Stream

902©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.

DataSet Enhancements

More Loading Options• DataAdapter.Fill

DataAdapter.FillLoadOption

LoadOptions.OverwriteChanges

LoadOptions.PreserveChanges

LoadOptions.Upsert

More Loading Options• DataAdapter.Fill

DataAdapter.FillLoadOption

LoadOptions.OverwriteChanges

LoadOptions.PreserveChanges

LoadOptions.Upsert

DataSet theSet = new DataSet();

SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Customers", "...");

da.FillLoadOption = LoadOption.OverwriteChanges;da.Fill(theSet, "Customers");

Page 903: Dotnet Stream

903©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.

DataSet Enhancements

DataSet.LoadLoad from DataReader directly FillErrorEventHandler to handle loading errorsAlso supports LoadOptions

Stream data From DataSetDataSet.GetDataReader method

returns a DataTableReader

RowState values are now updateableDataRow.SetAdded and DataRow.SetModified

Page 904: Dotnet Stream

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

XML and the DataSet

DataSet can read/write XML for its data and/or schema• You can create or modify data in a DataSet using XML• You can create or modify the DataSets schema using

XMLXML-related DataSet methods for reading:

• ReadXml: Reads an XML schema and data into the DataSet

• ReadXmlSchema: Reads an XML schema into the DataSet

And for writing: • WriteXml, WriteXmlSchema• GetXml, GetXmlSchema

Namespace property: sets the namespace for serializationFull support for SQL Server-style DiffGrams

Page 905: Dotnet Stream

905©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.

Using Data Set - Demo

Page 906: Dotnet Stream

906©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.

Using Data Set - Demo

private void Grid_Load(object sender, System.EventArgs e){

string str="Server=p3c20014;user id=sa;pwd=sa;Initial Catalog=pubs";

SqlConnection obj=new SqlConnection(str);string strcmd="select * from titles";SqlDataAdapter objAdapter=new

SqlDataAdapter(strcmd,obj);DataSet ds=new DataSet();try{

obj.Open();objAdapter.Fill(ds);

}

Page 907: Dotnet Stream

907©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.

Using Data Reader - Demo

catch(SqlException e1){

MessageBox.Show(e1.Message);}finally{

if(obj.State==ConnectionState.Open)obj.Close();

dataGrid1.DataSource=ds.Tables[0].DefaultView;}

}

Page 908: Dotnet Stream

908©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.

The DataTable

May be mapped to a physical table in the data source

Can be related to one another through DataRelations

Optimistic concurrency or locking - modelProperties of Interest:

Columns: Returns ColumnsCollection of DataColumns

Rows: Returns DataRow objects as a RowsCollection

ParentRelations: Returns the RelationsCollection

Constraints: Returns the table’s ConstraintsCollection

DataSet: Returns the DataSet of the DataTable

PrimaryKey: Gets the DataColumns that make up the

table’s primary key

Page 909: Dotnet Stream

909©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.

DataSet and DataTable

Create a DataTable and add it to a DataSet

DataSet ds = new DataSet();

DataTable dt= new DataTable( “Customers” );DataColumn dc; dc = new DataColumn( “CustID”, Type.GetType("System.Int16"));dt.Columns.Add( dc );dt.Columns.Add( “First_Name”,Type.GetType("System String”));dt.Columns.Add( “Last_Name”, Type.GetType("System String”));

ds.Tables.Add( dt );

Page 910: Dotnet Stream

910©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.

DataTable

First Class SupportDataSet operations now available on DataTable:

ReadXml/WriteXmlReadXmlSchema/WriteXmlSchemaClearCloneCopyMergeGetChanges

First Class SupportDataSet operations now available on DataTable:

ReadXml/WriteXmlReadXmlSchema/WriteXmlSchemaClearCloneCopyMergeGetChanges

DataTable tbl = new DataTable();

// Fill the table

DataTable newTbl = tbl.Clone();

tbl.Merge(newTbl);

DataTable changes = tbl.GetChanges();

Page 911: Dotnet Stream

911©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.

DataTable

DataSet not Required

DataAdapters

Fill(DataTable)

Update(DataTable)

DataReader

DataTable.Load(DataReade

r)

Stream from a DataTable

DataTable.GetTableReader(

)

Page 912: Dotnet Stream

912©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.

The DataRelation

Used to create logical relations between your data

Create relations between two (2) DataTable objectsRequires a DataColumn object from each DataTableThe DataType of both DataColumns must be the same

Cannot relate a Int32 DataColumn and a String DataColumn

The relation is named (by you!)DataRelation dr=new DataRelation( “myRelation”,...)

Makes relational navigation possibleRelationsCollection used to hold/group them

Accessed through the DataSet’s Relations property

Page 913: Dotnet Stream

913©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.

Methods of Reading and Writing XML

String oFile = “C:\\My_ADO.NET\\myXmlOutput.xsd”;String iFile = “C:\\My_ADO.NET\\myXmlInput.xsd”;

mds.WriteXmlSchema( oFile );mds.ReadXml( iFile);

mds.WriteXml( "C:\\My_ADO.NET\\myXmlData.txt", XmlWriteMode.DiffGram);

Page 914: Dotnet Stream

914©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.

The DataView

Create multiple views on DataTable objectsBindable to user interface controlsProperties of Interest:

Table: Retrieves or sets the associated DataTableSort: Gets or sets the table’s sort columns and sort orderRowFilter: Gets or sets the expression used to filter rowsRowStateFilter: Gets or sets the row state filter

None, Unchanged, New, Deleted, ModifiedCurrent, and others

Page 915: Dotnet Stream

915©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.

Creating a DataView

DataView view1 = new DataView( myTable );DataView view2 = new DataView( myTable );

view1.Sort = “Name ASC”;

view2.RowStateFilter= DataViewRowState.ModifiedOriginal;

DataGrid myGrid = new DataGrid();myGrid.SetDataBinding( view1, “Customer”);

Page 916: Dotnet Stream

916©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.

DataView Enhancements

DataView.ToTableCreates a new DataTable from a DataViewSupports Distinct and Column Filtering

DataView.ToTableCreates a new DataTable from a DataViewSupports Distinct and Column Filtering

DataTable filtered = view.ToTable(true, "CompanyName", "ContactName");

Page 917: Dotnet Stream

917©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.

Using DataTable and DataView - Demo

Page 918: Dotnet Stream

918©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.

Using DataTable and DataView - Demo

private void SortData_Load(object sender, System.EventArgs e){

comboBox1.Items.Add("Ascending");comboBox1.Items.Add("Descending");

string strConn = "Data Source=p3c20014;uid=sa;pwd=sa;Initial Catalog=pubs";

SqlConnection objConn = new SqlConnection(strConn);

string strQry = "select distinct(type) from titles";

SqlCommand objCom = new SqlCommand(strQry,objConn);

objCom.CommandType=CommandType.Text;

SqlDataReader dr = null;

Page 919: Dotnet Stream

919©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.

Using DataTable and DataView - Demo

try{

if(objConn.State==ConnectionState.Closed){

objConn.Open();dr=objCom.ExecuteReader();while(dr.Read()){

comboBox2.Items.Add(dr[0].ToString());}dr.Close();

}}

Page 920: Dotnet Stream

920©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.

Using DataTable and DataView - Demo

catch(SqlException objs){

throw objs;}finally{

dr.Close();if(objConn.State==ConnectionState.Open){

objConn.Close();}

}

}

Page 921: Dotnet Stream

921©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.

DataViewManager

Similar to a DataView but DataSet orientedUsed to create multiple views on a DataSet

Ability to automatically set filters on the tables

Properties of Interest:DataViewSettings: Gets the DataView for on each DataTableDataSet: Gets or sets the DataSet to be viewed

CreateDataView methodCreates a DataView on a DataTable

Page 922: Dotnet Stream

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

Data Set

DataViewManager

DataViewSettings

DataSet Tables

DataTable

Relations

DataRelation

DataRelation

DataRow(s)

DataColumn

Constraint(s)

DataTable

DataTable

DataView

DataViewSetting

DataViewSetting

Page 923: Dotnet Stream

923©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.

Insertion Through DataCommand - Demo

Page 924: Dotnet Stream

924©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.

Insertion Through DataCommand - Example

private void cmdOk_Click(object sender, System.EventArgs e)

{

string strConnection="Server=p3c20014;user id=sa;pwd=sa;Initial Catalog=roy";

SqlConnection objConnect=new SqlConnection(strConnection);

string strCmd="Insert into input(EmpId,EmpName,Department,BasicSal) values(@Eid,@Ename,@Dept,@Esal)";

SqlDataAdapter objAd=new SqlDataAdapter(strCmd,objConnect);

Page 925: Dotnet Stream

925©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.

Insertion Through DataCommand - Example

objAd.SelectCommand.Parameters.Add("@Eid",SqlDbType.Char,10,"EmpId");objAd.SelectCommand.Parameters["@Eid"].Value=textBox1.Text;

objAd.SelectCommand.Parameters.Add("@EName",SqlDbType.Char,10,"EmpName");objAd.SelectCommand.Parameters["@EName"].Value=textBox2.Text;

objAd.SelectCommand.Parameters.Add("@Dept",SqlDbType.Char,10,"Dept");objAd.SelectCommand.Parameters["@Dept"].Value=textBox3.Text;

objAd.SelectCommand.Parameters.Add("@Esal",SqlDbType.Char,10,"ESal");objAd.SelectCommand.Parameters["@ESal"].Value=textBox4.Text;

Page 926: Dotnet Stream

926©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.

Insertion Through DataCommand - Example

int resVal=0;try{

objConnect.Open();resVal=objAd.SelectCommand.ExecuteNonQuery();

}catch(SqlException ex){ MessageBox.Show(ex.Message); }finally{

if(objConnect.State==ConnectionState.Open)objConnect.Close();

}if(resVal==0){

MessageBox.Show("Data Insertion not completed");

}else{ MessageBox.Show(resVal+"row inserted "); }

}

Page 927: Dotnet Stream

927©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.

DataBinding

DataBinding is the ability to link data to objects. In practice, it is usually used to display and manage data on a form from a database in an easy way. We can have a table with ten fields shown on a form and the Data-Bindings would automatically manage all the changes and updates made to the fields.

Page 928: Dotnet Stream

928©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.

DataBinding

Windows Form controls can be bound to any data source, not just the traditional database tables. Specifically, objects that implement the IList, IBindingListor, and IEditableObject interface.

Page 929: Dotnet Stream

929©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.

DataBinding - Classes

Binding, BindingContext, BindingManagerBase, & CurrencyManager

The Binding class represents a single data bind between a data source and a control's property.

The BindingContext object is the top-most object in the binding hierarchy and manages the BindingManagerBase objects that control the interaction between a data source and the controls bound to it. It only has one property, Item, that exposes its BindingManagerBase collection.

The BindingManagerBase simply keeps track of the Binding objects associated with a DataTable on the form. The CurrencyManager, which inherits from the BindingManagerBase, tracks state information and creates a cursor for the current record being shown.

Page 930: Dotnet Stream

930©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.

DataBinding - Properties

The three most important properties, Count, Position, and Current, Note that the Current property returns a DataRowView which is then cast to the strong-typed row from which it came.

BindingManagerBase bmb = this.BindingContext[dsMain, "Contacts"];

Console.WriteLine("Number of Records: " + bmb.Count);

Console.WriteLine("Current Position: " + bmb.Position);

(returns a DataRowView) DataRowView drv = (DataRowView) bmb.Current;

DataRow dsContacts.ContactsRow row = (dsContacts.ContactsRow) drv.Row;

Console.WriteLine("Current Contact's Name: " + row.FirstName + " " + row.LastName);

Page 931: Dotnet Stream

931©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.

DataBinding - Methods

The important methods of a BindingManagerBase are AddNew, CancelCurrentEdit, EndCurrentEdit, and RemoveAt.

When a new record is added. The new record is not actually added to the DataTable until either the position changes (invoking EndCurrentEdit) or EndCurrentEdit is manually called.

Page 932: Dotnet Stream

932©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.

DataBinding - Methods

private void AddNewRecord(){BindingManagerBase bmb = this.BindingContext[dsMain, "Contacts"];

DialogResult result = MessageBox.Show("Keep changes made to the current record?", "", MessageBoxButtons.YesNo);if (result == DialogResult.Yes) bmb.EndCurrentEdit(); else bmb.CancelCurrentEdit();bmb.AddNew();dsContacts.ContactsRow row = (dsContacts.ContactsRow) ((DataRowView) bmb.Current).Row;

Console.WriteLine(row.RowState);bmb.EndCurrentEdit();

Console.WriteLine(row.RowState);}

Page 933: Dotnet Stream

933©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.

DataBinding - Events

The two important events in the BindingManagerBase are PositionChanged, which lets you know when the cursor is moved, and CurrentChanged that raises when the current record is being edited.

Page 934: Dotnet Stream

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

ADO.NET: DataRow States

Each DataRow in a DataTable contains state information in a RowState property. This is how the system keeps track of the changes made so that they can be accepted or rejected and saved back to a database.

Here are descriptions of the DataRowState enumerations.

DataRowState.AddedThis row is newly added to the dataset. It did not previously exist. Correlates to an INSERT SQL statement in the Data Adapter.

DataRowState.DeletedThe row has been deleted, but not yet actually removed from the dataset. Correlates to a DELETE SQL statement.

Page 935: Dotnet Stream

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

ADO.NET: DataRow StatesDataRowState.ModifiedChanges have been made to the row since the last AcceptChanges method was called. Correlates to an UPDATE SQL statement.

DataRowState.UnchangedThe row's fields/properties have not changed since the dataset was populated or since the last AcceptChanges/RejectChanges method was called.

DataRowState.DetachedThis row does not exist in any DataTable. It is entirely on its own, not yet having been added to a DataTable.

Page 936: Dotnet Stream

936©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.

Bindings: Format & Parse Events

Frequently data should be displayed differently than it is stored in the database. A currency would be stored as a 'decimal' but should be displayed with a dollar sign, commas, and the decimal placed fixed at two digits. For this, two events of the Binding class are exposed, Format & Parse.

Format is raised both when data is pulled from the data source and before it is shown, and also after the Parse event. The Parse event is called if data has changed in a control and before it is written to the data source (to remove formatting).

Page 937: Dotnet Stream

937©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.

Bindings: Format & Parse Events

The type of event that is called for both Format & Parse is ConvertEventHandler, which has its own special event arguments, ConvertEventArgs.

ConvertEventArgs exposes two properties, DesiredType and Value. Value contains the current data and should be set to the new data format. DesiredType contains the type of data wanted.

Page 938: Dotnet Stream

938©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.

Bindings: Format & Parse Events

private void InitTextBox(){ txtPrice.DataBindings[0].Format += new

ConvertEventHandler(txtPrice_Format); txtPrice.DataBindings[0].Parse += new

ConvertEventHandler(txtPrice_Parse);}private void txtPrice_Format(object sender, ConvertEventArgs e){ if (e.Value is decimal) e.Value = ((decimal) e.Value).ToString("c");}private void txtPrice_Parse(object sender, ConvertEventArgs e){ if (e.DesiredType == typeof(decimal)) { string price = e.Value.ToString(); price = price.Replace("$", "").Replace(",", ""); e.Value = decimal.Parse(price); }}

Page 939: Dotnet Stream

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

Data Binding - Demo

Page 940: Dotnet Stream

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

Data Binding - Demo

private void DataBinding_Load(object sender, System.EventArgs e){

string strConn = "Data Source=S2B21675;uid=sa;pwd=sa;Initial Catalog=pubs";

SqlConnection objConn = new SqlConnection(strConn);string str = "Select * from titles";

SqlCommand objCom = new SqlCommand(str,objConn);objCom.CommandType=CommandType.Text;

SqlDataReader dr = null;

Page 941: Dotnet Stream

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

Data Binding - Demo

try{if(objConn.State==ConnectionState.Closed){objConn.Open();dr=objCom.ExecuteReader();while(dr.Read()){comboBox1.Items.Add(dr["title_id"].ToString());}dr.Close();

}}catch(SqlException objs){throw objs;}

Page 942: Dotnet Stream

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

Data Binding - Demo

finally{

dr.Close();if(objConn.State==ConnectionState.Open){

objConn.Close();}

} }

private void cmdOK_Click(object sender, System.EventArgs e){

string strConn = "Data Source=p3c20014;uid=sa;pwd=sa;Initial Catalog=pubs";

SqlConnection objConn = new SqlConnection(strConn);string strQry = "Select * from titles where title_id='"+comboBox1.SelectedItem.ToString()+"'";

SqlDataAdapter objAdapt=new SqlDataAdapter(strQry,objConn);ds = new DataSet();

Page 943: Dotnet Stream

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

Data Binding - Demo

try{

objConn.Open();objAdapt.Fill(ds);

textBox1.DataBindings.Add("text",ds.Tables[0].DefaultView,“title");textBox2.DataBindings.Add("text",ds.Tables[0].DefaultView,“price");textBox3.DataBindings.Add("text",ds.Tables[0].DefaultView,"advance");textBox4.DataBindings.Add("text",ds.Tables[0].DefaultView,"type");

}catch(SqlException ex){

MessageBox.Show(ex.Message);}

Page 944: Dotnet Stream

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

Data Binding - Demo

finally{if(objConn.State==ConnectionState.Open){objConn.Close();}}}

private void cmdCancel_Click(object sender, System.EventArgs e){ds.Clear();textBox1.DataBindings.Clear();textBox2.DataBindings.Clear();textBox3.DataBindings.Clear();textBox4.DataBindings.Clear();

textBox1.Clear();textBox2.Clear();textBox3.Clear();textBox4.Clear();}

Page 945: Dotnet Stream

945©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.

Navigating Records - Demo

Page 946: Dotnet Stream

946©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.

App.config

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<appSettings>

<add key="MyConnection" value="server=p3c20014;uid=sa;pwd=sa;Initial Catalog=Pubs" />

</appSettings>

</configuration>

Page 947: Dotnet Stream

947©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.

Navigating Records - Demo

public DataSet ReturnDataSet(){

String strConn;strConn=ConfigurationSettings.AppSettings["MyConnection"];SqlConnection objConn = new SqlConnection(strConn);string strQry="select * from Publishers";SqlDataAdapter objAdapt = new SqlDataAdapter(strQry,objConn);

DataSet objDs=new DataSet();try{

objConn.Open();objAdapt.Fill(objDs);

}catch(SqlException ex){ throw ex; }finally{

objConn.Close();}return objDs; }

Page 948: Dotnet Stream

948©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.

Navigating Records - Demo

private void Navigation_Load(object sender, System.EventArgs e){

DataSet ds = ReturnDataSet();BindingContext bc=this.BindingContext;bm=bc[ds.Tables[0].DefaultView,""];bm.Position=0;

textBox1.DataBindings.Add("Text",ds.Tables[0].DefaultView,"pub_id");

textBox2.DataBindings.Add("Text",ds.Tables[0].DefaultView,"pub_name");

textBox3.DataBindings.Add("Text",ds.Tables[0].DefaultView,"city");

textBox4.DataBindings.Add("Text",ds.Tables[0].DefaultView,"state");

textBox5.DataBindings.Add("Text",ds.Tables[0].DefaultView,"country");

}

Page 949: Dotnet Stream

949©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.

Navigating Records - Demo

private void cmdFirst_Click(object sender, System.EventArgs e){

bm.Position = 0;}

private void cmdPrevious_Click(object sender, System.EventArgs e){

bm.Position -= 1;}

private void cmdNext_Click(object sender,System.EventArgs e){

bm.Position +=1;}

private void cmdLast_Click(object sender,System.EventArgs e){

bm.Position=bm.Count-1;}

Page 950: Dotnet Stream

950©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.

DataSet Serialization

The DataSet object in ADO.NET is an in-memory representation of disconnected, cached set of data and provides a consistent relational programming model regardless of the data source. When we require sending a DataSet class instance across process boundaries, the DataSet needs to be serialized.

Unfortunately, the DataSet class in the earlier version of ADO.NET used to serialize data as XML even if the BinarySerializer was specified. This resulted in slower serialization and an overhead of large sized serialized data. In ADO.NET 2.0 however, DataSet serialization has been improved to a large extent and you can now use the RemotingFormat property of the DataSet class to specify that the data is to be stored directly in binary format. Hence, the DataSet class ADO.NET 2.0, unlike ADO.NET 1.1, supports both XML and Binary Serialization formats. This is shown in the code example below.

Page 951: Dotnet Stream

951©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.

DataSet Serialization

BinaryFormatter binaryFormatter = new BinaryFormatter();

FileStream fileStream = new FileStream("c:\\emp.dat", FileMode.CreateNew);

DataSet empDataSet = GetEmployeeDataSet(); //This is a custom method that creates, populates and then returns a DataSet instance.

empDataSet.RemotingFormat = SerializationFormat.Binary;

binaryFormatter.Serialize(fileStream,empDataSet);

fileStream.Close();

Page 952: Dotnet Stream

952©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.

Bulk Copy Operation

Bulk copying of data from a data source to another data source is a new feature added to ADO.NET 2.0. Bulk copy classes provides the fastest way to transfer set of data from once source to the other. Each ADO.NET data provider provides bulk copy classes. For example, in SQL .NET data provider, the bulk copy operation is handled by SqlBulkCopy class, which can read a DataSet, DataTable, DataReader, or XML objects. Read more about Bulk Copy here.

Page 953: Dotnet Stream

953©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.

Bulk Copy Operation is faster

No per-row statement execution. When you do multiple inserts without bulk-copy, each insert is a statement in itself (regardless of whether it's batched together with other statements). With bulk-copy, we don't incur the cost of executing a statement for each row, the whole copy operation is a single thing.

No multiple network round-trips. Once the bulk-insert operation is setup, we send rows from the client to the server continously, without going back-and-forth over the wire.

Server storage engine also can greatly optimize how rows are inserted when performing a bulk-copy operation. How much can be optimized depends a lot on the recovery model the tarder database is set to; in "simple" and "bulk logged" the overhead of logging is greatly reduced during bulk-copy operations, helping a lot with performance.

Page 954: Dotnet Stream

954©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.

Bulk Copy Operation - Demo

string strConnection="Server=p3c20014;user id=sa;pwd=sa;Initial Catalog=Roy";SqlConnection source = new SqlConnection(connectionString);SqlConnection destination = new SqlConnection(connectionString);SqlCommand cmd = new SqlCommand("DELETE FROM BulkDataTable",destination);

source.Open();destination.Open();cmd.ExecuteNonQuery();

cmd = new SqlCommand("SELECT * FROM Products", source);

SqlDataReader reader = cmd.ExecuteReader();

Page 955: Dotnet Stream

955©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.

Bulk Copy Operation - Demo

SqlBulkCopy bulkData = new SqlBulkCopy(destination);

bulkData.DestinationTableName = "BulkDataTable";

bulkData.WriteToServer(reader);

bulkData.Close();destination.Close();source.Close();

Page 956: Dotnet Stream

956©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.

Batch Update

Batch update can provide a huge improvement in the performance by making just one round trip to the server for multiple batch updates, instead of several trips if the database server supports the batch update feature. The UpdateBatchSize property provides the number of rows to be updated in a batch. This value can be set up to the limit of decimal.

Page 957: Dotnet Stream

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

Data Paging

Data Paging is a very powerful feature in ADO.NET. It can be recollected that in the earlier version of ADO.NET we needed to make use of stored procedures for incorporating Data Paging functionality in our applications. Now, with ADO.NET 2.0, it is much simplified with the introduction of the ExecutePageReader method in the SqlDataReader class.

Now command object has a new execute method called ExecutePageReader. This method takes three parameters - CommandBehavior, startIndex, and pageSize. So if you want to get rows from 101 - 200, you can simply call this method with start index as 101 and page size as 100.

Page 958: Dotnet Stream

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

Data Paging

SqlConnection sqlConnection = new SqlConnection(connectionString);

sqlConnection.Open();

SqlCommand sqlCommand = new SqlCommand("Select * from Employee", sqlConnection);

SqlDataReader sqlDataReader = sqlCommand.ExecutePageReader(CommandBehavior.CloseConnection, 1, 25);

Page 959: Dotnet Stream

959©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.

DataTable's Load and Save Methods

ADO.NET 2.0 allows loading a DataReader object into a DataSet or a DataTable and vice versa. Both the DataSet and the DataTable classes in ADO.NET 2.0 contain the Load method that can be used to load a DataReader instance into a DataSet or a DataTable.

You can also load a DataReader object into a DataTable by using the Load method.

Page 960: Dotnet Stream

960©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.

DataTable's Load and Save Methods

SqlConnection sqlConnection = new SqlConnection(connectionString);

sqlConnection.Open();

SqlCommand sqlCommand = new SqlCommand("Select * from Employee", sqlConnection);

SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(CommandBehavior.CloseConnection);

DataTable dataTable = new DataTable("Employee");

dataTable.Load(sqlDataReader);

Page 961: Dotnet Stream

961©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.

DbProvidersFactories Class

This class provides a list of available data providers on a machine. You can use this class and its members to find out the best suited data provider for your database when writing a database independent applications.

Customized Data ProviderBy providing the factory classes now ADO.NET extends its support to custom data provider. Now you don't have to write a data provider dependent code. You use the base classes of data provider and let the connection string does the trick for you.

Page 962: Dotnet Stream

962©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.

DbProvidersFactories Class

This class is named DbProviderFactories and also resides in the System.Data.Common namespace. Since it is static, you don’t need to create an instance of the class in order to access it

Page 963: Dotnet Stream

963©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.

DbProvidersFactories Class

The purpose of an abstract factory is to provide an interface for creating families of related objects, without specifying their concrete classes. It is a creational pattern. When we write code to use the interface exposed by an abstract factory, we decouple our code from the specific factory or factories that create the objects we wish to consume. This allows us to define multiple factories that produce different objects meant for different situations.

GetFactory Function:

Name Description

DbProviderFactories.GetFactory (DataRow)

Returns an instance of a DbProviderFactory.

DbProviderFactories.GetFactory (String)

Returns an instance of a DbProviderFactory.

Page 964: Dotnet Stream

964©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.

DbProvidersFactories - Demo

Private cmdGetOleDB_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) { Data.Common.DbProviderFactory dbFactory; 

dbFactory = System.Data.Common.DbProviderFactories.GetFactory("System.Data.OleDb")

 DemonstrateFactory(dbFactory)

 }

Page 965: Dotnet Stream

965©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.

DbProvidersFactories - Demo

Private DemonstrateFactory(FactorySystem.Data.Common.DbProviderFactory Factory)

{Data.Common.DbConnection Connection;Data.Common.DbDataAdapter DA;Data.Common.DbCommand Command;Data.Common.DbParameter Parm;

Connection = Factory.CreateConnectionDA = Factory.CreateDataAdapterCommand = Factory.CreateCommandParm = Factory.CreateParameter

String str;str = Connection.GetType.ToString,str = str & DA.GetType.ToString,str = str & Command.GetType.ToString,str = str & Parm.GetType.ToString,MsgBox.Show(str); }

Page 966: Dotnet Stream

966©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.

Managed Provider

Provider Model ADO.NET v1.1 was based on interfaces

Not enough for provider-agnostic codeHard to evolve

ADO.NET v2.0 introduces a common APIAbstract base classes instead of interfaces

Better versioning storyProvider factories enabled at the API level

SQL syntax is still back-end specific

Page 967: Dotnet Stream

967©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.

Managed Provider

IDb* interfaces (e.g. IDbConnection)IDb* interfaces (e.g. IDbConnection)

SqlClient OleDb Odbc OracleClient

3rdParty

3rdParty

Provider-independent appsCode to this layer

Provider-specific appsCode to this layer

Db* abstract base classes (e.g. DbConnection)Db* abstract base classes (e.g. DbConnection)

Db*Base implementation classesDb*Base implementation classes

Page 968: Dotnet Stream

968©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.

Managed Provider

Provider FactoriesCan enumerate Managed ProvidersCan create a DbProviderFactory from Name

Factory to create common objects

Provider FactoriesCan enumerate Managed ProvidersCan create a DbProviderFactory from Name

Factory to create common objects

DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");

DbConnection conn = factory.CreateConnection();DbCommand cmd = factory.CreateCommand();DbDataReader rdr = cmd.ExecuteReader();DbDataAdapter da = factory.CreateDataAdapter();DataSet theSet = new DataSet();da.Fill(theSet);

Page 969: Dotnet Stream

969©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.

Asynchronous Execution

Asynchronous ExecutionAdded BeginXXX, EndXXX to most Executions

BeginExecuteNonQuery, EndExecuteNonQueryBeginExecuteReader, EndExecuteReader

Only supported on SqlClient so farMust add “Asynchronous Processing=true”

Asynchronous ExecutionAdded BeginXXX, EndXXX to most Executions

BeginExecuteNonQuery, EndExecuteNonQueryBeginExecuteReader, EndExecuteReader

Only supported on SqlClient so farMust add “Asynchronous Processing=true”

conn = new SqlConnection( "Server=.;database=...;Asynchronous Processing=true");cmd = conn.CreateCommand();// ...conn.Open();cmd.BeginExecuteReader(new AsyncCallback(SomeMethod), this);

Page 970: Dotnet Stream

970©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.

Using Stored Procedures

A stored procedures is a pre-defined, reusable routine that is stored in a database.  SQL Server compiles stored procedures, which makes them more efficient to use.  Therefore, rather than dynamically building queries in your code, you can take advantage of the reuse and performance benefits of stored procedures. 

Page 971: Dotnet Stream

971©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.

Using Stored Procedures

SqlCommand type can be used to execute stored procedures. 

There are two tasks require to make this happen: let the SqlCommand object know which stored procedure to execute and tell the SqlCommand object that it is executing a stored procedure.  These two steps are shown below:

SqlCommand cmd = new SqlCommand(“myStoredProcedure", conn);

procedure cmd.CommandType = CommandType.StoredProcedure;

Page 972: Dotnet Stream

972©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.

Sending Parameters to Stored Procedures

Using parameters for stored procedures is the same as using parameters for query string commands. 

SqlCommand cmd = new SqlCommand("CustOrderHist", conn);

cmd.CommandType = CommandType.StoredProcedure;cmd.Parameters.Add(new SqlParameter("@CustomerID", custId));

Page 973: Dotnet Stream

973©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.

Stored Procedures - Demo

using System;using System.Data;

using System.Data.SqlClient;

class StoredProcDemo

{

static void Main()

{

StoredProcDemo spd = new StoredProcDemo();

spd.RunStoredProc();

spd.RunStoredProcParams();

}

public void RunStoredProc()

{

SqlConnection conn = null;

SqlDataReader rdr = null;

Page 974: Dotnet Stream

974©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.

Stored Procedures - Demo

Console.WriteLine("\nTop 10 Most Expensive Products:\n");try{conn = new SqlConnection("Server=p3c20014;DataBase=Northwind;UserId=sa;pwd=sa");conn.Open();SqlCommand cmd = new SqlCommand("myStoredProc", conn);cmd.CommandType = CommandType.StoredProcedure;rdr = cmd.ExecuteReader();while (rdr.Read()){Console.WriteLine("Product: {0,-25} Price: ${1,6:####.00}",rdr["TenMostExpensiveProducts"],rdr["UnitPrice"] );}

}

Page 975: Dotnet Stream

975©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.

Stored Procedures - Demo

finally

{

if (conn != null)

{

conn.Close();

}

if (rdr != null)

{

rdr.Close();

} }

}

Page 976: Dotnet Stream

976©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.

CommandBuilder object

Used to generate single-table insert/update/delete commands for data adapter

Retrieves metadata from select command about table structure

Select command must have at least one primary key or unique column Call .Update() method of DataAdapter

Page 977: Dotnet Stream

977©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.

CommandBuilder Code

conn = new SqlConnection("datasource=p3c20014;initial catalog=northwind;UserId =sa; pwd =;");

String SqlString = "Select * from customers" ;

SqlCommand cmd = new SqlCommand(SqlString, cnn) DataSet ds = new DataSet();

SqlDataAdapter sqlda = New SqlDataAdapter(cmd);

sqlda.Fill(ds);

ds.Tables("Customers").Rows(0)("City") = "Chevy Chase“;

SqlCommandBuilder cb = New SqlCommandBuilder(sqlda);

sqlda.Update(ds, "Customers")

If (cnn.State = ConnectionState.Open)

cnn.Close();

Page 978: Dotnet Stream

978©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.

Concurrency Options

Pessimistic concurrency – Data is unavailable to users from the time the record is fetched until it is updated in the database.• Not supported in ADO.NET, can simulate with

transactions

Optimistic concurrency – Data is not locked, attempting to update a record that has already been changed results in a concurrency exception (DBConcurrencyException).

"Last in wins" – Overwrite the last changes

Page 979: Dotnet Stream

979©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.

Optimistic Concurrency

Use date time stamp to check for changeUpdate table set col1 = @newvalcol1, col2=@newvalcol2 where tableid = @tableid and datetimestamp=@datetimestamp

Match old columns exactlyUpdate table set col1 = @newvalcol1, col2=@newvalcol2 where tableid = @tableid and col1=@oldcol1 and col2=@oldcol2

Can catch concurrency exceptions

Apply your business logicShow original, current, and proposed records

Page 980: Dotnet Stream

980©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.

Retrieving result set & iterating

Use a SqlDataAdapter object to generate a DataSet or DataTable

Use a SqlDataReader to provide a read-only, forward-only data stream

Use an XmlReader to provide a read-only, forward-only data stream of XML data

Best Practices (Designing DAL)

Page 981: Dotnet Stream

981©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.

Retrieving a single item from a specified row

Use the CommandBehavior.SingleRow enumerated value whencalling the ExecuteReader method of the SqlCommand object

In case of parameters and outputs ensure that DataReader is

closed

Use ExecuteScalar for single values.

Best Practices (Designing DAL)

Page 982: Dotnet Stream

982©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.

Use DataSet when:

You require a disconnected memory-resident cache of data, so that

you can pass it to another component or tier within your application.

You require a disconnected memory-resident cache of data, so that

you can pass it to another component or tier within your application.

You are working with data retrieved from multiple data sources,

such as multiple databases, tables, or files.

You want to update some or all of the retrieved rows and use the

batch update facilities of the SqlDataAdapter.

You want to perform data binding against a control that requires a

data source that supports IList.

Data Reader vs. DataSet vs. XMLReader

Page 983: Dotnet Stream

983©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.

Use DataReader when:

Dealing with large volumes of data—too much to

maintain in a single cache.

Reduce the memory footprint of your application.

Want to avoid the object creation overhead

associated with the DataSet

Want to perform data binding with a control that

supports a data source that implements

IEnumerable

Wish to streamline and optimize your data access

Reading rows containing binary large object

(BLOB) columns

Data Reader vs. DataSet vs. XMLReader

Page 984: Dotnet Stream

984©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.

Use XMLReader when

processing the retrieved data as XML, without incurring performance overhead of creating a DataSet

Data Reader vs. DataSet vs. XMLReader

Page 985: Dotnet Stream

985©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.

Stored Procedures are:Pre-compiled code!Tightly Integrated with back end (Database) ServerLooks neater with parametersEven better with CLR Integration in SQL Server 2005

SQL Text is:(could be) ANSI compatible Interpreted at runtimeLoosely coupled with the backend database

server

Stored Procedures vs. SQL Text

Page 986: Dotnet Stream

986©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.

Best Practices (Passing Data Through Tiers)

Data Access Logic ComponentsCRUD Operations

Business EntitiesAbstract Data TypesDALC’s messaging formatCould be:

XML (XML String or XML DOM)DataSetTyped DataSetBusiness Entity (with/without CRUD Ops)

Page 987: Dotnet Stream

987©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.

Implementing Business EntitiesDon’t access database directlyCan be passed as an IO/Message to the

business processCan travel on the wire (Serializable)Do not initiate any transactionsCan be represented as:

XMLDataSet (typed/un-typed)Custom Object (with / without CRUD)

Page 988: Dotnet Stream

988©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.

Insert/Update/Delete - Demo

Page 989: Dotnet Stream

989©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.

Insert Record

private void cmdInsert_Click(object sender, System.EventArgs e){

string strConn = "Data Source=p3c20014;uid=sa;pwd=sa;Initial Catalog=Roy";SqlConnection objConn = new SqlConnection(strConn);

string strCmd="prcInsertEmp";SqlCommand objCmd=new SqlCommand(strCmd,objConn);objCmd.CommandType=CommandType.StoredProcedure;int resval=0;try{

objConn.Open();SqlCommandBuilder.DeriveParameters(objCmd);

objCmd.Parameters[1].Value=textBox1.Text;objCmd.Parameters[2].Value=textBox2.Text;objCmd.Parameters[3].Value=textBox3.Text;objCmd.Parameters[4].Value=textBox4.Text;resval=objCmd.ExecuteNonQuery();

}

Page 990: Dotnet Stream

990©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.

Insert Record

catch(SqlException sq){

MessageBox.Show(sq.Message);}finally{

if(objConn.State==ConnectionState.Open){

objConn.Close();}

}if(resval == 0){

MessageBox.Show("Data Insertion Failed");}else{

MessageBox.Show("Data Added" + resval);}

}

Page 991: Dotnet Stream

991©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.

Update Record

private void cmdUpdate_Click(object sender, System.EventArgs e){

string strConn = "Data Source=p3c20014;uid=sa;pwd=sa;Initial Catalog=Roy";SqlConnection objConn = new SqlConnection(strConn);string cmd = " Update EmployeeDetails set EmpName = '"+textBox2.Text+"',Department = '"+textBox3.Text +"' where EmpID = '"+ textBox1.Text+"'";SqlDataAdapter objad = new SqlDataAdapter(cmd,objConn);

int resval=0;try{objConn.Open();

resval=objad.SelectCommand.ExecuteNonQuery();

}

Page 992: Dotnet Stream

992©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.

Update Record

catch(SqlException sq){

MessageBox.Show(sq.Message);}finally{

if(objConn.State==ConnectionState.Open){

objConn.Close();}

}if(resval == 0){

MessageBox.Show("Data updation Failed");}else{

MessageBox.Show("Data updated" + resval);}

}

Page 993: Dotnet Stream

993©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.

Delete Record

private void cmdDelete_Click(object sender, System.EventArgs e){

string strConn = "Data Source=S2B20793;uid=sa;pwd=sa;Initial Catalog=Roy";SqlConnection objConn = new SqlConnection(strConn);string strQry="prcDelEmp";

SqlCommand objcmd = new SqlCommand(strQry,objConn);objcmd.CommandType = CommandType.StoredProcedure;objcmd.Parameters.Add(new SqlParameter("@EmpId",SqlDbType.Char,12,"EmpID")).Value = textBox1.Text;

int resval=0;try{

objConn.Open();resval=objcmd.ExecuteNonQuery();

}catch(SqlException sq){

MessageBox.Show(sq.Message);}

Page 994: Dotnet Stream

994©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.

Delete Record

finally{

if(objConn.State==ConnectionState.Open){

objConn.Close();}

}if(resval == 0){

MessageBox.Show("Data Deletion Failed");}else{

MessageBox.Show("Data Deleted" + resval);}

}

Page 995: Dotnet Stream

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.

Thank You !Thank You !

Page 996: Dotnet Stream

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

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

Microsoft Microsoft Application Application BlocksBlocksfor .NETfor .NET

COE – Current Technologies

Page 997: Dotnet Stream

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

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

Data Access Application Data Access Application BlockBlock

Page 998: Dotnet Stream

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

Topics of Discussion

About Data Access Application BlockWhy Data Application Blocks?Advantages of using Data Access Application Block.Structure of Data Application Block.Referencing a Data Access block in an Application.Developing Applications with Data Access Block.Retrieving Multiple Rows using SqlDataReader.Methods of SqlHelperParameterCache.

Page 999: Dotnet Stream

999©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.

About Data Application Block

The Microsoft Data Access Application Block for .NET consists of

• A single .NET-based assembly.• Contains all of the functionality necessary to

perform the most common data access tasks against a Microsoft SQL Server 2000 database.

Page 1000: Dotnet Stream

1000©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.

Why Data Application Block: 

The Data Access Application Block was designed to • Encapsulate best practice for data access.Applications often need to execute commands such as

Transact-SQL statements or stored procedures in a SQL Server database. These commands can be used to perform

• Database updates • Retrieve single values or rows• To retrieve XML data.

While the Microsoft ActiveX Data Objects (ADO) .NET class library in the .NET Framework provides

• A high level of abstraction • A great deal of functionality.

Page 1001: Dotnet Stream

1001©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.

Why Data Application Block: 

 

Developers find the following problems while working with data access.• Confused with the multitude of implementation choices available

when they build data access solutions. • Developers often find themselves

Duplicating similar code to open and close connections Assign parameters to commands to perform other data

access.

The Data Access Application Block was designed to address these problems by providing encapsulated logic to perform the most common data access tasks with a minimal requirement for custom code.

Page 1002: Dotnet Stream

1002©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.

Advantages of using Data Access Application

Block The following Data operations can be achieved using Data

Access Application Blocks.• Call stored procedures or SQL text commands. • Specify parameter details.• Return SqlDataReader, DataSet, XmlReader objects, or

single values. • Use strongly typed table and field names. • Support parameter caching, where required. • Allow additional tables to be added by passing in pre-

existing datasets.• Update a dataset with user-specified update commands. • Create SqlCommand objects. • Allow strongly typed data rows to be passed in place of

parameters.

Page 1003: Dotnet Stream

1003©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.

Structure of Data Access Application Block:

There are two major categories of data access logic that needed to be encapsulated by the Data Access Application Block

• The actual execution of database commands. • The management and caching of parameters.

To meet these needs, the designers of the Data Access Application Block made the decision to create two classes

• SqlHelper class, which provides methods for executing database commands

• SqlHelperParameterCache class, which provides parameter management functionality.

Page 1004: Dotnet Stream

1004©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.

Structure of Data Access Application Block

In order to minimize the code required to use the Data Access Application Block, the design decision was taken to declare all public functions in each class as static methods, allowing them to be called without instantiating an object instance of the class.

 Since client applications do not need to instantiate the Data Access Application Block classes, both the SqlHelper and SqlHelperParameterCache were designed to be non-inheritable, and to implement private constructors.

Page 1005: Dotnet Stream

1005©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.

Referencing a Data Application Block in an Application

When you create a data access client that uses the Data Access Application Block, you should perform the following steps:

• Set a reference to the Data Access Application Block assembly Microsoft.ApplicationBlocks.Data.dll. • (C:\Program Files\Microsoft Application Blocks for .NET\Data

Access v2\Code\CS\Microsoft.ApplicationBlocks.Data\bin\Debug).

• Add a using statement at the top of your data access client source file(s) to reference the Microsoft.ApplicationBlocks.Data namespace. All Data Access Application Block types are located within this namespace.

• Add a using statement to reference the System.Data and System.Data.SqlClient namespaces. The SqlHelper methods use various types from these namespaces as input and return parameters.

• Optionally, add a using statement to reference the System.Xml namespace. This is required only if you use the SqlHelper ExecuteXmlReader methods.

Page 1006: Dotnet Stream

1006©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.

Developing Applications with Data Access block.The following methods are available with SQLHelper class each of which is

overloaded to support a variety of functionalities.• ExecuteNonQuery (9 overloads).

• Executes a command that does not return rows.• public static int ExecuteNonQuery(method_parameters). • Overloaded Members

ExecuteNonQuery(string connectionString, CommandType commandType,string commandText).

ExecuteNonQuery(string connectionString, CommandType commandType,string commandText, params SqlParameter[] commandParameters).

ExecuteNonQuery(string connectionString, string spName, params object[] parameterValues)

ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText)

ExecuteNonQuery(SqlConnection connection, CommandType commandType,string commandText, params SqlParameter[] commandParameters)

ExecuteNonQuery(SqlConnection connection, string spName, params object[] parameterValues)

ExecuteNonQuery(SqlTransaction transaction, CommandType commandType,string commandText)

ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)

ExecuteNonQuery(SqlTransaction transaction, string spName, params object[] parameterValues)

Page 1007: Dotnet Stream

1007©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.

Developing Applications with Data Access block.

• ExecuteDataset (9 overloads)• Executes a command that returns rows as a DataSet.• public static DataSet ExecuteDataset(method_parameters)• Overloaded members

ExecuteDataset(string connectionString, CommandType commandType, string commandText). ExecuteDataset(string connectionString, CommandType commandType,string commandText, params

SqlParameter[] commandParameters). ExecuteDataset(string connectionString, string spName, params object[] parameterValues). ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText). ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params

SqlParameter[] commandParameters). ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params

SqlParameter[] commandParameters). ExecuteDataset(SqlConnection connection, string spName, params object[] parameterValues) ExecuteDataset(SqlTransaction transaction, CommandType commandType,string commandText). ExecuteDataset(SqlTransaction transaction, CommandType commandType,string commandText, params

SqlParameter[] commandParameters) ExecuteDataset(SqlTransaction transaction,string spName, params object[] parameterValues)

Page 1008: Dotnet Stream

1008©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.

Developing Application with Data Access Block

• ExecuteScalar (9 overloads).• Executes a command that returns a single value as an object.• public static object ExecuteScalar (method_parameters).• Overloaded members

ExecuteScalar(string connectionString, CommandType commandType, string commandText) ExecuteScalar(string connectionString,CommandType commandType, string commandText,params

SqlParameter[] commandParameters) ExecuteScalar(string connectionString, string spName, params object[] parameterValues) ExecuteScalar(SqlConnection connection, CommandType commandType,string commandText) ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText, params

SqlParameter[] commandParameters) ExecuteScalar(SqlConnection connection, string spName, params object[] parameterValues). ExecuteScalar(SqlTransaction transaction,CommandType commandType, string commandText) ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText,params

SqlParameter[] commandParameters) ExecuteScalar(SqlTransaction transaction,string spName, params object[] parameterValues)

 

Page 1009: Dotnet Stream

1009©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.

Developing Application with Data Access Block

• ExecuteXmlReader ( 6 overloads).• Executes a command that returns XML in an XmlReader.• public static XmlReader ExecuteXmlReader

(method_parameters) • Overloaded members

ExecuteXmlReader(SqlConnection connection, CommandType commandType,string commandText)

ExecuteXmlReader(SqlConnection connection, CommandType commandType,string commandText, params SqlParameter[] commandParameters)

ExecuteXmlReader(SqlConnection connection, string spName,params object[] parameterValues)

ExecuteXmlReader(SqlTransaction transaction, CommandType commandType, string commandText)

ExecuteXmlReader(SqlTransaction transaction, CommandType commandType, string commandText,params SqlParameter[] commandParameters)

ExecuteXmlReader(SqlTransaction transaction,string spName, params object[] parameterValues)

Page 1010: Dotnet Stream

1010©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.

Developing Application with Data Access Block

• FillDataSet ( 9 overloads)• Executes a command that populates a DataSet that is provided as a

parameter.• public static void FillDataset(method_parameters).• Overloaded members.

FillDataset(string connectionString, CommandType commandType,string commandText, DataSet dataset, string[] tableNames)

FillDataset(string connectionString, CommandType commandType,string commandText, DataSet dataSet, string[] tableNames,params SqlParameter[] commandParameters)

FillDataset(string connectionString, string spName, DataSet dataSet,string[] tableNames, params object[] parameterValues)

FillDataset(SqlConnection connection, CommandType commandType,string commandText, DataSet dataSet, string[] tableNames)

FillDataset(SqlConnection connection, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames, params SqlParameter[] commandParameters)

FillDataset(SqlConnection connection, string spName, DataSet dataSet, string[] tableNames, params object[] parameterValues)

FillDataset(SqlTransaction transaction, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames)

FillDataset(SqlTransaction transaction, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames, params SqlParameter[] commandParameters)

FillDataset(SqlTransaction transaction,string spName, DataSet dataSet, string[] tableNames,params object[] parameterValues)

Page 1011: Dotnet Stream

1011©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.

Developing Applications with Data Access block

• ExecuteNonQueryTypedParams.• Executes a command that does not return rows using

a DataRow’s column values as parameters.

• ExecuteDatasetTypedParams.• Executes a command that returns rows as a DataSet

using a DataRow’s column values as parameters.

• ExecuteReaderTypedParams.• Executes a command that returns rows as a

SqlDataReader using a DataRow’s column values as parameters.

• CreateCommand• Creates a command object given a stored procedure

and parameters.

• UpdateDataset• Updates a dataset using an existing connection and

user-specified update commands.

Page 1012: Dotnet Stream

1012©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.

Retrieving multiple rows using a SqlDataReader

The following example assumes that this stored procedure has been created in the database to which the connection string in the code relates. 

CREATE PROCEDURE getProductsByCategory@CategoryID INTEGERASSELECT ProductID, ProductName, QuantityPerUnit, UnitPriceFROM ProductsWHERE CategoryID = @CategoryID

The following overload of the ExecuteReader method can be used to call a stored procedure with command parameters.

public static SqlDataReader ExecuteReader(string connectionString,

CommandType commandType, string commandText, params SqlParameter[] commandParameters);

Page 1013: Dotnet Stream

1013©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.

Retrieving multiple rows using a SqlDataReader

The following code fragment illustrates how the SqlHelper class can be used to retrieve a SqlDataReader obect. After it's retrieved, the SqlDataReader could be bound to a control such as a DataList.

private SqlDataReader RetrieveDataReader(string connectionString, int categoryID)

{ // Call ExecuteReader static method of SqlHelper class

that returns a SqlDataReader // We pass in database connection string, stored

procedure name and value of categoryID parameter SqlDataReader reader =

SqlHelper.ExecuteReader(connectionString, "getProductsByCategory", categoryID);

return reader;} Similarly by the use of other overloaded methods of the

SqlHelperClass the Data Access operations can be greatly simplified.

Page 1014: Dotnet Stream

1014©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.

Methods of SqlHelperParameterCache

• CacheParameterSet• Caches a SqlParameter array for reuse.

• GetCachedParameterSet• Retrieves a cached SqlParameter array.

• GetSpParameterSet• Retrieves the required parameter array for a specified

stored procedure. 

Page 1015: Dotnet Stream

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 Management Exception Management Application BlockApplication Block

Page 1016: Dotnet Stream

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

Topics of Discussion

• About Exception Management Application Block.• Advantages of using Exception Management

Application block.• Design of Exception Management Application block.• Main Elements of Exception Management Application

block.• Classes and Interfaces in the Exception Management

Application block.• BaseApplicationException class.• BaseApplicationException class constructors.• ExceptionManager Component.• Application Configuration files.• ExceptionManagerSectionHandler Class.

Page 1017: Dotnet Stream

1017©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

• Publisher interface • Publisher class.• Developing Applications using Exception

Management Application Block.• Creating Custom ApplicationExceptions.• Publishing an Exception.

Page 1018: Dotnet Stream

1018©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 Management Application Block

• Provides a simple yet extensible framework for logging exception information to the default location of the Windows Application Event Log.

• Custom components can be created to • Log exception details to other data sources• To notify operators, without affecting your application code.

Page 1019: Dotnet Stream

1019©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.

Advantages of using Exception Management Application block

Specifically, the Exception Management Application Block will help you:

• Manage Exceptions in an efficient and consistent manner.

• Isolate exception management from business logic code.

• Handle and log exceptions with minimum amount of custom code e.g. Catch (Exception ex) { ExceptionManager.Publish(ex) }

Page 1020: Dotnet Stream

1020©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.

Design of Exception Management Application block

The flow of logic when an Exception Management block is used to publish an exception as follows:

• The application throws an Exception which is derived from the BaseApplicationException class provided in the Exception Management Application block.

• The Application calls the Publish method of the ExceptionManager class.

• The ExceptionManager class uses the ExceptionManagerSectionHandler for retrieving the application’s exception management settings.

• The exception management settings are read from the configuration file to determine how the exception should be published.

• There can be 2 possibilities• If no settings are found the exception is published in the Windows

event log using the default publisher class.• If the exception settings are found the default/custom publisher

classes are used to publish the exception.

Page 1021: Dotnet Stream

1021©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.

Main Elements of Exception Management Application Block

Page 1022: Dotnet Stream

1022©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.

Classes and interfaces in the Exception Management Application block.

The Exception Management Application block consists of the following classes and interfaces.

• BaseApplicationException: Base exception class.Custom exceptions can be derived from this class.

• ExceptionManagementSectionHandler: Used to retrieve the exception management settings from the application’s configuration file which can be used to fine tune the runtime behaviour.

• ExceptionManager: Primary class through which the application interacts to publish and log the exception.

• ExceptionManagerInstaller:This class is used when you install the Exception Management Application Block to create the two Event sources used by the default publisher and by custom publishers when writing to the Microsoft Windows Event Log.

• DefaultPublisher: provides logging functionality and writes information to the Event Log.

• IExceptionPublisher and IExceptionXmlPublisher: These interfaces are implemented by the publisher classes.

Page 1023: Dotnet Stream

1023©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.

BaseApplicationException Class

The primary features of this class are:• The class provides a base exception class from

which all application exception classes can derive.

• The class contains information that is valuable to all application exceptions.

• The base class should be lightweight and should include only information that is valuable to all application exception classes.

• The base class is serializable to ensure that it can be remoted across .NET remoting boundaries.

Page 1024: Dotnet Stream

1024©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.

BaseApplicationException Class Constructors

The BaseApplicationException class derives from the System.ApplicationException and implements the following 3 public constructors.

• Constructor taking no parameters.public BaseApplicationException() : base()

{ // Initialization code}• Constructor allowing the Message property to be set.

public BaseApplicationException(string message) : base(message){ // Initialization code}• Constructor allowing the Message and InnerException property to be set.

public BaseApplicationException(string message,Exception inner) : base(message, inner){ // Initialization code}

The provision of these constructors allows exception classes derived from BaseApplicationException to be instantiated in three different ways.

Page 1025: Dotnet Stream

1025©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.

ExceptionManager ComponentThe primary goals of the ExceptionManager Component

are:• The component should require a minimal amount of code

by the developer to integrate into an application. • Behavior should be based on configuration settings that

can be modified allowing changes to be made without recoding, recompiling, and in the case of ASP.NET applications, without restarting the application.

• Internal exceptions thrown by custom publishers should be caught and logged.

• XML serialization of the exception chain is an issue. The XmlSerializer object only serializes read/write values, which limits its use for exception objects. The exception manager component provides its own XmlSerializer implementation.

Page 1026: Dotnet Stream

1026©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.

Application Configuration Files

Contains settings that can be read by an Application at run time.

Settings in the file indicate • Whether or not exceptions should be logged or

notification sent.• Name of the publisher class that must be used to publish

the exception.• Whether or not the publisher should receive the

exception information as an Exception object or XML document.

• Specific exceptions that should be included or excluded when publishing.

Page 1027: Dotnet Stream

1027©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.

ExceptionManagerSectionHandler Class

The ExceptionManagerSectionHandler class is used to read the exception management configuration settings from the application’s configuration file.

The ExceptionManager Class:• Declared as Sealed class with a private constructor to

prevent inheritance.• Exposes a static method Publish that is called from the

application.• Publish method calls the publishes specified in the

configuration file.Internal Exception Handling:• The ExceptionManagement assembly includes an

exception class CustomPublisherException derived from BaseApplicationException.

• Used to raise internal exceptions if exception is thrown by custom publisher.

Page 1028: Dotnet Stream

1028©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.

Publisher interfaceThe publisher assembly consists of the following 2 interfaces:• IExceptionPublisher : Defines a single method called Publish

which accepts 3 parameters• System.Exception object-Representing the exception to

publish.• NameValueCollection object containing the AdditionalInfo

collection.• NameValueCollection object representing the settings in the

configuration file. • IExceptionXmlPublisher: It also defines a single method called

Publish which takes the following 2 parameters.• XmlDocument object representing the Exception information.• NameValueCollection object representing the settings in the

configuration file. public interface IExceptionPublisher{ void Publish( Exception exception, NameValueCollection additionalInfo, NameValueCollection configSettings);}public interface IExceptionXmlPublisher{ void Publish( XmlDocument exceptionInfo,NameValueCollection configSettings);}

Page 1029: Dotnet Stream

1029©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.

Publisher Class

There are 2 primary kinds of publisher solutions:• The DefaultPublisher class.

• Provides a default publisher that implements the IExceptionPublisher interface.

• Publishes the entire exception chain and any other information in the Event Log.

• Custom Publisher class. • Used for creating publisher classes by implementing

IExceptionPublisher or IExceptionXmlPublisher interface.

Page 1030: Dotnet Stream

1030©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.

Developing Applications using Exception Management Application Block

The Exception Management Application block is implemented as two dll’s named:

• Microsoft.ApplicationBlocks.ExceptionManagement.dll • This is the main exception management assembly. • It contains the ExceptionManager class, which is used

to publish exceptions. • This assembly is referred to as the

ExceptionManagement assembly.• Microsoft.ApplicationBlocks.ExceptionManagement.Inter

faces.dll • This assembly contains the interface definitions • Definitions are used by the default publisher in the

ExceptionManagement assembly and by your own custom publishers.

• This assembly is referred to as the Interfaces assembly.

Page 1031: Dotnet Stream

1031©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.

Creating CustomApplication Exceptions

Our Custom Exception classes should derive from BaseApplicationException class. Deriving from this class ensures that our exception type supports the following:

• The computer name where the exception occurred.• The date and time of the exception.• The name of the application domain hosting the

application.• The name of the Thread and windows identities.

• Custom information specified in the configuration files.

Page 1032: Dotnet Stream

1032©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.

Creating CustomApplication Exceptions

using System;

using System.Runtime.Serialization;

using Mirosoft.ApplicationBlocks.ExceptionManagement;

[Serializable]

public class LogonException : BaseApplicationException

{

// Default constructor

public LogonException() : base()

{

}

// Constructor with exception message

public LogonException(string message) : base(message)

{

}

// Constructor with message and inner exception

public LogonException(string message, Exception inner): base(message,inner){ }

// Protected constructor to de-serialize data

protected LogonException(SerializationInfo info,StreamingContext context) : base(info,context) { }

}

Page 1033: Dotnet Stream

1033©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.

Publishing an Exceptionusing System;

using System.IO;

using System.Windows.Forms;

using Microsoft.ApplicationBlocks.ExceptionManagement;

private bool DoLogon(string userName, string password)

{ try {

using (FileStream fs = new FileStream( "Accounts.dat",

FileMode.Open, FileAccess.Read ))

{

return CheckUserDetails(fs, userName, password);

}

}

catch (FileNotFoundException ex )

{

throw new LogonException(

"Internal Logon Failure. User file not found", ex );

}

}

Page 1034: Dotnet Stream

1034©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.

Publishing an Exceptionprivate void btnLogon_Click(object sender, System.EventArgs e){ try { if ( DoLogon(txtUserName.Text, txtPassword.Text) == true ) { MessageBox.Show("Your Logon Was Successful"); } else { MessageBox.Show("Logon failed. Invalid user name or password"); } } catch( LogonException lex) { // publish exception using ExceptionManager ExceptionManager.Publish( lex ); MessageBox.Show(lex.Message); }}private bool CheckUserDetails( FileStream fs,string username,string password){ // access user file and check username and password return true; // Simulation}

Page 1035: Dotnet Stream

1035©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.

Quiz

• List the components of the ExceptionManagement Application block.

• How is it advantageous to use the Application blocks?

• Enumerate the process flow of Exception publishing using the ExceptionManagement Application block.

• Use the ExceptionManagement Application block for exception handling in your application.

Page 1036: Dotnet Stream

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.

Thank You !Thank You !

Page 1037: Dotnet Stream

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

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

Introduction to NUnit Introduction to NUnit

COE – Current Technologies

Page 1038: Dotnet Stream

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

Objective

• To Learn on how to use write NUnit test cases.

Page 1039: Dotnet Stream

1039©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

• Knowledge of .NET programming.

Page 1040: Dotnet Stream

1040©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.

H/w & S/w Required

• NUnit should be installed

Page 1041: Dotnet Stream

1041©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. NUnit• Introduction• What is Unit Test• Why do we need NUnit• Sample Test Case

Page 1042: Dotnet Stream

1042©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 Unit Test?

Unit Testing – This checks the correctness and completeness of a module, when treated in isolation

Basic unit in a .NET program is Class, which is tested for correctness and completeness in isolation

Page 1043: Dotnet Stream

1043©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 NUnit?

NUnit is an open source .NET testing framework used to write and run repeatable tests. NUnit features include:

• Assertions for testing expected results • Test fixtures for sharing common test data • Test suites for easily organizing and running

tests • Graphical and textual test runners • Uses an Attribute based programming model • With features like watching a file/assembly

change events and reloading it as soon as they are changed ,a developer can perform development and test cycles sides by side.

Page 1044: Dotnet Stream

1044©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.

Why is NUnit required ?

• Mistakes are Inevitable It doesn't matter how much time you put into design and how careful you are when programming

• Regression Testing ensures, that changes do not break the system

• NUnit – a savior for .NET Programmers, performs the regression testing

Page 1045: Dotnet Stream

1045©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.

Sample Code – To be testedConsider the following piece of code that needs to

be unit testednamespace bank{

public class Account{

private float balance;

public void Deposit(float amount){

balance+=amount;

}

  public void Withdraw(float amount){

balance-=amount;

}

public void TransferFunds(Account destination, float amount){

}

  public float Balance{

get{ return balance;}

}

}

}

Page 1046: Dotnet Stream

1046©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.

Writing test case

namespace bank{using NUnit.Framework;

 [TestFixture]public class AccountTest{ [Test] public void TransferFunds(){ Account source = new Account(); source.Deposit(200.00F); Account destination = new Account(); destination.Deposit(150.00F);

  source.TransferFunds(destination, 100.00F); Assertion.AssertEquals(250.00F,destination.Balance); Assertion.AssertEquals(100.00F, source.Balance);

}}

}

Page 1047: Dotnet Stream

1047©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.

Testing the test case

To create a test case,add the following references to the test case

• Reference of the NUnitTestClass containing the code to test.

• Reference of the nunit.Framework.dll from C:\Program Files\NUnit V2.1\bin (if nUnit is installed in C:\ ).

• Reference of the nunit.util.dll from C:\Program Files\NUnit V2.1\bin (if nUnit is installed in C:\ ).

• Import the namespaces in your test case Application as using NUnit.Framework;

Page 1048: Dotnet Stream

1048©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.

Adding reference• Create a new C# project in VS.Net• Add the NUnit reference – In the Solution Explorer right

click on the reference and click on add a reference

Page 1049: Dotnet Stream

1049©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.

Adding Reference

• Navigate to NunitV2 directory and go into the bin subdirectory

Page 1050: Dotnet Stream

1050©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.

Testing

• Add the test case• Compile the project• Start the Nunit- GUI

Page 1051: Dotnet Stream

1051©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.

Adding the test case to NUnit GUI• Go under File->Open and navigate to your projects

“bin” directory .• Select the exe or dll file of your compiled project and

click Open.

Page 1052: Dotnet Stream

1052©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.

Testing

Click on Run

Page 1053: Dotnet Stream

1053©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.

Examining the results

Green bar indicates the test has succeeded.

Page 1054: Dotnet Stream

1054©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.

Examining the results

If a red bar appears the test has failed.Make corrections in the code as per the suggestions and re-test your code.

Page 1055: Dotnet Stream

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.

Thank You !Thank You !

Page 1056: Dotnet Stream

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

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

FxCop 1.32FxCop 1.32

COE – Current Technologies

Page 1057: Dotnet Stream

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

FxCop - Introduction

FxCop is a code analysis tool that checks managed code assemblies for conformance to Microsoft .NET Framework design guidelines plus custom guidelines.

FxCop uses introspection, MSIL parsing, and call graph analysis to inspect assemblies for more than 200 defects in the following areas Library design, Localization, Naming conventions, Performance, Security.

Page 1058: Dotnet Stream

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

FxCop

FxCop includes both GUI and command line versions of the tool. FxCop provides XML based test reports. You can write custom rules based on your company standards and add-up in FxCop tool to test your assembly.

Why FxCop

To ensure that coding standards such as naming conventions, localization etc. To avoid bad coding and make use of best practices. Well-formatted test reports.

Page 1059: Dotnet Stream

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

FxCop - WorkFlow

Analyse the assembliesReview the reported messages and determine

the disposition for each: • Code defect - fix the source code. • Message is reporting an intentional variance from the rule -

exclude the message.

Exclude items as appropriate. Correct any code defects detected by FxCop. Rebuild your assemblies.

Page 1060: Dotnet Stream

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

FxCop - Analysis

To create a project and run an FxCop analysis

• Start FxCop from the Start menu, or double-click FxCop.exe in the

• installation directory.• From the Project menu, select Add Targets.• Browse to the assembly (.exe or .dll file) to

add, and click Open.• Run the analysis by clicking the Analyze

button on the toolbar.• The analysis report is displayed in the

messages pane.

Page 1061: Dotnet Stream

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

FxCop - Analysis

From the Project menu, select Add Targets.Browse to the assembly to add, and click Open.Click the Analyze button on the toolbar orFrom the Project menu, select Analyze.Press the F5 function key.

Page 1062: Dotnet Stream

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

FxCop - Analysis

• Select a rule library to display only messages generated by the rules in that library.• Select a specific rule to display only messages generated by that rule.• Select a target to display only messages for that target and its child nodes.

Filtering is an optional feature that allows you to see a subset of the messages present in a report. After performing an analysis, you can filter the displayed messages by clicking items in the configuration pane.

Page 1063: Dotnet Stream

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

FxCop - Analysis

The analysis report is saved to an XML file. The XML schema, FxCopReport.xsd, is located in the \Xml subdirectory installed by FxCop.

This directory also contains XSL style sheets that transform the analysis report XML into formatted reports.

Page 1064: Dotnet Stream

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

FxCop - CommandLine

Command-line options are used to specify the assemblies to be analyzed, the rules

used to analyze the assemblies, and the location of the output file.

To specify the assemblies and rules, use one of the following:The /project option, which uses a project saved from the FxCop application.The /file and /rule options, which directly specify the assemblies and rules, respectively.

To specify the location of the output file, use one of the following:The /out option, which saves the results of an analysis in an XML file.The /console option, which displays the results in a console window or, if integrated with Visual Studio, in Visual Studio's Output window.

The following are examples of a minimum command line:FxCopCmd /p:SomeProject.FxCop /cFxCopCmd /f:SomeAssembly.dll /r:"C:\RulesDirectory\SomeRules.dll" /o:OutputFile.xml

Page 1065: Dotnet Stream

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

FxCop – Integrate with Visual Studio

To integrate FxCopCmd into Visual Studio, you must configure Visual Studio to run FxCopCmd as an external tool.

Once configured, FxCopCmd uses the /console and /consoleXsl options to send an abbreviated analysis report, including source code information if available, to Visual Studio's Output window.

Page 1066: Dotnet Stream

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

FxCop – Integrate with Visual Studio

1. In the Title text box, type FxCop.2. To set the value of the Command text

box, browse to the location where FxCop is installed, and select FxCopCmd.exe.

3. In the Arguments text box, specify /console (or /c) in addition to any command-line options you use when running the analysis from the command line.

4. Set the Initial Directory to the location where FxCopCmd should start.

5. Select the Use Output window check box.

6. Click OK.

From the Tools menu in Visual Studio, select External Tools, and then Add to display the External Tools new configuration dialog box.

Page 1067: Dotnet Stream

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.

Thank You !Thank You !

Page 1068: Dotnet Stream

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.

HTMLHTML

* For internal use only

COE – Current Technologies

Page 1069: Dotnet Stream

1069©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

• Understand HTML• Understand CSS• Knowledge on how to use CSS in HTML• Understand Java Scripts• Knowledge on how to use Java Scripts in HTML• Understand DHTML

Page 1070: Dotnet Stream

1070©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 Discussion1. HTML

Introduction Document structure Structuring document content with Headings The document body Text formatting Constructing Lists Images Tables Creating Links Forms Other useful tags Scripts

Page 1071: Dotnet Stream

1071©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

HTML was originally designed so that scientists could create text-based documents containing both basic formatting commands (known as markup) and links to other information (known as hypertext or hyperlinks).

For instance, a document about earthquakes could contain a link to another document about plate tectonics written by a different scientist

Page 1072: Dotnet Stream

1072©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.

Document Structure All HTML documents are composed of

• An HTML element that describes the document as a HTML document

• A declarative header section, which is enclosed in the <HEAD> element

• The main body of the document, which contains the actual document content. The body can be contained within either the <BODY> or <FRAMESET> elements.

Page 1073: Dotnet Stream

1073©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.

Structuring document content with Headings• The first markup tag used in any HTML document should be

<HTML> and the last should be </HTML>.• Then comes the document-header data, which uses <HEAD>

element.• Eg:

<HTML><HEAD>

<TITLE> My first HTML document</TITLE><HEAD>

</HTML>

Page 1074: Dotnet Stream

1074©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.

Structuring document contents with Headings

<HTML><HEAD>

<TITLE> Resume</TITLE></HEAD><BODY BGCOLOR=“white” TEXT=“black”>

<H1>Employment History</H1><H1> Education</H1>

</H2> Undergraduate</H2><H2> Graduate</H2>

<H1>Skills</H1><H2>Managerial</H2><H2>Computer Related</H2>

</H3> Hardware/Software</H3>

<H3> Internet/Web</H3><H1>References</H1></BODY>

</HTML>

Page 1075: Dotnet Stream

1075©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.

The Document Body• Contains the content of the document.• Eg:

<HTML><HEAD>

<TITLE> MY FIRST HTML DOCUMENT </TITLE></HEAD><BODY BGCOLOR=“teal” TEXT=“white” LINK=“navy” VLINK=“maroon”></BODY>

</HTML>

Page 1076: Dotnet Stream

1076©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.

Text Formatting Paragraph Element

<P> The idea of text formatting may at first seem to go against our previous statements that HTML should only provide structure for the document.</P>

Providing Emphasis <P> “I <EM> really don’t want to go to school today,” the

little girl said.</P> Strong Emphasis

<P> “I <STRONG> really don’t </STRONG> want to go to school today,” the little girl said.</P>

Page 1077: Dotnet Stream

1077©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.

Constructing Lists

Unordered lists<P> Vehicles I have owned</P><UL>

<LI> 1993 Saturn SL1</LI><LI>1996 Ford Contour </LI><LI>1999 Ford Ranger</LI>

<UL> Ordered lists

<P> Things to do today </P><OL>

<LI> Check Email </LI><LI> Write a chapter</LI><LI> Teach Class <LI>

<OL>

Page 1078: Dotnet Stream

1078©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.

Constructing Lists

Definition Lists<DL><DT> RAM

<DD>Random Access Memory</DD></DT><DT> BIOS

<DD> Basic Input Output System </DD></DT></DL>

Page 1079: Dotnet Stream

1079©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.

Images

<img src="URL"> Where URL is a complete or partial path to the

source image file to be loaded, including the file name. Eg: <b>This is a transparent inline image <img src="bearico1.gif"> of a bear.</b>

align=value, allowed values are top, middle, center, bottom, abstop, absmiddle, absbottom, right, leftEg: This image is aligned <img src="orb.gif"

align=absmiddle> in the absolute middle of the text line. This image is aligned in the absolute middle of the text line.

Eg: <img src="image.gif" alt="This is an image."> The text “This is an image” would display if the image file image.gif could not be displayed.

Page 1080: Dotnet Stream

1080©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.

Tables

<TABLE WIDTH=“75%” BORDER=“5” CELLPADDING=“10”><TR ALIGN=“RIGHT”>

<TD ROWSPAN=“2”> Seuss’ Fish</TD><TD>One Fish</TD><TD BGCOLOR=“red”> Red Fish </TD>

</TR><TR>

<TD> Two fish</TD><TD BGCOLOR=“blue” ALIGN =“CENTER”> Blue Fish

</TD></TR><TR>

<TD COLSPAN=“3” ALIGN=“CENTER”> Learn HTML with Dr. Seuss!</TD></TR>

</TABLE>

Page 1081: Dotnet Stream

1081©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.

Creating Links

<a href="URL">Link Text or Object</a> <P> Additional details about our new widgets can be found

on the <A HREF=“details.html”>widgets details page</A> An image can be used as a link object

<a href="index.html"><img src="return.gif"></a> to the top level.

Page 1082: Dotnet Stream

1082©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.

Generating Forms

The form container has two attributes METHOD & ACTION Method describes how the data collected by the form should

be sent to the form processor. For most purposes , this value will be “post”.

ACTION defines the form processor to be used. Two options are generally available: an e-mail processor and a CGI script

The URL defined as the ACTION value points to a CGI script that will receive and act upon the data sent by the browser when the user hits the “submit” button.

Page 1083: Dotnet Stream

1083©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.

Form Input Controls

Text Creates a text input box

Password Creates a specialized input box. The characters entered are obscured to maintain security.

Checkbox Creates a box which holds a checkmark and acts as a toggle between an on and off state.

Radio Similar to checkbox, but used for groups. Only one option per group may be selected at any time.

Submit Creates a standard button used to instruct the browser to apply the action defined in the <FORM> element

Reset Creates a button which will return all form elements to their original state.

Textarea Creates a text input area that can contain more than one line.

Each of these control elements takes similar syntax. <INPUT TYPE= ”Control Type” NAME= ”MyControl”>

Page 1084: Dotnet Stream

1084©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.

Form Input Controls

. Select Creates an drop down select (or list) box Syntax <Select name=”ControlName”> <Option value=”Value1”>Value2 </option> . . </Select> Where

Value1 - Value to be submitted to the server Value2 - Value to be displayed in the browser

Page 1085: Dotnet Stream

1085©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.

Other useful tags

Comment tagsIt is often useful to make notes, or comments, inside your HTML files that will not actually display on the screen.

For Example:<!–

Author: Eric Schurman Purpose: Demonstrate comments Location: Chapter 4

--> Meta Tags

This tag can also be used to furnish a number of services not directly related to the content of the page. Following is a list of some of the tasks you can accomplish with <META> tags, along with the corresponding code: Force a page to refresh after a set number of seconds (5 in the sample

below). <META HTTP-EQUIV="REFRESH" CONTENT="5">

Force a page to not be cached (stored locally). Some browsers do not support this feature

<META NAME="Pragma" CONTENT="No-Cache">

Page 1086: Dotnet Stream

1086©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.

Other useful tags

Redirect the user to a different page after a set period of time:<META HTTP-EQUIV="refresh"

CONTENT="5;URL=http://www.microsoft.com">

Indicate that the document's contents expired at a point in the past, which forces the page not to be read from the local cache:

<META HTTP-EQUIV="Expires" CONTENT="Thursday, 18-Jan 96 16:26:30 GMT">

Page 1087: Dotnet Stream

1087©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.

Scripts

Functionality that isn’t available in HTML can be added to documents using various scripting languages, such as JavaScript, VBScript etc.

The <SCRIPT> element is used for this . SCRIPT elements can appear in either the HEAD or BODY

elements of a document, depending on the purpose of the script.

Page 1088: Dotnet Stream

1088©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.

Advanced topics - Cascaded Style Sheet Example

MyHtml.html

<HEAD><TITLE>SORT POS Force Match Screen</TITLE><LINK REL="stylesheet" TYPE="text/css" HREF="MYSTYLESHEET.CSS">

</HEAD>…<TABLE BORDER="0" CELLSPACING="0" BORDERCOLOR="#5C3317"

BGCOLOR="#c0c0c0" WIDTH="100%"><TH align="center"HEIGHT="20" class=PageTitleFont>POS Force Match - Order/POS Inquiry</TH><TR> <TD WIDTH="100%" class=TableHeaderFontLeft> </TD></TR>

</TABLE>…

Page 1089: Dotnet Stream

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.

DHTMLDHTML

Page 1090: Dotnet Stream

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

Topics of Discussion

DHTML What is Dynamic HTML Components Object Oriented scripting Scripting Dynamic Styles Creating movement on the Screen

Page 1091: Dotnet Stream

1091©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 Dynamic HTML?

Dynamic HTML is not just one particular technology, language or set of features. Instead, DHTML comprises a number of different technologies and describes how these technologies interact.In Simple terms, DHTML allows you to use conventional HTML, script, and a variety of other technologies to dynamically change how HTML displays text and graphics on a screen.

Making HTML Dynamic

HTML pages are static; generally, the only way to change a screen display with HTML alone is to load another page. Internet Explorer versions 4 and 5, however, support an extensive Document Object Model that exposes all the elements of a page, including the HTML elements. This allows any HTML element in Internet Explorer to be manipulated at any time, even if the page has already been loaded, turning plain, old HTML into Dynamic HTML

Page 1092: Dotnet Stream

1092©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 Dynamic HTML? Contd..

For example, let's say that you have a Web page containing the image shown on this screen.

Page 1093: Dotnet Stream

1093©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 Dynamic HTML? Contd..

If you want to change the image using just HTML, your only real option is to go to another page that displays a new image. With Dynamic HTML, you can change the image simply by changing the attributes of the HTML image tag. This would allow us to create a page in which the light bulb could be turned on by just clicking it<HTML>

<HEAD><SCRIPT LANGUAGE="JavaScript">function ChangeImage(){MyImage.src="bulbon.gif"}</SCRIPT>

</HEAD><BODY>

<IMG ID="MyImage" SRC="bulboff.GIF" ALIGN="center" ONCLICK="ChangeImage()"> <B>Click to Turn On!</B> 

</BODY></HTML>

Page 1094: Dotnet Stream

1094©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.

ComponentsObjects

HTML page contains elements, which are usually defined by opening and closing tags surrounding specific content. Some elements are contained within others; a table row (TR) element is contained in a table element, for example.

Every element on a page is represented in the Dynamic Object Model as an object, the basic unit of the Object Model.

Examples: image a span of text the body region of an HTML document

Note: Anything described in the text of an HTML file

Page 1095: Dotnet Stream

1095©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.

Components Contd..

PropertiesIn traditional HTML, you can modify an element by setting its attributes. The attributes contain information describing that element.

For instance, here is a simple image tag with three HTML attributes: SRC, WIDTH and ID:

<IMG SRC="oldpic.gif" WIDTH="10" ID="MyImage"> Events

An action or occurrence on the page, such as a mouse click, is referred to as an event. Here are few examples of events:

onmousedown onmouseover onmouseout onkeypress Onfocus

Note: The onclick event is a special event that can be fired by either

the mouse or the keyboard.

Page 1096: Dotnet Stream

1096©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.

Components Contd..

MethodsMethods describe the actions an object can take.

For instance, here is a simple image tag with three HTML attributes: SRC, WIDTH and ID:

<IMG SRC="oldpic.gif" WIDTH="10" ID="MyImage">

Page 1097: Dotnet Stream

1097©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-Oriented ScriptingReading and Changing Properties

In Internet Explorer, virtually all properties can be both read and manipulated through script. In the below code changes the image height and width attributes dynamically<HTML>

<HEAD> <TITLE>Listing 7-1</TITLE>

</HEAD> <BODY>

<IMG ID="Img1" SRC="circle.gif"> <SCRIPT LANGUAGE="JavaScript">

alert("Img1 has width "+Img1.width+" and height "+Img1.height)

Img1.height=150 Img1.width=30 alert("Now it has width "+Img1.width+" and height

"+Img1.height) </SCRIPT>

</BODY> </HTML>

Page 1098: Dotnet Stream

1098©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.

Scripting Dynamic Styles

With dynamic styles in, an element's formatting can be changed at any time with script.

Dynamic styles in your Web page gives you the ability to Change the size, weight, and even the font style of your text in

response to a user's input Expand and collapse outlines Move items on the screen

Note:• Use dot notation to read or set a property of style sheet object

Example<SPAN ID="MySpan" STYLE="color: blue">Hello!</SPAN>

Can be accessed using MySpan.style.color

Page 1099: Dotnet Stream

1099©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.

Scripting Dynamic StylesExample:

<HTML> <HEAD> <SCRIPT LANGUAGE="JavaScript"> <!– function changeIt(oClicked){ oCS=oClicked.style alert("You clicked the element named "+oClicked.id+".") alert("It is "+oCS.fontWeight+". Click OK to change it.") if (oCS.fontWeight==`bold'){oCS.fontWeight=`normal‘} else {oCS.fontWeight=`bold‘} } //--> </SCRIPT> </HEAD>

Page 1100: Dotnet Stream

1100©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.

Scripting Dynamic Styles

<BODY> <SPAN ID=MySpan STYLE="font-weight: bold; cursor: hand"

onclick="changeIt(this)"> Click me! Then click me again!

</SPAN> </BODY>

</HTML>

Page 1101: Dotnet Stream

1101©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.

Creating Movement on the ScreenDynamic styles allows you to precisely position objects at specific locations on the screen. By changing the properties that specify location, the objects can be movedExample:

<HTML> <HEAD>

<TITLE>Listing 15-4</TITLE> <STYLE>SPAN {position:absolute}</STYLE> <SCRIPT LANGUAGE="JavaScript">

function moveSpans(){

Span1.style.top=15 Span2.style.posTop=Span2.style.posTop+1 Span3.style.left=10 Span4.style.top=window.event.y Span5.style.posLeft=window.event.x Span6.style.pixelTop=window.event.x Span6.style.posLeft=window.event.y

} </SCRIPT>

</HEAD>

Page 1102: Dotnet Stream

1102©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.

Creating Movement on the Screen

<BODY onmousemove="moveSpans()"> <SPAN ID="Span1" STYLE="top: 0; left: 0">First Span</SPAN> <SPAN ID="Span2" STYLE="top: 50; left: 50">Second

Span</SPAN> <SPAN ID="Span3" STYLE="top: 100; left: 100">Third

Span</SPAN> <SPAN ID="Span4" STYLE="top: 150; left: 150">Fourth

Span</SPAN> <SPAN ID="Span5" STYLE="top: 200; left: 200">Fifth

Span</SPAN> <SPAN ID="Span6" STYLE="top: 250; left: 250">Sixth

Span</SPAN> </BODY>

</HTML>

Page 1103: Dotnet Stream

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.

ExercisesExercises

Page 1104: Dotnet Stream

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

Exercise 1

1. Design an HTML page with following information• Page heading as “Employee Information System” with

font-style: italic font-size: 24pt color: Blue

• Following input controls Employee Number - text box

Should allow only Numbers

Employee Name - text box Should allow both alphabets and Special Characters

Date of Birth - text box Should be less than current date

Grade – Select box Location [Chennai – Bangalore] – Radio button Basic Salary – Text box

Should allow only whole numbers

HRA Should allow only whole numbers

PF Should allow only whole numbers

Page 1105: Dotnet Stream

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

Exercise 1

• Following buttons Clear

Should clear user inputs Validate

Should validate user inputs Should calculate the Gross and Net salary Display Gross and Net Salary in the same page

Page 1106: Dotnet Stream

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.

CSSCSS

Page 1107: Dotnet Stream

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

Topics of Discussion

CSS Introduction In-Line Styles Style Sheets Style Sheets – Global Style sheets Style Sheets – Linked Style sheets Classes Links

Page 1108: Dotnet Stream

1108©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

The Cascading Style Sheets (CSS) specification was developed by the World Wide Web Consortium (W3C) to provide a simple model that separates the style of a document from the content.

ExampleA style sheet can be created that defines <H1> tags as bold 24-point Verdana type with a 1-centimeter white border and a red background. Changing this one definition can change the appearance of all <H1> tags on the site.

Advantages: Changing style of document can be done with a few simple

tweaks to the document style We can alter everything from the size, style, and color of

text to the spacing between letters and lines, the border and padding around elements, and the exact position of an object on the page.

Page 1109: Dotnet Stream

1109©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.

In-Line StylesAn in-line style is a style applied to a particular tag on a Web page. You can apply an in-line style to any tag on a page by using the STYLE attribute Like other attributes, STYLE affects only the tag that contains it, just as setting the WIDTH attribute for an image affects only that image. Therefore, in-line styles are most useful for precise control of a single element, rather than for large-scale changes to an entire page or site.Example:

<HTML> <HEAD> <TITLE>Listing 11-3</TITLE> </HEAD> <BODY> <SPAN STYLE="font-weight: bold; font-style: italic"> This text is in a SPAN.</SPAN><BR> This text is not in a SPAN. </BODY>

</HTML>

Page 1110: Dotnet Stream

1110©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.

Style Sheets

A style sheet consists of one or more style definitions (also called style rules).

A style sheet can be contained within a Web document or kept in a file outside the document.

A style definition is made up of a selector followed by a declaration block

ExampleSPAN {font-weight: bold; font-style: italic}

Note: declaration block follows the selector and is enclosed

in curly braces list of style declarations, separated by semicolons

Page 1111: Dotnet Stream

1111©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.

Style Sheets - Global Style SheetsGlobal Style Sheets

A global (or embedded) style sheet is included as part of the HTML in a document. This type of style sheet defines its boundaries by the <STYLE> and </STYLE> tags and must be placed in the header region of the HTML document.

Example 1:<HTML>

<HEAD> <STYLE>SPAN {font-weight: bold; font-style:

italic} </STYLE> </HEAD> <BODY>

<SPAN>This text is in a SPAN. </SPAN><BR> This text is not in a SPAN.<BR> <SPAN>This text is in a SPAN. </SPAN><BR> This text is not in a SPAN.<BR> <SPAN>This text is in a SPAN. </SPAN><BR> This text is not in a SPAN.<BR>

</BODY> </HTML>

Page 1112: Dotnet Stream

1112©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.

Style Sheets - Global Style SheetsExample 2:

<HTML> <HEAD>

<TITLE>Listing 11-6</TITLE> <STYLE>

H1 {font-size: 16pt; font-weight: bold; color: red}

H2 {font-style: italic; font-size: 24pt; color: green} SPAN {font-weight: bold; font-style: italic}

</STYLE> </HEAD> <BODY>

<SPAN>This text is in a SPAN.</SPAN> <H1>This text is in an H1.</H1> <H2>This text is in an H2.</H2>

</BODY> </HTML>

Page 1113: Dotnet Stream

1113©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.

Style Sheets - Linked Style Sheets

Linked Style SheetsThe formatting flexibility described in the preceding

sections does not end at the level of the single Web page; you can control styles across several pages or even across an entire Web site by using linked style sheets.

A linked (or external) style sheet is simply a text file that includes style definitions; it is saved using the CSS filename extension.

The file, which is external to the HTML file, can be referenced by (or linked to) an HTML document that uses the HTML <LINK> tag.

Example:sample.css

H1 {font-size: 16pt; font-weight: bold; color: red}

H2 {font-style: italic; font-size: 24pt; color: green}

SPAN {font-weight: bold; font-style: italic}

Page 1114: Dotnet Stream

1114©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.

Style Sheets - Linked Style SheetsSample.html

<HTML> <HEAD>

<TITLE>Listing 11-8</TITLE> <LINK HREF=“sample.css" REL="STYLESHEET"

TYPE="text/css"> </HEAD> <BODY>

<SPAN>This text is in a SPAN.</SPAN> <H1>This text is in an H1.</H1> <H2>This text is in an H2.</H2> <H2 STYLE="font-size: 36pt">This is modified H2

text.</H2> </BODY>

</HTML>

Note: @import: command enables one style sheet to

include another

Page 1115: Dotnet Stream

1115©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.

ClassesCSS supports the creation of classes. Put simply, a class is a variation of an existing element. For example, suppose you want to use the <B> tag throughout your document, but you want slight variations depending on where each tag is used.

<HTML> <HEAD>

<TITLE>Listing 11-11</TITLE> <STYLE>

B.large {font-size: 24pt} B.small {font-size: 8pt}

</STYLE> </HEAD> <BODY>

<B>This is a standard B.</B> <B CLASS="small">This uses the small class.</B> <B CLASS="large">This uses the large class.</B>

</BODY> </HTML>

Page 1116: Dotnet Stream

1116©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.

Classes

Note: A class is defined by a selector name followed by a

period and the class name value is then assigned to the class, using a

statement enclosed in curly braces To create a global class that is usable by all

elements, do no specify a particular tag as a selector

Example: <STYLE>

.large {font-size: 24pt}

.small {font-size: 8pt} </STYLE>

Page 1117: Dotnet Stream

1117©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.

LinksUsing dynamic styles, you can also change the style of the different states of a hypertext link, which is defined by the anchor tag, <A>. Example

<HTML> <HEAD>

<TITLE>Listing 11-13</TITLE> <STYLE>

A:link {text-decoration: none} A:hover {color: red; text-decoration: underline} A:visited {color: green}

</STYLE> </HEAD> <BODY>

<A HREF="http://msdn.microsoft.com">msdn.microsoft.com</A><BR>

<A HREF="http://microsoft.com">microsoft.com</A><BR><A

HREF="http://www.w3.org/style/">www.w3.org/style</A><BR> <A HREF="http://www.w3.org">www.w3.org</A><BR>

</BODY> </HTML>

Page 1118: Dotnet Stream

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.

Thank You !Thank You !

Page 1119: Dotnet Stream

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

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

XML XML

COE – Current Technologies

Page 1120: Dotnet Stream

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

Course Objectives

• Lean what XML is

• What are the industrial uses of XML

• How to write an XML

• What are XML Parsers and its types

• XSL

• X Path Expressions and Functions

• XSLT Elements

Page 1121: Dotnet Stream

1121©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.

• WWW, HTML and the basics of building Web pages

• Web scripting languages like JavaScript or VBScript

Prerequisites for the course

Page 1122: Dotnet Stream

1122©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.

Session Plan

• Overview• Syntax• XML DTD • XML Parsers• Beautification of XML• XSL• xPath Expressions• xPath functions• XSLT Elements.• Literal Result Elements• Conditional formatting• XSL FO

Page 1123: Dotnet Stream

1123©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 XML• XML stands for Extensible Markup Language.

• XML is a cross-platform, software and hardware independent tool for transmitting information.

• XML is a markup language much like HTML .• XML was designed to describe data. • XML tags are not predefined. You must define your own tags. • XML uses a Document Type Definition (DTD) or an XML Schema to describe the data.• XML was designed to describe data and to focus on what data is. HTML was designed

to display data and to focus on how data looks.• The main difference between XML and HTML:

• XML was designed to carry data.

• XML is not a replacement for HTML.

• XML and HTML were designed with different goals:

• HTML is about displaying information, while XML is about describing information.

Page 1124: Dotnet Stream

1124©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 XML• XML was not designed to DO anything. XML was created to structure, store and to send

information.• The following example is a note to Tove from Jani, stored as XML:

<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>

• The note has a header and a message body. It also has sender and receiver information. But still, this XML document does not DO anything. It is just pure information wrapped in XML tags. Someone must write a piece of software to send, receive or display it.

• XML documents are meant to be like Web pages, and viewed in a browser

• There are "browsers" or other tools that are meant to be used with XML

• XML creates "pages" similar to HTML

Page 1125: Dotnet Stream

1125©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 XML - Viewing XML Files• To view an XML document in IE 5.0 (and higher) you can click on a link, type the URL in the address

bar, or double-click on the name of an XML file in a files folder. If you open an XML document in IE, it will display the document with color coded root and child elements. A plus (+) or minus sign (-) to the left of the elements can be clicked to expand or collapse the element structure. If you want to

view the raw XML source, you must select "View Source" from the browser menu.

• To view an XML document in Netscape 6 you'll have to open the XML file and then right-click in XML file and select "View Page Source". If you open an XML document in

Netscape 6, it will display the document with color coded root and child elements.

Page 1126: Dotnet Stream

1126©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 XML• XML tags are not predefined.• The tags used to mark up HTML documents and the structure of HTML documents are

predefined. The author of HTML documents can only use tags that are defined in the HTML standard (like <p>, <h1>, etc.).

• XML allows the author to define his own tags and his own document structure.

• The tags in the example above (like <to> and <from>) are not defined in any XML standard. These tags are "invented" by the author of the XML document.

• Below is a sample xml portraying the “Plant Catalog”, which describes each plant in terms of below parameters/properties.

• BOTANICAL name• COMMON name• ZONE • LIGHT• PRICE• AVAILABILITY

Exercise: Write an XML to describe employees in your organization.

plant_catalog.xml

Page 1127: Dotnet Stream

1127©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.

Uses of XML• XML was designed to store, carry, and exchange data

• XML can Separate Data from HTML. With XML, data is stored outside the HTML.

• When HTML is used to display data, the data is stored inside the HTML. With XML, data can be stored in separate XML files. This way developer can concentrate on using HTML for data layout and display, and be sure that changes in the underlying data will not require any changes to the display HTML.

• XML data can also be stored inside HTML pages as "Data Islands". One can still concentrate on using HTML only for formatting and displaying the data.

• E.g.: The unofficial <xml> tag is used to embed XML data within HTML. XML data can be embedded directly in an HTML page like this:

<html><body><xml id="cdcat" src="cd_catalog.xml"></xml><table border="1" datasrc="#cdcat"><tr><td><span datafld="ARTIST"></span></td><td><span datafld="TITLE"></span></td></tr></table></body></html>

cd_catalog.xml

Page 1128: Dotnet Stream

1128©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.

Uses of XML• With XML, data can be exchanged between incompatible systems.

• In the real world, computer systems and databases contain data in incompatible formats. One of the most time-consuming challenges for developers has been to exchange data between such systems over the Internet.

• Converting the data to XML can greatly reduce this complexity and create data that can be read by many different types of applications.

• With XML, plain text files can be used to share data.

• Since XML data is stored in plain text format, XML provides a software- and hardware-independent way of sharing data.

• This makes it much easier to create data that different applications can work with. It also makes it easier to expand or upgrade a system to new operating systems, servers, applications, and new browsers.

• With XML, plain text files can be used to store data.

• XML can also be used to store , exchange, import and export data in files or in databases. Applications can be written to store and retrieve information from the store, and generic applications can be used to display the data.

Page 1129: Dotnet Stream

1129©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.

Uses of XML• With XML, your data is available to more users.

• Since XML is independent of hardware, software and application, you can make your data available to other than only standard HTML browsers.

• Other clients and applications can access your XML files as data sources, like they are accessing databases. Your data can be made available to all kinds of "reading machines" (agents).

• XML can be used to Create new Languages

• XML is the mother of WAP and WML.

• The Wireless Markup Language (WML), used to markup Internet applications for handheld devices like mobile phones, is written in XML.

Exercise: List any other 3-5 uses of XML

Page 1130: Dotnet Stream

1130©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.

DAY1: Syntax• XML Syntax• XML Elements• XML Validation - Well Formed XML

• XML Validation - Valid XML

Page 1131: Dotnet Stream

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

XML Syntax• XML documents use a self-describing and simple syntax.

<?xml version="1.0" encoding="ISO-8859-1"?><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>• The first line in the document - the XML declaration - defines the XML version and the

character encoding used in the document. In this case the document conforms to the 1.0 specification of XML and uses the ISO-8859-1 (Latin-1/West European) character set.

• The next line describes the root element of the document (like it is saying: "this document is a note"):

• The next 4 lines describe 4 child elements of the root (to, from, heading, and body):

• And finally the last line defines the end of the root element:

Page 1132: Dotnet Stream

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

XML Syntax• XML elements must have a closing tag. With XML, it is illegal to omit the closing tag.

• In HTML some elements do not have to have a closing tag. The following code is legal in HTML:

<p>This is a paragraph<p>This is another paragraph

• In XML all elements must have a closing tag, like this:<p>This is a paragraph</p>

<p>This is another paragraph</p> • XML declaration is not required to have a closing tag. This is not an error. The declaration is not

a part of the XML document itself. It is not an XML element, and it should not have a closing tag.

• XML tags are case sensitive• Unlike HTML, XML tags are case sensitive.

• With XML, the tag <Letter> is different from the tag <letter>.

• Opening and closing tags must therefore be written with the same case:<Message>This is incorrect</message><message>This is correct</message>

Page 1133: Dotnet Stream

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

XML Syntax• Improper nesting of tags makes no sense to XML.

• In HTML some elements can be improperly nested within each:

<b><i>This text is bold and italic</b></i>.

• In XML all elements must be properly nested:

<b><i>This text is bold and italic</i></b>

• All XML documents must contain a single tag pair to define a root element. All other elements must be within this root element. All elements can have sub elements (child elements). Sub elements must be correctly nested within their parent element:

E.g.: <root>

<child> <subchild>.....</subchild> </child></root>

• XML elements can have attributes in name/value pairs just like in HTML. In XML the attribute value must always be quoted. Study the two XML documents below. The first one is incorrect, the second is correct:

Page 1134: Dotnet Stream

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

XML Syntax<?xml version="1.0" encoding="ISO-8859-1"?>

<note date=12/11/2002><to>Tove</to><from>Jani</from></note><?xml version="1.0" encoding="ISO-8859-1"?><note date="12/11/2002"><to>Tove</to><from>Jani</from></note>

The error in the first document is that the date attribute in the note element is not quoted. Correct date="12/11/2002". Incorrect date=12/11/2002.

• With XML, the white space in your document is not truncated. This is unlike HTML. With HTML, a sentence like -

Hello my name is Tove,

will be displayed like this:

Hello my name is Tove,

because HTML strips off the white space.

Page 1135: Dotnet Stream

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

XML Syntax• With XML, a new line is always stored as LF.

• The syntax for writing comments in XML is similar to that of HTML.

• <!-- This is a comment -->

Page 1136: Dotnet Stream

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

XML Elements• With XML, documents can be Extended to carry more information. E.g.: Given

<note><to>Tove</to><from>Jani</from><body>Don't forget me this weekend!</body></note>

• an application that extracted the <to>, <from>, and <body> elements from the XML document produces below output:

To: Tove

From: Jani

Don't forget me this weekend!

• Imagine that the author of the XML document added[Extended] some extra information to it:

<note><date>2002-08-01</date><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>

• The application will still be able to find the <to>, <from>, and <body> elements in the XML document and produce the same output.

Page 1137: Dotnet Stream

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

XML Elements• Elements are related as parents and children. Imagine that this is a

description of a book:. Next slide displays the XML document in the hierarchical format representing this book.

My First XML

Introduction to XML What is HTML

What is XML

XML Syntax Elements must have a closing tag

Elements must be properly nested

Page 1138: Dotnet Stream

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

XML Elements<book>

<title>My First XML</title><prod id="33-657" media="paper"></prod><chapter>Introduction to XML<para>What is HTML</para><para>What is XML</para></chapter>

<chapter>XML Syntax<para>Elements must have a closing tag</para><para>Elements must be properly nested</para></chapter>

</book>• Book is the root element. Title, prod, and chapter are child elements of book. Book is

the parent element of title, prod, and chapter. Title, prod, and chapter are siblings (or sister elements) because they have the same parent.

Page 1139: Dotnet Stream

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

XML Elements• XML elements can have attributes. In HTML (and in XML) attributes provide additional

information about elements: <img src="computer.gif"> <a href="demo.asp">.

• Attributes are used to provide additional information about elements. Attributes often provide information that is not a part of the data. In the example below, the file type is irrelevant to the data, but important to the software that wants to manipulate the element:

• <file type="gif">computer.gif</file>

• Attribute values must always be enclosed in quotes, but either single or double quotes can be used. For a person's sex, the person tag can be written like this: • <person sex="female”> or <person sex='female'>

Exercise: Write a program to describe the regional hierarchy in the world. [Ex: for India]World

ContinentsCounteries

States……….

Page 1140: Dotnet Stream

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

XML Validation - Well Formed XML• A "Well Formed" XML document is a document that conforms

to the XML syntax

<?xml version="1.0" encoding="ISO-8859-1"?>

<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>

Page 1141: Dotnet Stream

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

XML Validation - Valid XML • A "Valid" XML document is a "Well Formed" XML document,

which also conforms to the rules of a Document Type Definition (DTD):<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE note SYSTEM "InternalNote.dtd"><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>

Here, the xml being properly structured is not sufficient, but also has to adhere to the rules specified in the file InternalNote.dtd.

Page 1142: Dotnet Stream

1142©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.

DAY1: XML DTD • XML DTD • XML DTD - Internal • XML DTD - External

Page 1143: Dotnet Stream

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

XML DTD • DTD (Document Type Definition) defines legal building blocks of an XML

document.

• DTD defines the document structure with a list of legal elements.

• XML provides an application independent way of sharing data. With a DTD, independent groups of people can agree to use a common DTD for interchanging data.

• An application can use a standard DTD to verify that the data received from the outside world is valid. You can also use a DTD to verify your own data.

• A DTD can be declared inline in your XML document, or as an external reference.

• Following slides give an overview of internal and external DTDs. For further information on DTD, refer to http://xmlfiles.com/dtd/dtd_building.asp site.

Page 1144: Dotnet Stream

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

XML DTD - Internal • This is an XML document with a Document Type Definition:

<?xml version="1.0"?>

<!DOCTYPE note [ <!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)>]><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>

• The DTD is interpreted like this:!ELEMENT note (in line 2) defines the element "note" as having four elements: "to,from,heading,body".!ELEMENT to (in line 3) defines the "to" element to be of the type "CDATA".!ELEMENT from (in line 4) defines the "from" element to be of the type "CDATA"and so on.....

Page 1145: Dotnet Stream

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

XML DTD - External • This is the same XML document with an external DTD:

<?xml version="1.0"?><!DOCTYPE note SYSTEM "note.dtd"><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>

• This is a copy of the file "note.dtd" containing the Document Type Definition:

<?xml version="1.0"?><!ELEMENT note (to,from,heading,body)><!ELEMENT to (#PCDATA)><!ELEMENT from (#PCDATA)><!ELEMENT heading (#PCDATA)><!ELEMENT body (#PCDATA)>

Page 1146: Dotnet Stream

1146©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.

DAY1: XML Parsers• XML Parsers• XML DOM Parsers• XML SAX Parsers

Page 1147: Dotnet Stream

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

XML Parsers• A parser is a program that initially reads through the XML file and

transforms the information into some form that another program can use directly.

• In order to process XML data, every program or server process needs an XML parser. The parser extracts the actual data out of the textual representation and creates either events or new data structures from them.

• XML parser is used to read and update - create and manipulate - an XML document. An XMLparser is a processor that reads an XML document and determines the structure and properties of the data.

• A generalized XML parser reads XML files and generates a hierarchically structured tree, then hands off data to viewers and other applications for processing. A validating XML parser also checks the XML syntax and reports errors. It goes beyond the XML rules for well formed and validates the document against an XML DTD, the parser is said to be a "validating" parser

Page 1148: Dotnet Stream

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

XML Parsers• There are two different kinds of XML parsers.

• Non Validating Parser: These parser do not check a document against any DTD (Document Type Definition). It is only checked whether the document is properly marked up according to XML syntax rules(well-formed or not).

• Validating Parser: checks, whether the document is valid. The parser verifies that the document conforms to a specific DTD

(either internal or external to the XML file being parsed). .

Page 1149: Dotnet Stream

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

XML Parsers• Parsers are different not only in their support for checking and

transforming documents but also in the way they read a document.

• Event-based parsers read the text sequentially, and whenever a start or end tag appears an event is sent to the application. The Simple API for XML (SAX) is such an API.

• With the second approach the parser builds a hierarchical data structure from the content of the document. This is how the Document Object Model (DOM) API works, similar to the HTML document tree in a Web browser.

.

Page 1150: Dotnet Stream

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

XML DOM Parsers• XML parser is used to load an XML document into the memory of the

computer. When the document is loaded, its information can be retrieved and manipulated by accessing the DOM.

• The DOM represents a tree view of the XML document.

• A DOM tree is composed of nodes that result from parsing an XML document. A node is the in-memory representation of an XML entity. The standard W3C DOM model has several types of nodes. For example, a text node represents a block of text in the XML document, an element node represents an element of the XML document, and an attribute node represents the name and value of an attribute placed within an element.

• The DOM is a tree because (except for the root or document node) every other node has a parent. For example, attribute nodes are always associated with an element node, while the text enclosed within the element's open tag and close tag is mapped to a text node. The text node is a child node of the element node. So, representing even a

very simple form of XML document may require multiple node types.

Page 1151: Dotnet Stream

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

XML SAX Parsers• The Simple API for XML or SAX is faster and more efficient than using the DOM. SAX is a

Java based API that is very robust and effective. These SAX parsers make it easy for you to start using the Simple API for XML.

• Unlike DOM (Document Object Model) which creates a tree based representation for the information in your XML documents, SAX does not have a default object model. This means that when you create a SAX parser and read in a document (unlike DOM) you will not be given a default object model. A SAX parser is only required to read in your XML document and fire events based on the things it encounters in your XML document. Events are fired when the following things happen:

open element tags are encountered in your document

close element tags are encountered in your document

#PCDATA and CDATA sections are encountered in your document

processing instructions, comments, entity declarations, are encountered in your document.

.

Page 1152: Dotnet Stream

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.

Thank You !

Page 1153: Dotnet Stream

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

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

Java ScriptJava Script

COE – Current Technologies

Page 1154: Dotnet Stream

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

Topics of Discussion

Java Script• Introduction• Operators• Statements• Core Objects• Document Objects• Window Objects• Form Objects• Events

Page 1155: Dotnet Stream

1155©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

JavaScript is a compact, object-based scripting language for developing client and server Internet applications.

The significant advantage of Java Scripts is that scripts run on the client side. Once a page has been downloaded, all its scripts run on the user's browser rather than on a server that might be halfway around the world.

Anyone who views your Web pages with a script-capable browser can use your scripts without installing any extra software—and potentially without even knowing that scripts are being used. To the viewer, scripts are seamless and invisible.

Page 1156: Dotnet Stream

1156©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.

Operators Arithmetic String Logical Bitwise Assignment Comparison Special

Page 1157: Dotnet Stream

1157©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.

Operators - Arithmetic

+ (Addition) Adds 2 numbers. ++ (Increment) Adds one to a variable

representing a number - (Unary negation, subtraction) As a unary

operator, negates the value of itsargument. As a binary operator, subtracts 2 numbers.

-- (Decrement) Subtracts one from a variable representing a number (returning either the new or old value of the variable)

* (Multiplication) Multiplies 2 numbers. / (Division) Divides 2 numbers. % Computes the integer remainder of dividing 2

numbers.

Page 1158: Dotnet Stream

1158©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.

Operators - String + (String addition) Concatenates 2 strings. += Concatenates 2 strings and assigns the result to the first

operand.

Page 1159: Dotnet Stream

1159©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.

Operators - Logical && (Logical AND) Returns true if both logical operands are

true. Otherwise, returns false. || (Logical OR) Returns true if either logical expression is

true. If both are false, returns false. ! (Logical negation) If its single operand is true, returns

false; otherwise, returns true.

Page 1160: Dotnet Stream

1160©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.

Operators - Bitwise

& (Bitwise AND) Returns a one in each bit position if bits of both operands are ones

^ (Bitwise XOR) Returns a one in a bit position if bits of one but not both operands are one.

| (Bitwise OR) Returns a one in a bit if bits of either operand is one.

~ (Bitwise NOT) Flips the bits of its operand. << (Left shift) Shifts its first operand in binary

representation the number of bits to the left specified in the second operand, shifting in zeros from the right.

>> (Sign-propagating right shift) Shifts the first operand in binary representation the number of bits to the right specified in the second operand, discarding bits shifted off.

>>> (Zero-fill right shift) Shifts the first operand in binary representation the number of bits to the right specified in the second operand, discarding bits shifted off, and shifting in zeros from the left.

Page 1161: Dotnet Stream

1161©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.

Operators - Assignment

= Assigns the value of the second operand to the first operand += Adds 2 numbers and assigns the result to the first. -= Subtracts 2 numbers and assigns the result to the first. *= Multiplies 2 numbers and assigns the result to the first. /= Divides 2 numbers and assigns the result to the first. %= Computes the modulus of 2 numbers and assigns the result to

the first. &= Performs a bitwise AND and assigns the result to the first

operand. ^= Performs a bitwise XOR and assigns the result to the first

operand. |= Performs a bitwise OR and assigns the result to the first

operand. <<= Performs a left shift and assigns the result to the first operand. >>= Performs a sign-propagating right shift and assigns the result

to the first operand. >>>= Performs a zero-fill right shift and assigns the result to the first

operand.

Page 1162: Dotnet Stream

1162©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.

Operators - Comparison

== Returns true if the operands are equal. != Returns true if the operands are not equal. > Returns true if left operand is greater than right

operand. >= Returns true if left operand is greater than or equal to

right operand. < Returns true if left operand is less than right operand. <= Returns true if left operand is less than or equal to right

operand.

Page 1163: Dotnet Stream

1163©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.

Operators - Special

?: Lets you perform a simple "if...then...else” , Evaluates two expressions and returns the result of the

second expression. delete Lets you delete an object property or an element at a

specified index in an array. new Lets you create an instance of a user-defined object type

or of one of the built-in object types. this Keyword that you can use to refer to the current object. typeof Returns a string indicating the type of the unevaluated

operand. void The void operator specifies an expression to be

evaluated without returning a value.

Page 1164: Dotnet Stream

1164©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.

Statements

break continue do….while for for…in function if….else return switch var

Page 1165: Dotnet Stream

1165©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.

Core Objects

Array Represents an array. Boolean Represents a Boolean value. Date Represents a date. Function Specifies a string of JavaScript code to be compiled

as a function. Math Provides basic math constants and functions; for

example, its PI property contains the value of pi. Number Represents primitive numeric values Object Contains the base functionality shared by all

JavaScript objects. String Represents a JavaScript string.

Page 1166: Dotnet Stream

1166©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.

Date-object

JavaScript lets you use some predefined objects. This is for example the Date-object, the Array-object or the Math-object. There are several other objects - please refer to the documentation provided by Netscape for a complete reference. As the name implies this object lets you work with time and date.

today= new Date() This creates a new Date-object called today

In order to get another date and time we can use another constructor (this is the Date() method which is called through the new operator when constructing a new Date-object):

today= new Date(1997, 0, 1, 17, 35, 23) This will create a Date-object which represents the first of

January 1997 at 17:35 and 23 seconds. So you specify the date and time like this:

Date(year, month, day, hours, minutes, seconds)

Page 1167: Dotnet Stream

1167©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.

Functions

Functions We will use functions in most of our JavaScript programs. Basically

functions are a way for bundling several commands together.<html>

<script language="JavaScript"><!-- hide

function myFunction() {

document.write("Welcome to my homepage!<br>");

document.write("This is JavaScript!<br>");}myFunction();myFunction();myFunction();

// --></script></html>

Page 1168: Dotnet Stream

1168©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.

Functions Functions can also be used in combination with event-

handlers.

<html><head><script

language="JavaScript"><!-- hide

function calculation() { var x= 12;

var y= 5; var result= x + y;

alert(result);}

// --></script></head><body>

<form><input type="button"

value="Calculate" onClick="calculation()"></form>

</body></html>

Page 1169: Dotnet Stream

1169©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.

Array-object

Arrays can be seen as many variables bundled together. You can access them through one name and a number. Let's say out array is called names. Then we can access the first name through names[0]. The second name is called name[1] and so on. Since JavaScript 1.1 (Netscape Navigator 3.0) you can use the Array-object. You can create a new array through

myArray= new Array(). Now you can assign values to this array: myArray[0]= 17; myArray[1]= "Stefan"; myArray[2]= "Koch"; JavaScript arrays are really flexible. You do not have to bother

about the size of the array - its size is being set dynamically. If you write myArray[99]= "xyz" the size of the array get 100 elements (a JavaScript array can only grow - it hasn't got the ability to shrink. So keep your arrays as small as possible.).

It doesn't matter if you store numbers, strings or other objects in an array

Page 1170: Dotnet Stream

1170©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.

String-object

The string object offers properties and methods to perform a variety of manipulations on a given string.

The Math object provides those functions and methods necessary to perform mathematical calculations, from PI value to trigonometric functions.

Page 1171: Dotnet Stream

1171©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.

Methods of the string Object

anchor() Surrounds the string with an anchor tag

big() Surrounds the string with the BTML BIG tag

charAt() Given an index as an argument, returns the character at the specified index

strike() Surrounds the string with the HTML strike tag

substring() Given two indexes, returns the substring starting at the first index and ending with the character before the last index. If the second index is greater , the substring starts with the second index and ends with the character before the first index.

toLowerCase() Makes the entire string lowercase

toUpperCase() Makes the entire string uppercase

split() Returns an array of strings by splitting the string into substrings at a separator passed to the method as the argument.

Page 1172: Dotnet Stream

1172©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.

Methods of Math Object

random() Returns a random no between zero and one

round() Rounds a no to the nearest integer

sin() Calculates the sine of a no

sqrt() Calculates the square root of a no

pow() Calculates the value of one no to the power of a second no- takes two arguments

Min() Returns the least of two nos

Log() Calculates the natural logarithm of a no

Floor() Returns the next integer less than or equal to a number

Page 1173: Dotnet Stream

1173©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.

Document Objects Document :-Contains information about the

current document, and provides methods for displaying HTML output to the user.

The following are event handlers for the document object.

onClick , onDblClick , onKeyDown , onKeyPress , onKeyUp, onMouseDown , onMouseUp

Page 1174: Dotnet Stream

1174©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.

Window Objects Frame A window that can display

multiple,independently scrollable frames on a single screen, each with its own distinct URL.

History Contains an array of information on the URLs that the client has visited within a window.

Location Contains information on the current URL. screen Contains properties describing the display

screen and colors. Window Represents a browser window or frame. This

is the top-level object for each document, Location, and History object group.

Page 1175: Dotnet Stream

1175©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.

WindowCreating windows

• Opening new browser windows is a great feature of JavaScript. You can either load a new document (for example a HTML-document) to the new window or you can create new documents (on-the-fly).

<html><head>

<script language="JavaScript">

<!-- hidefunction openWin() {

myWin= open("bla.htm");

}// -->

</script></head>

<body><form>

<input type="button" value="Open new window" onClick="openWin()">

</form></body>

</html>

function openWin2()

{

myWin= open("bla.htm", "displayWindow", "width=400,height=300,status=no,toolbar=no,menubar=no");

}

Page 1176: Dotnet Stream

1176©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.

Window

The name of a window As you have seen we have used three arguments for opening a window:

myWin= open("bla.htm", "displayWindow", "width=400, height=300, status=no, toolbar=no,menubar=no");

What is the second argument for? This is the name of the window. We have seen how to use the target-property earlier. If you know the name of an existing window you can load a new page to it with <a href="bla.html" target="displayWindow">

Here you need the name of the window (if the window does not exist, a new window is created through this code). Please note that myWin is not the name of the window. You can just access the window through this variable. As this is a normal variable it is only valid inside the script in which it is defined. The window name (here displayWindow) is a unique name which can be used by all existing browser windows.

Page 1177: Dotnet Stream

1177©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.

Window

Closing windows You can close windows through JavaScript. For this you

need the close() method. Let's open a new window as shown before. In this window we load the following page:

<html><script language="JavaScript">

<!-- hidefunction closeIt() {

window.close();}

</script></html>

Page 1178: Dotnet Stream

1178©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.

Form Objects

Button A push button on an HTML form. Checkbox A checkbox on an HTML form. FileUpload A file upload element on an HTML form. Form Lets users input text and make choices

from Form elements such as checkboxes, radio buttons, and selection lists.

Hidden A Text object that is suppressed from form display on an HTML form.

Password A text field on an HTML form that conceals its value by displaying asterisks (*).

Radio A set of radio buttons on an HTML form. Reset A reset button on an HTML form. Select A selection list on an HTML form. Submit A submit button on an HTML form. Text A text input field on an HTML form. Textarea A multiline input field on an HTML form.

Page 1179: Dotnet Stream

1179©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.

Form Objects Contd…Validating form input

• Forms are widely used on the Internet. The form input is often being sent back to the server or via mail to a certain e-mail account. But how can you be certain that a valid input was done by the user? With the help of JavaScript the form input can easily be checked before sending it over the Internet.

• Setting the focus to a certain form-element with the help of the focus() method you can make your form a little bit more user-friendly. You can define which element is in focus at the beginning. You can do this with the following piece of script:

function setfocus() {

document.first.text1.focus();}

• This script would set the focus to the first text-element in the script I have shown above. You have to specify the name of the whole form - which is called first here - and the name of the single form element - here text1. If you want to put the focus on this element when the page is being loaded you can add an onLoad-property to your <body> tag. This looks like this:

<body onLoad="setfocus()">

Page 1180: Dotnet Stream

1180©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.

Form Objects Contd…

We can extend this with the following code:function setfocus() { document.first.text1.focus(); document.first.text1.select();}

Evaluating a form using the button element<HTML>

<HEAD><TITLE>button Example</TITLE><SCRIPT LANGUAGE="JavaScript">

<!-- HIDE FROM OTHER BROWSERSfunction calculate(form) {

form.results.value = eval(form.entry.value);}// STOP HIDING FROM OTHER BROWSERS -->

</SCRIPT></HEAD>

Page 1181: Dotnet Stream

1181©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.

Form Objects Contd…

<BODY><FORM METHOD=POST>

Enter a JavaScript mathematical expression:<INPUT TYPE="text" NAME="entry"

VALUE=""><BR>The result of this expression is:<INPUT TYPE=text NAME="results“

onFocus="this.blur();"><BR><INPUT TYPE="button" VALUE="Calculate"

onClick="calculate(this.form);"></FORM></BODY>

</HTML

Page 1182: Dotnet Stream

1182©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

Events and event handlers are very important for JavaScript programming. Events are mostly caused by user actions. If the user clicks on a button a Click-event occurs. If the mouse pointer moves across a link a MouseOver-event occurs. There are several different events.

We want our JavaScript program to react to certain events. This can be done with the help of event-handlers. A button might create a popup window when clicked. This means the window should pop up as a reaction to a Click-event. The event-handler we need to use is called onClick.

<form><input type="button" value="Click me"

onClick="alert('Yo')"></form>

Page 1183: Dotnet Stream

1183©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 <html>

<head><title> Events </title><script>

<!--hide from other browsersvar name=“”;//stop hiding from other browsers-->

</script></head><body onLoad=“name=prompt(‘enter your name:’,’Name”);

alert (‘Greetings’ + name+’, welcome to my page!’);”onUnload= “alert(‘goodbye’+name+’,sorry to see you

go!’);”><img src=“title.gif”>

</body></html>

Page 1184: Dotnet Stream

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

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

Web Application Development Web Application Development with ASP.NET 2.0with ASP.NET 2.0

COE – Current Technologies

Page 1185: Dotnet Stream

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

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

ASP.NET Session TopicsASP.NET Session Topics

Page 1186: Dotnet Stream

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

ASP.NET Discussion Topics

Introduction• An E-Commerce Web Site scenario• ASP.NET Architecture• Web Application Development• Web Application folders

Features added in ASP.NET2.0Features added in ASP.NET2.0

Page 1187: Dotnet Stream

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

ASP.NET Discussion Topics

Web Forms• ASP.NET Process• Application Lifecycle and Events• Page Life cycle• Compilation Life cycle• ASP.NET Objects

Master Pages Themes

• Skins• Style Sheets

Features added in ASP.NET2.0Features added in ASP.NET2.0

Page 1188: Dotnet Stream

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

ASP.NET Discussion Topics

ASP.NET Controls• HTML Controls• Standard Server Controls• Login Controls• Validation Controls• Navigation

Advanced Controls• User Controls• Composite Controls• Custom Controls• Web parts

Features added in ASP.NET2.0Features added in ASP.NET2.0

Page 1189: Dotnet Stream

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

ASP.NET Discussion Topics

Server Side Data Access• Data Binding Model

Data Controls• Data Source Controls• Data Bound Controls

DataGrid GridView DataList DetailsView FormView Repeater

Features added in ASP.NET2.0Features added in ASP.NET2.0

Page 1190: Dotnet Stream

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

ASP.NET Discussion Topics

Web Application Management • State Management

Client Side state Management Server Side state Management

• Caching Techniques OutputCaching FragmentCaching DataCaching PostCacheSubstitution

• Tracing and Logging• Exception Handing

ErrorPages CustomExceptions

Features added in ASP.NET2.0Features added in ASP.NET2.0

Page 1191: Dotnet Stream

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

ASP.NET Discussion Topics

Web Site Management • Web site Configuration

Web Administration Tool

• Security Authentication

Windows Forms Digest

Authorization Allow/Roles/Verbs

• Health Monitoring• Deployment

Features added in ASP.NET2.0Features added in ASP.NET2.0

Page 1192: Dotnet Stream

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 ASP.NETIntroduction to ASP.NET

Page 1193: Dotnet Stream

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

ASP.NET 2.0 FeaturesC

on

trols

Pag

eFra

mew

ork

Serv

ices

an

d A

PIs

DataControls

LoginControls

Web PartsOther NewControls

Master PagesThemes

and SkinsImproved

Client ScriptingCompilation

& Localization

MembershipRole

ManagementProfiles Configuration

SiteMaps

HealthMonitoring

Other NewServices

Page 1194: Dotnet Stream

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

ASP.NET 2.0 Features

ASP.NET “Page Framework” Features

Master PagesMaster Pages Themes/SkinsThemes/Skins Adaptive UIAdaptive UILocalizationLocalization

ASP.NET “Building Block” APIs

MembershipMembership Role ManagerRole Manager PersonalizationPersonalization

Site NavigationSite Navigation Database CachingDatabase Caching ManagementManagement

ASP.NET “Control Buckets”

SecuritySecurity Web PartsWeb PartsDataData NavigationNavigation

Page 1195: Dotnet Stream

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

ASP.NET Web Application Scenario• An E-Commerce Web

Site scenario Consumer viewpoint

Website interface to view product listing, description and make orders.

Retailer viewpoint:

Provide services to validate credit card payment and deliver products through courier service.

Page 1196: Dotnet Stream

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

ASP.NET Web Architecture

“A web application in ASP.NET is a collection of pages, controls, code modules, and services all running under a single web server application directory (usually IIS) “

“A web application in ASP.NET is a collection of pages, controls, code modules, and services all running under a single web server application directory (usually IIS) “

Page 1197: Dotnet Stream

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

ASP.NET Layered Architecture

Presentation TierPresentation Tier

Business Logic TierBusiness Logic Tier

Data TierData Tier

Graphic Files

Graphic Files

UI Pages(.htm)

UI Pages(.htm)

XML Web Services(.asmx)

XML Web Services(.asmx)

User Controls(.ascx)

User Controls(.ascx)

Code-Behind File(.aspx.vb or .aspx.cs)

Code-Behind File(.aspx.vb or .aspx.cs)

ProxyProxy ADO.NETADO.NET

.NET Objects.NET

Objects

Data Source

COM+ServicesCOM+

ServicesCOM

ObjectsCOM

Objects

RCWRCW

Web Form (.aspx)

Web Form (.aspx)

Page 1198: Dotnet Stream

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

ASP.NET Namespaces

ASP.NET Namespaces

System.WebSystem.Web

ConfigurationConfiguration SessionStateSessionState

CachingCaching SecuritySecurity

ServicesServices

DescriptionDescription

DiscoveryDiscovery

ProtocolsProtocols

UIUI

HtmlControlsHtmlControls

WebControlsWebControls

Page 1199: Dotnet Stream

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

ASP.NET Web Application Development

Web Site Options:

Choose Installed Templates

ASP.NET Web Site

Choose Locations:

File System:

An Web Application in VS2005

runs in a default development Server using

any ports available. The application itself is

stored in the file system which could be later

copied into Web Server during deployment.

HTTP:

To work under the Web Server

FTP:

To work with web applications and

code that reside in a remote server

2

1

1

2

Page 1200: Dotnet Stream

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

ASP.NET Web site Development

Code Behind Model

Default.aspx -HTML File

Default.aspx.cs -C# File

1

2

1

2

Page 1201: Dotnet Stream

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

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

ASP.NET Web FormsASP.NET Web Forms

Page 1202: Dotnet Stream

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

ASP.NET Web Forms

Topics for Discussion• ASP.NET Web Application Files and Folders• ASP.NET Process• Application Lifecycle and Events• Page Life cycle• Compilation Life cycle• ASP.NET Objects

Page 1203: Dotnet Stream

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

ASP.NET Application file extensionsType Extension

Solution .sln

Project File .csproj

ASP.NET Page File

.aspx

.aspx.cs (code behind)

ASP.NET User Control File

.ascx

.ascx.cs (code behind)

ASP.NET WEB Service asmxasmx.cs (code behind)

Library File .cs

Configuration File .config

Page 1204: Dotnet Stream

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

ASP.NET Application folders

Folder Description

App_Browsers Contains browser definitions (.browser files) that ASP.NET uses to identify individual browsers and determine their capabilities..

App_Code Contains source code for utility classes and business objects (for example, .cs, .vb, and .jsl files)

App_Data Contains application data files including MDF files, XML files, as well as other data store files.

App_GlobalResources

Contains resources (.resx and .resources files) that are compiled into assemblies with global scope

Page 1205: Dotnet Stream

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

ASP.NET Application foldersFolder Description

App_LocalResources

Contains resources (.resx and .resources files) that are associated with a specific page, user control, or master page in an application.

App_Themes Contains a collection of files (.skin and .css files, as well as image files and generic resources) that define the appearance of ASP.NET Web pages and controls..

App_WebReferences

Contains reference contract files (.wsdl files), schemas (.xsd files), and discovery document files (.disco and .discomap files) defining a Web reference for use in an application.

Page 1206: Dotnet Stream

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

ASP.NET Process Model with IIS

ASP.NET Process Model• The IIS (INETINFO.EXE), runs as a System Process.• ASP.NET applications are created by creating a new Virtual

Directory and specifying an Application Name.• Standard IIS ISAPI filtering is used to route all ASP.NET requests to

the ISAPI filter ASPNET_ISAPI.DLL.• ASPNET_ISAPI.DLL routes all requests to a single instance of the

worker process, ASPNET_WP.EXE, through a named pipe.• ASP.NET applications run side-by-side in partitions within the

worker process known as “App Domains”.

Page 1207: Dotnet Stream

1207©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.

Application Life cycle

Steps in Application Life Cycle• User requests an application resource from the Web server • ASP.NET receives the first request for the application. • ASP.NET core objects are created for each request. • An HttpApplication object is assigned to the request• The request is processed by the HttpApplication pipeline

Page 1208: Dotnet Stream

1208©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.

Application Life cycle

Application Life cycleThe following events are executed by the

HttpApplication class while the request is processed. • Validate the request, which

examines the information sent by the browser and determines whether it contains potentially malicious markup

• Perform URL mapping, if any URLs have been configured in the UrlMappingsSection section of the Web.config file.

• Based on the file name extension of the requested resource ,select a class that implements IHttpHandler to process the request

• Call the ProcessRequest method of the appropriate IHttpHandler class for the request.

Page 1209: Dotnet Stream

1209©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.

Application Life cycle

Global.asaxDuring the application life cycle, the application raises events.

• To handle application events or methods, create a file named Global.asax in the root directory of the application.

• ASP.NET compiles it into a class derived from the HttpApplication class, and then uses the derived class to represent the application.

An instance of HttpApplication processes only one request at a time.

ASP.NET automatically binds application events to handlers in the Global.asax file using the naming convention Application_event, such as Application_BeginRequest.

The Application_Start and Application_End methods are special methods that do not represent HttpApplication events.

ASP.NET calls them once for the lifetime of the application domain, not for each HttpApplication instance.

HttpApplication.InitCalled once for every instance of the HttpApplication class after all modules have been created.

Page 1210: Dotnet Stream

1210©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.

Page Life cycle

ResponseResponse

ResponseResponsePagePageClassClass

Instantiate, process and Instantiate, process and renderrender

Gen’dPageClassFile

GenerateGenerate

InstantiateInstantiate

ParseParseASPXASPX

EngineEngine

ASPXFile

RequestRequest

RequestRequest

Code-Code-behindbehindclassclassfilefile

ASPXFile

Page Development Dynamic Compilation

Page 1211: Dotnet Stream

1211©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.

Compilation Life cycle

Item Description

App_GlobalResources The application's global resources are compiled and a resource assembly is built. Any assemblies in the application's Bin folder are linked to the resource assembly.

App_WebResources Proxy types for Web services are created and compiled. The resulting Web references assembly is linked to the resource assembly if it exists

Profile properties defined in the Web.config file

If profile properties are defined in the application's Web.config file, an assembly is generated that contains a profile object.

Page 1212: Dotnet Stream

1212©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.

Compilation Life cycle

Item Description

App_Code Source code files are built and one or more assemblies are created. All code assemblies and the profile assembly are linked to the resources and Web references assemblies if any.

Global.asax The application object is compiled and linked to all of the previously generated assemblies.

Page 1213: Dotnet Stream

1213©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.

Compilation Life cycle

Item Description

App_LocalResources If the folder containing the requested item contains an App_LocalResources folder, the contents of the local resources folder are compiled and linked to the global resources assembly.

Individual Web pages (.aspx files), user controls (.ascx files), HTTP handlers (.ashx files), and HTTP modules (.asmx files)

Compiled as needed and linked to the local resources assembly and the top-level assemblies

Themes, master pages, other source files

Skin files for individual themes, master pages, and other source code files referenced by pages are compiled when the referencing page is compiled.

Page 1214: Dotnet Stream

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

ASP.NET Page Directives

Directive Description

Assembly Links an assembly to the Page or user control for which it is associated.

Control Page directive meant for use with user controls (.ascx).

Implements

Implements a specified .NET Framework interface.

Import Imports specified namespaces into the Page or user control.

Master Enables you to specify master page–specific attributes and values to use when the page parses or compiles. This directive can be used only with master pages (.master).

MasterType

Associates a class name to a Page in order to get at strongly typed references or members contained within the specified master page.

Page 1215: Dotnet Stream

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

ASP.NET Page Directives

Directive Description

OutputCache Controls the output caching policies of a Page or user control.

Page Enables you to specify page specific attributes and values to use when the page parses or compiles. This directive can be used only with ASP.NET pages (.aspx).

PreviousPageType

Enables an ASP.NET page to work with a postback from another page in the application.

Reference Links a Page or user control to the current Page or user control.

Register Associates aliases with namespaces and class names for notation in custom server control syntax.

Page 1216: Dotnet Stream

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

ASP.NET Objects

Types of ASP.NET Objects• Request• Response• Server• Application• Session

Page 1217: Dotnet Stream

1217©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.

Request Object Properties and Methods• Application Path – Gets the path of the page.

• Path – Gets the Path and Name of the Page.

• PhysicalApplicationPath – Gets the full Path of the Page in physical form.

• Browser – Provides Access to the browser Object.

• Cookies – Provides access to the cookies collection.

• IsSecureConnection – Provides Info on the HTTP Connection.

• RequestType – Get or Post.

• QueryString-Gets Parameters Passed to the Page using Get.

• URL-Gets the Complete Address as submitted by the Browser.

• RawUrl-Gets the complete address Without Domain name and protocol.

• UserHostName-Gets the name of the Machine Requesting the page.

• UserHostAddress-Gets the IP Address of the machine requesting the page.

• UserLangage-Gets the language settings set by the browser.

Request Object

Page 1218: Dotnet Stream

1218©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.

Response Object Properties and Methods• Buffer-Default is True.• ContentType-Specifies the MIME type.• Cookies-Provides access to the cookies collection.• Clear()-Buffer will be emptied and contents discarded.• Flush()-All the HTML in the buffer is sent to the browser.• End()-Ends page execution and sends HTML in the buffer to the

browser.

Response Object

Page 1219: Dotnet Stream

1219©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.

Server Object Properties and Methods• MachineName- Gets the Windows name of the machine that

ASP.NET is Running on.• ScriptTimeOut- Gets /Sets the amount of time before an ASP.NET

page time out.• HTMLEncode() – Takes a string and Encodes it to be displayed in

the browser.• HTMLDecode()- Contrary to HTMLEncode().• MapPath()- Takes a Virtual Path and Returns the Complete Physical

Path.

Server Object

Page 1220: Dotnet Stream

1220©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.

Application Object Properties and MethodsUsed to persist state at a Web Application level.

• Lock()- Used to lock all Application level variables.• UnLock()- Used to unlock all Appliction level variables for

processing

Application Object

Page 1221: Dotnet Stream

1221©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.

Session Object Properties and MethodsUsed to persist state at user level.

• Abandon()-Ends the current session.• Clear()- Removes all information from the session.• IsNewSession-Specifies if the current request amounts to a new

session.• TimeOut-Period of Idle time in minutes before a session expires.

Session Object

Page 1222: Dotnet Stream

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.

Master PagesMaster Pages

Page 1223: Dotnet Stream

1223©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.

Master Pages provides with an easy method of creating a “Consistent look and feel”

for a Web site.

Master Pages provides with an easy method of creating a “Consistent look and feel”

for a Web site.

Site.master default.aspx

Content

http://.../default.aspx

Content-PlaceHolder

ASP.NET Master Pages

Page 1224: Dotnet Stream

1224©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 for Discussion:• Need for Master Pages• Building a Master Page• Creating a content page• Configuring master files• Specifying Page titles• Dynamically loading master pages• Exposing properties and methods of a master page• Nested Master Pages• Container specific master pages• Event Ordering b/w master and content pages

ASP.NET Master Pages

Page 1225: Dotnet Stream

1225©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.

Header

CommonPage Items

Need for Master Pages

Footer

Page 1226: Dotnet Stream

1226©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.

Problems with Maintaining Consistent Page Layout• Most sites follow a consistent layout

Header, footer, navigation Site ‘structure’ is repeated on most pages

• Today lots of code and markup duplication Makes site updates very challenging to coordinate

Current Solutions Available• User Controls

Problem: Unbalanced html tags (example: tables) Problem: Lots of different controls on a page (adds more pieces

to puzzle)• Tool-based solution

Problems: Done at design-time, requires merging and modifying every file

Problems: Forces you to stick with a single tool

Need for Master Pages

Page 1227: Dotnet Stream

1227©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.

Master Pages Enable Flexible and Reusable UI layout

Master Pages Can Contain:• Page markup• Content (Header, Footer, HTML, ASP.NET controls)• Replaceable regions for specialized content

Key Benefits:• Consistent page layout• Shared UI & code elements• Can be defined both programmatically and declaratively

Master Pages-The Solution

Page 1228: Dotnet Stream

1228©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.

Creating Master Pages

Create a master page with .master extension

Define a master directive:• <%@ master .. %>

Add content:• Can contain any html or control page content• Define replaceable place-holder regions:

Use an <asp:contentplaceholder> control Add default content within it (optional)

• At runtime, the ASP.NET engine combines these elements into a single page for the end user

Page 1229: Dotnet Stream

1229©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.

Creating Master Pages

1

1 Opting for Code Behind Model

Page 1230: Dotnet Stream

1230©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.

Creating Master Pages

1

2

Master Page File

Content Place Holders for Content Pages

1

2

Page 1231: Dotnet Stream

1231©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.

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="ShopMaster.master.cs" Inherits="ShopMaster" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>My Master Page</title></head><body> <form id="form1" runat="server"> <table cellpadding="3" border="1"> <tr bgcolor="silver"> <td colspan="2"> <h1>My Shopping Home Page</h1> </td></tr>

Creating Master Pages

Page 1232: Dotnet Stream

1232©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.

<tr><td> <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> </td> <td> <asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server"> </asp:ContentPlaceHolder> </td> </tr> <tr> <td colspan="2"> Copyright 2007 - My Company </td> </tr> </table> </form></body></html>

Creating Master Pages

Page 1233: Dotnet Stream

1233©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.

Creating Content Pages

Create an ASP.NET page (.aspx extension)

On the page directive:• <%@ page masterpagefile= %> attribute to reference master• Set the title attribute <%@ Page title=“Home Page” %>

Optionally add content to override the master:• Only <asp:content> controls or server-side script allowed• <asp:content> controls replace regions in the master:

The contentplaceholderid identifies master’s region <asp:content> controls can contain any page content

Page 1234: Dotnet Stream

1234©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.

Creating Content Pages

1

Opting for Code Behind ModelSelecting a particular Master page

1

Page 1235: Dotnet Stream

1235©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.

Creating Content Pages

1

Selecting a particular Master page1

Page 1236: Dotnet Stream

1236©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.

<%@ Page Language="C#" MasterPageFile="~/ShopMaster.master" AutoEventWireup="true" CodeFile="MyFirContent.aspx.cs" Inherits="MyFirContent" Title="Untitled Page" %><asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"><b>Enter your name:</b><br /> <asp:Textbox ID="TextBox1" runat="server" /> <br /> <br /> <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" /><br /> <br /> <asp:Label ID="Label1" runat="server" /></asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server"><asp:Image ID="Image1" runat="server" ImageUrl="logo.png" Width=100 Height=100 /></asp:Content>

Creating Content Pages

Page 1237: Dotnet Stream

1237©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.

<%@ page masterpagefile=“~/my.master” %><%@ master %>

my.mastermy.master

Header

Footer

Navigation

<asp:contentplaceholder Id=“MainContent”> Here is the content that replaces …</asp:contentplaceholder>

default.aspx (content-page)default.aspx (content-page)

<%@ master %>

my.mastermy.master

Header

Footer

Navigation

<asp:contentplaceholder Id=“MainContent”> Here is my basic default content </asp:contentplaceholder>

<%@ master %>

my.mastermy.master

Footer

Navigation

<asp:contentplaceholder Id=“MainContent”> Here is my basic default content </asp:contentplaceholder>

Header

<%@ page masterpagefile=“~/my.master” %><%@ master %>

my.mastermy.master

Header

Footer

Navigation

<asp:contentplaceholder Id=“MainContent”> Here is my basic default content </asp:contentplaceholder>

default.aspx (content-page)default.aspx (content-page)

<asp:content contentplaceholderid=“MainContent”> Here is the content

that replaces …/asp:content>

<%@ page masterpagefile=“~/my.master” %><%@ master %>

my.mastermy.master

Header

Footer

Navigation

<asp:contentplaceholder Id=“MainContent”> Here is my basic default content </asp:contentplaceholder>

default.aspx (content-page)default.aspx (content-page)

<asp:content contentplaceholderid=“MainContent”> Here is the content

that replaces …/asp:content>

<%@ page masterpagefile=“~/my.master” %><%@ master %>

MyShop.masterMyShop.master

Header

Footer

Navigation

<asp:contentplaceholder Id=“MainContent”> Here is my basic default content </asp:contentplaceholder>

default.aspx (content-page)default.aspx (content-page)

<asp:content contentplaceholderid=“MainContent”> Here is the content

that replaces …/asp:content>

<%@ page masterpagefile=“~/my.master” %>

Default.aspx (content-page)Default.aspx (content-page)

<asp:content contentplaceholderid=“MainContent”> Here is the content

that replaces …/asp:content>

During Runtime, the ASP.NET engine combines both master and content pages into a single page for the end user

Runtime Behavior of Master Pages

Page 1238: Dotnet Stream

1238©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.

<configuration> <system.web> <pages masterPageFile="~/MyShopMaster.master" /> </system.web></configuration>

<configuration> <location path="AdministrationArea"> <system.web> <pages masterPageFile="~/ShopAdmin.master" /> </system.web> </location></configuration>

Specifying the master page in the Web.config file Specifying the master page in the Web.config file

Specifying the master page for a specific folder in the Web.config file Specifying the master page for a specific folder in the Web.config file

Configuring Master Pages

Page 1239: Dotnet Stream

1239©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.

protected void Page_LoadComplete(object sender, EventArgs e) { Master.Page.Title = "This page was generated on: " +

DateTime.Now.ToString(); }

protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { Label1.Text = System.Guid.NewGuid().ToString(); } }

Your GUID number from the master page is:<br /> <asp:Label ID="Label1" runat="server" /></b><p> protected void Page_LoadComplete(object sender, EventArgs e) { Label1.Text = (Master.FindControl("Label1") as Label).Text; }

Coding a custom page title for the content page- MyFirContent.aspx.csCoding a custom page title for the content page- MyFirContent.aspx.cs

Working with Controls and Properties from the Master PageA master page that creates a GUID on the first request –MyShopMaster.aspx.cs

Working with Controls and Properties from the Master PageA master page that creates a GUID on the first request –MyShopMaster.aspx.cs

Getting at the Label’s Text value in the content page-MyFirContent.aspxGetting at the Label’s Text value in the content page-MyFirContent.aspx

Working with Master Pages

Page 1240: Dotnet Stream

1240©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.

Nesting Master Pages

Master-pages can be nested• Enables a master to master relationship

Useful when a site enforces an overall layout and defines sub-layouts within• Content Pages can also be Master Pages. • It is possible to derive a Master page from another Master

Page. • Content Pages would then derive from the appropriate

section master for the section the Content Page belongs to.

ASPXASPX MASTER (ASPX Content-page)MASTER (ASPX Content-page)

MASTER (MASTER)MASTER (MASTER)

MASTER (ASPX Content-page)MASTER (ASPX Content-page)

Page 1241: Dotnet Stream

1241©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.

Event Ordering between Master and Content Pages• Master page child controls initialization• Content page child controls initialization• Master page initialization• Content page initialization• Content page load• Master page load• Master page child controls load• Content page child controls load

Event ordering

Page 1242: Dotnet Stream

1242©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.

Container Specific Master Pages• Web applications may be viewed in a variety of Containers

(Browsers). Depending upon the viewing container used by the end user, the ASP.NET engine pulls the appropriate master file.

• Build container specific master pages to provide end users with the best possible viewing experience by taking advantage of the features of specific containers

<%@ Page Language="C#" MasterPageFile="~/MasterShop.master" Mozilla:MasterPageFile="~/MozillaShop.master"

Opera:MasterPageFile="~/OperaShop.master" %>

<%@ Page Language="C#" MasterPageFile="~/MasterShop.master" Mozilla:MasterPageFile="~/MozillaShop.master"

Opera:MasterPageFile="~/OperaShop.master" %>

Container Specific Master Pages

Page 1243: Dotnet Stream

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.

Themes and SkinsThemes and Skins

Page 1244: Dotnet Stream

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

ASP.NET Themes and Skins“Themes define visual styles for web pages”

“Themes can be applied at the application, page or a server control level”

Topics for discussion:Creating a theme

• Creating Folder Structure• Creating a skin• Creating a CSS• Creating images folder

Applying theme to• A aspx page• An entire application

Removing themes from• Server Controls• Web Pages

Themes and Master PagesAssigning themes to pages dynamically

Page 1245: Dotnet Stream

1245©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.

Current Situation

Web developers want to:• Customize the visual appearance of a web site or page • Enforce a look-’n’-feel for the site

Some of today’s approaches and problems include:• Inline styles

Developer must touch every control More difficult to set styles on dynamic controls

• CSS style-sheet More difficult to set styles on dynamic controls Does not work on control properties, collection or templates

Page 1246: Dotnet Stream

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

ASP.NET Themes and Skins

Themes enable rich customization of UI

• Enables consistent look-’n’-feel for controls in an application

• Enables easy co-operation of developer + designer

Themes can contain:

• Skins: Properties to set on one or more server control types

• Styles: CSS stylesheet files

• Resources: Images

Themes can be set both declaratively and programmatically

Can be used both as a pre-step and post-step operation

• “Theme” attribute applies after control created (total control)

• “StyleSheetTheme” attribute applies before control (control override)

Page 1247: Dotnet Stream

1247©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.

Creating the Proper Folder Structure• Create a Theme folder by right-clicking on the project in Visual

Studio and selecting Add Folder@Theme.• Within the App_Themes folder, Create an additional theme folder

for each and every theme to use in application• Each theme folder must contain the elements of the theme, which

can include the following: A single skin file CSS files Images

Creating folder structure

Page 1248: Dotnet Stream

1248©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.

A skin is a definition of styles applied to the server controls in a ASP.NET page. • Skins can work in conjunction with CSS files or images. • To create a theme to use in your ASP.NET applications, you use just

a single skin file in the theme folder. • The skin file can have any name, but it must have a .skin file

extension• The control definitions must contain the runat=”server” attribute. • No ID attribute is specified in the skinned version of the control

<asp:Label runat="server" ForeColor="#004000" Font-Names="Verdana" Font-Size="X-Small" /> <asp:Textbox runat="server" ForeColor="#004000" Font-Names="Verdana" Font-Size="X-Small" BorderStyle="Solid" BorderWidth="1px" BorderColor="#004000" Font-Bold="True" />

<asp:Label runat="server" ForeColor="#004000" Font-Names="Verdana" Font-Size="X-Small" /> <asp:Textbox runat="server" ForeColor="#004000" Font-Names="Verdana" Font-Size="X-Small" BorderStyle="Solid" BorderWidth="1px" BorderColor="#004000" Font-Bold="True" />

Creating Skin

Page 1249: Dotnet Stream

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

• ASP.NET pages are routinely made up of HTML server controls, raw HTML, or even raw text

• For a theme that goes beyond the server controls, define the theme style so that HTML server controls, HTML, and raw text are all changed according to the theme.

• Achieve this with a CSS file within Themes folder. To create a comprehensive theme with this dialog, you define

each HTML element that might appear in the ASP.NET page.

Creating Style

Page 1250: Dotnet Stream

1250©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.

• A lot of controls use images to create a better visual appearance. • The first step in incorporating images into server controls that

consistently use themes is to create an Images folder within the Themes folder

Creating Images

Page 1251: Dotnet Stream

1251©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.

Applying a Theme to a Single ASP.NET PageApplying a Theme to a Single ASP.NET Page

Applying a Theme to an Entire ApplicationApplying a Theme to an Entire Application

Removing Themes from Server ControlsRemoving Themes from Server Controls

Removing Themes from Web PagesRemoving Themes from Web Pages

<configuration> <system.web> <pages theme=“Fall” /> </system.web></configuration>

<%@ Page Language=“C#" Theme=“Fall" %>

<asp:Textbox ID="TextBox1" runat="server" BackColor="#000000" ForeColor="#ffffff" EnableTheming="false"/>

<%@ Page Language=“C#" EnableTheming="False" %>

Applying and Removing Themes

Page 1252: Dotnet Stream

1252©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.

• If the content page that is using this master page doesn’t make any specification on theming (it does not use the EnableTheming attribute)

• Even if the EnableTheming value is set in the content page, any value that is specified in the master page takes precedence.

<%@ Master Language=“C#" EnableTheming="false" %><%@ Master Language=“C#" EnableTheming="false" %>

Applying and Removing Themes

Page 1253: Dotnet Stream

1253©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.

protected void Page_PreInit(object sender, System.EventArgs e) { Page.Theme = Request.QueryString["ThemeChange"]; }

Assigning the Page’s Theme ProgrammaticallyAssigning the Page’s Theme Programmatically

Assigning a Control’s SkinID ProgrammaticallyAssigning a Control’s SkinID Programmatically

protected void Page_PreInit(object sender, System.EventArgs e) { TextBox1.SkinID = "TextboxDashed"; }

Assigning Themes dynamically

Page 1254: Dotnet Stream

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

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

ASP.NET ControlsASP.NET Controls

Page 1255: Dotnet Stream

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

ASP.NET Controls

Topics for discussion:• HTML Controls• Server Side Controls• Login Controls• Validation Controls• Navigation

Page 1256: Dotnet Stream

1256©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.

Post Back Mechanism

ASP.NET Server AppASP.NET Server App

Mapping a browser event to server event

Click!Click!Click!Click!

Button1

Control

Control

Control

Button1 .RaisePostBackEvent().RaisePostBackEvent()

callscalls OnClick() OnClick()

invokes event handlerinvokes event handlerButton1_Click()Button1_Click()

Controls registered to receive Controls registered to receive post-back event notificationpost-back event notification

IPostBackEventHandlerIPostBackEventHandler

HTTP form postHTTP form post

Page 1257: Dotnet Stream

1257©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.

Controls Rendering

Page/Control ProcessingFirst load

InitInit

LoadLoad

PreRenderPreRender

SaveViewStateSaveViewState

RenderRender

DisposeDispose

Each control instantiated, set to initial state, added to Each control instantiated, set to initial state, added to control treecontrol tree

User code runs, tests User code runs, tests !IsPostBack!IsPostBack condition to data condition to data bind 1bind 1stst values valuesCreateChildControls() ensures controls are ready to CreateChildControls() ensures controls are ready to renderrenderControls save current state (if different than initial Controls save current state (if different than initial values)values)

Each control renders itself to the ResponseEach control renders itself to the Response

Pages and all controls are disposedPages and all controls are disposed

Page 1258: Dotnet Stream

1258©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.

Postback Rendering

Page/Control ProcessingPost back

InitInit

LoadLoad

PreRenderPreRender

SaveViewStateSaveViewState

RenderRender

DisposeDispose

Last state of the controls is restored from ViewState Last state of the controls is restored from ViewState valuesvalues

Posted data (in the HTTP form) is passed to its Posted data (in the HTTP form) is passed to its associated controlassociated controlEvents are fired for controls in tree order, except the Events are fired for controls in tree order, except the event that caused the post. It’s fired last.event that caused the post. It’s fired last.

LoadViewStateLoadViewState

Postback dataPostback data

Postback eventsPostback events

Page 1259: Dotnet Stream

1259©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.

Postback and ViewStateHello2.aspx.csIf (!IsPostBack) …First Request

Response__VIEWSTATE = "dDwt…" <Input id="TextBox1">

Minder Chen

Post back to the same page

__VIEWSTATE = "dDwt…" Textbox1.Text = "Minder Chen"

States of a page is maintained via the ViewState between the Postback

Hello2.aspx

<asp:textbox id="TextBox1" runat="server" />

__VIEWSTATE = "dDwt…"<Input id="TextBox1" value="Minder Chen" …>

ResponseDefault value

Page 1260: Dotnet Stream

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

ASP.NET HTML Controls

HTML ControlsHTML Controls

Page 1261: Dotnet Stream

1261©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.

Features of HTML Controls

“HTML server controls are HTML elements containing attributes that make them programmable in server code”

HTML server controls offer the following features:• An object model that you can program against on the server using

familiar object-oriented techniques. • A set of events for which you can write event handlers and the

event is handled in server c• The ability to handle events in client script.• Automatic maintenance of the control's state. • Interaction with ASP.NET validation controls • Data binding to one or more properties of the control.• Support for styles.

Page 1262: Dotnet Stream

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

HTML Controls

Input Control

Button

Reset

Submit

Text

File

Password

CheckBox

Radio

Hidden

SelectCommand

InsertCommand

DeleteCommand

ConnectionConnectionHTML ControlsHTML Controls

Text AreaText Area

ImageImage

TableTable

SelectSelect

HorizontalRule,DivHorizontalRule,Div

InputInput

Page 1263: Dotnet Stream

1263©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.

Server Side Controls

Server Side ControlsServer Side Controls

Page 1264: Dotnet Stream

1264©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.

Features of Server Side Controls

“Web server controls do not necessarily map one-to-one to HTML server controls”

Server controls offer the following features:

• A rich object model that provides type-safe programming capabilities.

• Automatic browser detection.

• Ability to define your own layout for the control using Templates.

• The ability to specify whether a control's event causes immediate posting to

• the server or is instead cached and raised when the page is submitted.

• Support for themes.

• Ability to pass events from a nested control to the container control.

Page 1265: Dotnet Stream

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

ASP.NET Label Control

The Label control displays text in a set location on the page.

LabelLabel

<asp:Label ID="Label1" runat="server" AccessKey="N" AssociatedControlID="Textbox1">User<u>n</u>ame</asp:Label>

<asp:Label ID="Label1" runat="server" AccessKey="N" AssociatedControlID="Textbox1">User<u>n</u>ame</asp:Label>

<asp:Textbox ID="TextBox1" runat="server"></asp:Textbox></p>

Page 1266: Dotnet Stream

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

ASP.NET TextBox Control

The TextBox control enables the user to enter text . The display width of TextBox is determined by its Columns property. If TextMode is MutliLine, the display height of TextBox is determined by the Rows property.

TextBoxTextBox

<asp:TextBox id="Text1" Text="Copy this text to the label" Width="200px" runat="server"/>

<asp:TextBox id="Text1" Text="Copy this text to the label" Width="200px" runat="server"/>

Page 1267: Dotnet Stream

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

ASP.NET Button Control

The Button control provides a command button-style control that is used to post a Web Forms page back to the server

ButtonButton

<asp:Button id=Button1 Text="Click Me" onclick="Button1_Click" runat="server" /> <asp:Label id=Label1 runat=server />

<asp:Button id=Button1 Text="Click Me" onclick="Button1_Click" runat="server" /> <asp:Label id=Label1 runat=server />

void Button1_Click(object Source, EventArgs e) {

Label1.Text="You clicked the button"; }

Page 1268: Dotnet Stream

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

ASP.NET LinkButton Control

LinkButton is used to post a Web Forms page back to the server

LinkButtonLinkButton

<asp:LinkButton Text="Click Me!" Font-Names="Verdana" Font-Size="14pt" onclick="LinkButton1_Click" runat="server"/>

<asp:LinkButton Text="Click Me!" Font-Names="Verdana" Font-Size="14pt" onclick="LinkButton1_Click" runat="server"/>

Page 1269: Dotnet Stream

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

ASP.NET Image Button Control

ImageButton is used to post back to the server

ImageButtonImageButton

Image Button as a Image Map

Size:100pixelsSize:100pixels

Page 1270: Dotnet Stream

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

ASP.NET Image Button Control

<table width="100%" border="0"> <tr> <td width="25%"> <asp:ImageButton id="Button1" ImageUrl="ip.jpg" BorderWidth="2px" onclick="ImageButton1_OnClick" runat="server" Width="100" Height="100"/> </td> <td> <asp:Label id="Label1" Text="X:" runat="SERVER"/> <br/> <asp:Label id="Label2" Text="Y:" runat="SERVER"/> </td> </tr> </table> <asp:Label id="Label3" font-bold="true" Text="" runat="SERVER"/>

Page 1271: Dotnet Stream

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

ASP.NET Image Button Control

public void ImageButton1_OnClick(object Source, ImageClickEventArgs e) { int x = e.X; int y = e.Y; Label1.Text = "X: " + x.ToString(); Label2.Text = "Y: " + y.ToString(); if (x >= 60) { Label3.Text = "You clicked on the Right side!"; } else { Label3.Text = "You clicked on Left side!"; } }

Page 1272: Dotnet Stream

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

ASP.NET HyperLink Control

The HyperLink control is used to navigate from the client to another page

HyperLinkHyperLink

<asp:hyperlink id=HyperLink1 runat="server"> Go To Shopping Homepage</asp:hyperlink>

<asp:hyperlink id=HyperLink1 runat="server"> Go To Shopping Homepage</asp:hyperlink>

protected void Page_Load(object sender, EventArgs e) { // Set hyperlink to "~", which indicates application root. HyperLink1.NavigateUrl = "~"; }

Page 1273: Dotnet Stream

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

ASP.NET DropDownList Control

The DropDownList control provides a single-select drop-down list.

DropDownListDropDownList

Data binding to a static ArrayList with a DropDownList control.

Page 1274: Dotnet Stream

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

ASP.NET DropDownList Control

protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ArrayList values = new ArrayList(); values.Add("IN"); values.Add("KS"); values.Add("MD"); DropDown1.DataSource = values; DropDown1.DataBind(); } } public void SubmitBtn_Click(Object sender, EventArgs e) { Label1.Text = "You chose: " + DropDown1.SelectedItem.Text; }

<asp:DropDownList id="DropDown1" runat="server" /> <asp:button ID="Button1" Text="Submit" OnClick="SubmitBtn_Click" runat="server"/> <asp:Label id="Label1" Font-Names="Verdana" font-size="10pt" runat="server" />

<asp:DropDownList id="DropDown1" runat="server" /> <asp:button ID="Button1" Text="Submit" OnClick="SubmitBtn_Click" runat="server"/> <asp:Label id="Label1" Font-Names="Verdana" font-size="10pt" runat="server" />

Page 1275: Dotnet Stream

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

ASP.NET ListBox Control

The ListBox control provides a single-selection or multiple-selection list. To enable multiple selection, set the SelectionMode property to Multiple

ListBoxListBox

Page 1276: Dotnet Stream

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

ASP.NET ListBox Control

public void SubmitBtn_Click(Object Sender, EventArgs e) {

if (ListBox1.SelectedIndex > -1) { Label1.Text = "You chose: " + ListBox1.SelectedItem.Text;

}

}

<asp:ListBox ID="ListBox1" Width="100px" runat="server"> <asp:ListItem>Item 1</asp:ListItem> <asp:ListItem>Item 2</asp:ListItem> <asp:ListItem>Item 3</asp:ListItem> <asp:ListItem>Item 4</asp:ListItem> </asp:ListBox> <asp:Button Text="Submit" ID=submit1 OnClick="SubmitBtn_Click" runat="server" /><asp:Label ID="Label1" Font-Names="Verdana" Font-Size="10pt" runat="server" />

Page 1277: Dotnet Stream

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

ASP.NET CheckBox Control

The CheckBox server control accepts Boolean (true or false) input. When selected, its Checked property is true

CheckBoxCheckBox

<asp:CheckBox id=Check1 Text="CheckBox1" runat="server" /> <asp:CheckBox id=Check1 Text="CheckBox1" runat="server" />

Page 1278: Dotnet Stream

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

ASP.NET CheckBoxList Control

The CheckBoxList control provides a multiple-selection checked list

CheckBoxListCheckBoxList

Properties:

RepeatLayout

Table- the list is rendered within a table

Flow- the list is rendered without any table structure

RepeatDirection

Vertical- the list is rendered vertically

Horizontal- the list is rendered horizontally

. <asp:CheckBoxList ID="Check1" runat="server"> <asp:ListItem>Item 1</asp:ListItem> <asp:ListItem>Item 2</asp:ListItem> <asp:ListItem>Item 3</asp:ListItem> <asp:ListItem>Item 4</asp:ListItem> <asp:ListItem>Item 5</asp:ListItem> <asp:ListItem>Item 6</asp:ListItem> </asp:CheckBoxList>

<asp:CheckBoxList ID="Check1" runat="server"> <asp:ListItem>Item 1</asp:ListItem> <asp:ListItem>Item 2</asp:ListItem> <asp:ListItem>Item 3</asp:ListItem> <asp:ListItem>Item 4</asp:ListItem> <asp:ListItem>Item 5</asp:ListItem> <asp:ListItem>Item 6</asp:ListItem> </asp:CheckBoxList>

Page 1279: Dotnet Stream

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

ASP.NET RadioButton Control

The RadioButton control permits to intersperse the radio buttons in a group with other content in the page.

RadioButtonRadioButton

Page 1280: Dotnet Stream

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

ASP.NET Radio Button Control

public void SubmitBtn_Click(Object Sender, EventArgs e) { if (Radio1.Checked) { Label1.Text = "<b>You selected:</b> " + Radio1.Text; } else if (Radio2.Checked) { Label1.Text = "<b>You selected:</b> " + Radio2.Text; } else if (Radio3.Checked) { Label1.Text = "<b>You selected:</b> " + Radio3.Text; } }

Page 1281: Dotnet Stream

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

ASP.NET Radio Button Control

<h4>Select the type of installation you wish to perform:</h4><asp:RadioButton ID="Radio1" Text="Typical" Checked="True" GroupName="RadioGroup1“runat="server" />This option installs the features most typically used. <i>Requires 1.2 MB disk space.</i><br /><asp:RadioButton ID="Radio2" Text="Compact" GroupName="RadioGroup1" runat="server" />This option installs the minimum files required to run the product. <i>Requires 350KB disk space.</i><br /><asp:RadioButton ID="Radio3" runat="server" Text="Full" GroupName="RadioGroup1" />This option installs all features for the product. <i>Requires 4.3 MB disk space.</i><br /><asp:Button ID="Button1" Text="Submit" OnClick="SubmitBtn_Click" runat="server" /><asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

Page 1282: Dotnet Stream

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

ASP.NET RadioButtonList Control

The RadioButtonList control provides a single-selection checked list

RadioButtonListRadioButtonList

Page 1283: Dotnet Stream

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

<asp:RadioButtonList ID="RadioButtonList1" runat="server"> <asp:ListItem>Item 1</asp:ListItem> <asp:ListItem>Item 2</asp:ListItem> <asp:ListItem>Item 3</asp:ListItem> <asp:ListItem>Item 4</asp:ListItem> <asp:ListItem>Item 5</asp:ListItem> <asp:ListItem>Item 6</asp:ListItem></asp:RadioButtonList>

<asp:CheckBox ID="chkLayout" OnCheckedChanged="chkLayout_CheckedChanged" Text="Display Table Layout" Checked="true" utoPostBack="true" runat="server" /><asp:CheckBox id=chkDirection OnCheckedChanged="chkDirection_CheckedChanged" Text="Display Horizontally" AutoPostBack="true" runat="server" />

ASP.NET RadioButtonList Control

Page 1284: Dotnet Stream

1284©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.

public void chkLayout_CheckedChanged(Object sender, EventArgs e) { if (chkLayout.Checked == true) { RadioButtonList1.RepeatLayout =

RepeatLayout.Table; } else { RadioButtonList1.RepeatLayout = RepeatLayout.Flow; } }public void chkDirection_CheckedChanged(Object sender, EventArgs e) { if (chkDirection.Checked == true) { RadioButtonList1.RepeatDirection = RepeatDirection.Horizontal; } else { RadioButtonList1.RepeatDirection = RepeatDirection.Vertical; } }

ASP.NET RadioButtonList Control

Page 1285: Dotnet Stream

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

ASP.NET Image Control

The Image control displays the image defined by its ImageUrl property

ImageImage

<asp:Image ID="Image1" ImageUrl="images/cereal1.gif" AlternateText="Healthy Grains" runat="server" />

<asp:Image ID="Image1" ImageUrl="images/cereal1.gif" AlternateText="Healthy Grains" runat="server" />

Page 1286: Dotnet Stream

1286©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.

ImageMap control is used to create an image that contains defined hotspot regions.The control can either generate a post back to the server or navigate to a specified URL

ImageMapImageMap

<asp:imagemap id="Buttons" imageurl="hotspot.jpg" alternatetext="Navigate buttons" runat="Server">

<asp:RectangleHotSpot hotspotmode="Navigate" NavigateUrl="navigate1.htm" alternatetext="Button 1" top="30" left="175" bottom="110" right="355"> </asp:RectangleHotSpot> <asp:RectangleHotSpot hotspotmode="Navigate" NavigateUrl="navigate2.htm" alternatetext="Button 2" top="155" left="175" bottom="240“ right="355“</asp:RectangleHotSpot>

</asp:imagemap>

<asp:imagemap id="Buttons" imageurl="hotspot.jpg" alternatetext="Navigate buttons" runat="Server">

<asp:RectangleHotSpot hotspotmode="Navigate" NavigateUrl="navigate1.htm" alternatetext="Button 1" top="30" left="175" bottom="110" right="355"> </asp:RectangleHotSpot> <asp:RectangleHotSpot hotspotmode="Navigate" NavigateUrl="navigate2.htm" alternatetext="Button 2" top="155" left="175" bottom="240“ right="355“</asp:RectangleHotSpot>

</asp:imagemap>

ASP.NET ImageMap Control

Page 1287: Dotnet Stream

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

ASP.NET ImageMap Control

<asp:imagemap id="Buttons" imageurl="hotspot.jpg" alternatetext="Navigate buttons" hotspotmode="Postback" onclick="Buttons_Clicked" runat="Server"> <asp:RectangleHotSpot hotspotmode="Postback" postbackvalue="Button1" alternatetext="Button 1" top="30" left="175" bottom="110" right="355"> </asp:RectangleHotSpot>

<asp:imagemap id="Buttons" imageurl="hotspot.jpg" alternatetext="Navigate buttons" hotspotmode="Postback" onclick="Buttons_Clicked" runat="Server"> <asp:RectangleHotSpot hotspotmode="Postback" postbackvalue="Button1" alternatetext="Button 1" top="30" left="175" bottom="110" right="355"> </asp:RectangleHotSpot>

void Buttons_Clicked(object sender, ImageMapEventArgs e) { label1.Text = e.PostBackValue + " clicked!"; }

Running different server code based on the region of the image that is clicked

Page 1288: Dotnet Stream

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

ASP.NET Table Control

The Table control builds up a table programmatically by adding TableRows to the Rows collection of the table, and TableCells to the Cells collection of the row.

TableTable

Creating rows and columns for a table dynamically

Page 1289: Dotnet Stream

1289©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.

protected void Button1_Click(object sender, EventArgs e) { for (int j = 0; j < 3; j++) { TableRow r = new TableRow(); for (int i = 0; i < 4; i++) { TableCell c = new TableCell(); c.Controls.Add(new LiteralControl("row " +

j.ToString() + ", cell " + i.ToString())); r.Cells.Add(c); } Table1.Rows.Add(r); } }

<asp:Table id="Table1" Font-Names="Verdana" Font-Size="8pt" CellPadding=5 CellSpacing=0 BorderColor="black" BorderWidth="1" Gridlines="Both" runat="server"/><asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Create Table" />

<asp:Table id="Table1" Font-Names="Verdana" Font-Size="8pt" CellPadding=5 CellSpacing=0 BorderColor="black" BorderWidth="1" Gridlines="Both" runat="server"/><asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Create Table" />

ASP.NET Table Control

Page 1290: Dotnet Stream

1290©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.

The BulletedList control is used to create a list of items formatted with bullets

BulletedListBulletedList

<asp:BulletedList ID=BulletedList1 BulletStyle="Circle" runat=server> <asp:ListItem>Item #1</asp:ListItem> <asp:ListItem>Item #2</asp:ListItem> <asp:ListItem>Item #3</asp:ListItem> <asp:ListItem>Item #4</asp:ListItem> </asp:BulletedList>

The BulletedList control can also render a list of hyperlinks

<asp:BulletedList DisplayMode = HyperLink runat=server> <asp:ListItem Value="http://support.Microsoft.com">Support</asp:ListItem> <asp:ListItem Value="http://www.asp.net">ASP.NET</asp:ListItem> </asp:BulletedList>

ASP.NET BulletedList Control

Page 1291: Dotnet Stream

1291©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.

This control enables a developer to store a non-displayed value

HiddenFieldHiddenField

ASP.NET HiddenField Control

Page 1292: Dotnet Stream

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

<asp:HiddenField id="HiddenField1" runat="Server" /> <asp:Button id="Button1" Text="Click Me" onclick="Button1_Click" runat="server" /> Clicked <asp:Label id="Label1" Text="0" runat="server" /> times

public void Button1_Click(object sender, EventArgs e) { if (HiddenField1.Value == String.Empty) HiddenField1.Value = "0"; //Increment the hidden field value by 1 HiddenField1.Value = (Convert.ToInt32(HiddenField1.Value) + 1).ToString(); Label1.Text = HiddenField1.Value; }

ASP.NET HiddenField Control

Page 1293: Dotnet Stream

1293©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.

A Literal control is used to display text. Styles can be applied to a literal control This control will pass the content directly to the client browser, unless the Mode property to encode the

content is used.

LiteralLiteral

<asp:Literal ID=Literal2 Mode=Encode Text="<Some encoded text>" runat=server />

<asp:Literal ID=Literal2 Mode=Encode Text="<Some encoded text>" runat=server />

<asp:Literal ID=Literal1 Text="I am a literal control" runat=server />

<asp:Literal ID=Literal1 Text="I am a literal control" runat=server />

ASP.NET Literal Control

Page 1294: Dotnet Stream

1294©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.

The Calendar control displays a month calendar from which users can select dates

CalendarCalendar

<asp:Calendar id=Calendar1 onselectionchanged="Calendar1_SelectionChanged" runat="server" />

protected void Calendar1_SelectionChanged(object sender, EventArgs e) { CalLabel.Text = "Selected date is: " + Calendar1.SelectedDate.ToShortDateString(); }

ASP.NET Calendar Control

Page 1295: Dotnet Stream

1295©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.

CalendarCalendar

ASP.NET Calendar Control

Page 1296: Dotnet Stream

1296©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.

Choose a Selection Mode: <asp:DropDownList id="lstSelMode" runat="server" AutoPostBack="true"> <asp:ListItem Value="None" >None</asp:ListItem> <asp:ListItem Value="Day" Selected="True">

Day</asp:ListItem> <asp:ListItem Value="DayWeek" >DayWeek</asp:ListItem> <asp:ListItem Value="DayWeekMonth" >

DayWeekMonth</asp:ListItem> </asp:DropDownList>

ASP.NET Calendar Control

Page 1297: Dotnet Stream

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

<asp:Calendar id="Calendar1" runat="server" onselectionchanged="Date_Selected" Font-Names="Arial" Font-Size="12px"

Height="180px" Width="200px" SelectorStyle-BackColor="gainsboro“

TodayDayStyle-BackColor="gainsboro" DayHeaderStyle-BackColor="gainsboro" OtherMonthDayStyle-ForeColor="gray“

TitleStyle-BackColor="gray“ TitleStyle-Font-Bold="True"

TitleStyle-Font-Size="12px“ SelectedDayStyle-BackColor="Navy“

SelectedDayStyle-Font-Bold="True“ NextPrevFormat="ShortMonth"

NextPrevStyle-ForeColor="white“ NextPrevStyle-Font-Size="10px"

SelectorStyle-ForeColor="navy“ SelectorStyle-Font-Size="9px"

SelectWeekText = "week" SelectMonthText = "month" /><asp:Label id="Label1" runat="server" />

ASP.NET Calendar Control

Page 1298: Dotnet Stream

1298©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.

protected void Page_Load(object sender, EventArgs e){

Calendar1.SelectionMode = (CalendarSelectionMode)lstSelMode.SelectedIndex; if (Calendar1.SelectionMode == CalendarSelectionMode.None) Calendar1.SelectedDates.Clear(); } public void Date_Selected(object s, EventArgs e) { switch (Calendar1.SelectedDates.Count) { case (0): //None Label1.Text = "No dates are currently selected";

break; case (1): //Day Label1.Text = "The selected date is " +

Calendar1.SelectedDate.ToShortDateString();break; case (7): //Week Label1.Text = "The selection is a week beginning " +

Calendar1.SelectedDate.ToShortDateString();break; default: //Month Label1.Text = "The selection is a month beginning " +

Calendar1.SelectedDate.ToShortDateString();break; } }

ASP.NET Calendar Control

Page 1299: Dotnet Stream

1299©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.

The AdRotator control presents ad images that, when clicked, navigate to a new Web location.

AdRotatorAdRotator

The rotation schedule for ads is defined in an XML file

<Advertisements> <Ad> <ImageUrl>images/banner1.gif</ImageUrl> <NavigateUrl>http://www.microsoft.com</NavigateUrl> <AlternateText>Microsoft.com</AlternateText> <Keyword>Computers</Keyword> <Impressions>80</Impressions> </Ad> </Advertisements>

<asp:AdRotator id="ar1" AdvertisementFile="Ads.xml" BorderWidth="1" runat=server />

<asp:AdRotator id="ar1" AdvertisementFile="Ads.xml" BorderWidth="1" runat=server />

ASP.NET AdRotator Control

Page 1300: Dotnet Stream

1300©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.

Attribute Description

ImageUrl An absolute or relative URL to the ad image file.

NavigateUrl The Web location to navigate to when the image is clicked. If NavigateUrl is not set, the image is not clickable.

AlternateText The text to render as the ALT attribute of the image. When the page is viewed with Microsoft Internet Explorer, this acts as a ToolTip for the ad.

Keyword Specifies a category for the ad that the page can filter on.

Impressions A number that indicates the "weight" of the ad in the schedule of rotation relative to the other ads in the file. The larger the number, the more often the ad will be displayed.

ASP.NET AdRotator Control

Page 1301: Dotnet Stream

1301©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.

The FileUpLoad control enables to upload file to the server. It displays a text box control and a browse button to select a file to upload to the server.

FileUploadFileUpload

ASP.NET FileUpload Control

Page 1302: Dotnet Stream

1302©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.

public void Button1_Click(object sender, EventArgs e){ if (FileUpLoad1.HasFile) {

Label1.Text = "Received :" + FileUpLoad1.FileName + " Content Type :" + FileUpLoad1.PostedFile.ContentType

+ " Length: " + FileUpLoad1.PostedFile.ContentLength; } else { Label1.Text = "No uploaded file"; } }

<asp:FileUpLoad id="FileUpLoad1" AlternateText="You cannot upload files" runat="server" /> <asp:Button id="Button1" Text="Upload" OnClick="Button1_Click" runat="server" /> <asp:Label id="Label1" runat="server" />

ASP.NET FileUpload Control

Page 1303: Dotnet Stream

1303©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.

The Wizard control provides navigation through a series of steps that collect information incrementally from a user

Wizard Wizard

ASP.NET Wizard Control

Page 1304: Dotnet Stream

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

ASP.NET Wizard Control

The Wizard consists of:

Collection of WizardSteps:

• Each WizardStep contains a discrete piece of content to be displayed to the user. Only one WizardStep will be displayed at a time.

Navigation Area:

• The navigation area below each WizardStep that contains the navigation buttons to go the next and pervious steps in the wizard.

SideBar:

• An optional element that contains a list of all WizardSteps and provides a means to skip around the WizardSteps in a random order.

Header:

• An optional element to provide consistent information at the top of the WizardStep.

Page 1305: Dotnet Stream

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

ASP.NET Wizard Control

The StepType associated with each WizardStep determines the type of navigation buttons that will be displayed for that step.

The StepTypes are: • Start: Displays a Next button. • Step: Displays Next and Previous buttons. • Finish: Displays a Finish button. • Complete: Displays no navigation buttons and hides the SideBar if

it is displayed. • Auto:One of the step types listed above is selected based on the

order of the step in the collection

Page 1306: Dotnet Stream

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

<asp:Wizard ID="Wizard1" runat="server" ActiveStepIndex="0" OnActiveStepChanged="GetFavoriteNumberOnActiveStepIndex"BackColor="#FFFBD6" BorderColor="#FFDFAD" BorderWidth="1px" CellPadding="5" Font-Names="Verdana“ Font-Size="0.8em" Width="322px"> <WizardSteps> <asp:WizardStep ID="WizardStep1" runat="server" Title="Step 1"> <strong>Wizard Step 1</strong> <br /><br /> Favorite Number: <asp:DropDownList ID="DropDownList1" runat="server"> <asp:ListItem>1</asp:ListItem> <asp:ListItem>2</asp:ListItem> </asp:DropDownList> <br /> </asp:WizardStep>

ASP.NET Wizard Control

Page 1307: Dotnet Stream

1307©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.

public void GetFavoriteNumberOnActiveStepIndex(Object Sender, EventArgs e) { Label1.Text = "Thank you for telling that your favorite number

is:" + DropDownList1.SelectedItem.Text; }

<asp:WizardStep ID="WizardStep2" runat="server" Title="Step 2" StepType="Complete"> <strong>Wizard Step 2</strong><br /> <br /> <asp:Label ID="Label1" runat="server"/> </asp:WizardStep> </WizardSteps> <SideBarStyle Width="75px" VerticalAlign="Top"/> </asp:Wizard>

ASP.NET Wizard Control

Page 1308: Dotnet Stream

1308©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.

• The DocumentSource specifies the XML document to use. • This document will be written directly to the output stream unless

TransformSource is also specified. • TransformSource must be a valid XSL Transform document and will

be used to transform the XML document before its contents are written to the output stream.

The Xml control can be used to write out an XML document or the results of an XSL Transform

XML XML

ASP.NET XML Control

Page 1309: Dotnet Stream

1309©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.

The MultiView control represents a control that acts as a container for groups of View controls. It allows you to define a group of View controls, where each View control contains child controls

Multiview/ViewMultiview/View

Selecting multiple views

ASP.NET MultiView Control

Page 1310: Dotnet Stream

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

<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0"> <asp:View ID="View1" runat="server">

Now showing View #1<br /> <asp:TextBox ID="TextBox1“

runat="server"></asp:TextBox><asp:Button ID="Button1" runat="server“ Text="Button" />

</asp:View> <asp:View ID="View2" runat="server">

Now showing View #2<br /> <asp:HyperLink ID="HyperLink1" runat="server"

NavigateUrl="http://www.asp.net">HyperLink</asp:HyperLink>

<asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl="http://www.asp.net">HyperLink</asp:HyperLink>

</asp:View></asp:MultiView>

ASP.NET MultiView Control

Page 1311: Dotnet Stream

1311©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.

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { MultiView1.ActiveViewIndex = Convert.ToInt32(DropDownList1.SelectedValue); }

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"

OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"> <asp:ListItem Value="0">View 1</asp:ListItem> <asp:ListItem Value="1">View 2</asp:ListItem> <asp:ListItem Value="2">View 3</asp:ListItem> </asp:DropDownList><br /> <hr />

ASP.NET MultiView Control

Page 1312: Dotnet Stream

1312©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.

The Panel control is a container for other controls . It is especially useful when you want to generate controls programmatically or hide or show a group of controls

PanelPanel

Adding Controls to panel dynamically

ASP.NET Panel Control

Page 1313: Dotnet Stream

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

<asp:Panel id="Panel1" runat="server“ BackColor="gainsboro“ Height="200px“ Width="300px"> Panel1: Here is some static content... <br /> </asp:Panel><asp:CheckBox id="Check1" Text="Hide Panel" runat="server"/><asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />

<asp:Panel id="Panel1" runat="server“ BackColor="gainsboro“ Height="200px“ Width="300px"> Panel1: Here is some static content... <br /> </asp:Panel><asp:CheckBox id="Check1" Text="Hide Panel" runat="server"/><asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />

protected void Button1_Click(object sender, EventArgs e) { if (Check1.Checked) { Panel1.Visible = false; } else { Panel1.Visible = true; } for (int i = 1; i <= 3; i++) { System.Web.UI.WebControls.Label l = new

System.Web.UI.WebControls.Label(); l.Text = "Label" + i.ToString(); l.ID = "Label" + i.ToString(); Panel1.Controls.Add(l); Panel1.Controls.Add(new LiteralControl("<br>")); } }

ASP.NET Panel Control

Page 1314: Dotnet Stream

1314©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.

The PlaceHolder control can be used as a container control within a document to dynamically load other controls

PlaceHolderPlaceHolder

ASP.NET PlaceHolder Control

Page 1315: Dotnet Stream

1315©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.

protected void Button1_Click1(object sender, EventArgs e) { HtmlButton clicker = new HtmlButton(); clicker.InnerText = "Button 1"; Bullseye.Controls.Add(clicker); clicker = new HtmlButton(); clicker.InnerText = "Button 2"; Bullseye.Controls.Add(clicker); clicker = new HtmlButton(); clicker.InnerText = "Button 3"; Bullseye.Controls.Add(clicker); }

<asp:PlaceHolder id="Bullseye" runat="server" /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click1" Text="Button" />

<asp:PlaceHolder id="Bullseye" runat="server" /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click1" Text="Button" />

ASP.NET PlaceHolder Control

Page 1316: Dotnet Stream

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

ASP.NET Login Controls

Login ControlsLogin Controls

Page 1317: Dotnet Stream

1317©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.

LoginLogin

Password-Recovery

Password-Recovery

LoginStatusLoginStatus

LoginNameLoginName

LoginViewLoginView

CreateUser-Wizard

CreateUser-Wizard

Change-Password

Change-Password

Login Controls

ASP.NET Login Controls

Page 1318: Dotnet Stream

1318©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.

Name Description

ChangePassword

UI for changing passwords

CreateUserWizard

UI for creating new user accounts

LoginUI for entering and validating user names and passwords

LoginName Displays authenticated user names

LoginStatus UI for logging in and logging out

LoginViewDisplays different views based on login status and roles

PasswordRecovery

UI for recovering forgotten passwords

Types of Login Controls

Page 1319: Dotnet Stream

1319©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.

Features of Login Control• Standard UI for logging in users• Integrates with Membership service

Calls ValidateUser automatically No-code validation and logins

• Also works without Membership service• Incorporates RequiredFieldValidators• Highly customizable UI and behavior

LoginLogin

ASP.NET Login Control

Page 1320: Dotnet Stream

1320©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.

Customizing the Login Control

<asp:Login ID="LoginControl" RunAt="server" CreateUserText="Create new account" CreateUserUrl="CreateUser.aspx" DisplayRememberMe="false" PasswordRecoveryText="Forgotten your password?" PasswordRecoveryUrl="RecoverPassword.aspx" LoginButtonText="Do It!" TitleText="Please Log In"/>

<asp:Login ID="LoginControl" RunAt="server" CreateUserText="Create new account" CreateUserUrl="CreateUser.aspx" DisplayRememberMe="false" PasswordRecoveryText="Forgotten your password?" PasswordRecoveryUrl="RecoverPassword.aspx" LoginButtonText="Do It!" TitleText="Please Log In"/>

Login Control-Customization

Page 1321: Dotnet Stream

1321©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.

Name Description

LoggingIn

Fired when the user clicks the Log In button. Purpose: to Prevalidate login credentials (e.g., make sure e-mailaddress is well-formed)

Authenticate

Fired when the user clicks the Log In button. Purpose: to authenticate the user by validating his or her login credentials

LoggedIn Fired following a successful login

LoginError Fired when an attempted login fails

Login Control Events

Page 1322: Dotnet Stream

1322©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.

Features of LoginView Control• Displays content differently to different users depending on:

Whether user is authenticated If user is authenticated, the role memberships he or she is

assigned• Template-driven

<AnonymousTemplate> <LoggedInTemplate> <RoleGroups> and <ContentTemplate>

LoginViewLoginView

ASP.NET LoginView Control

Page 1323: Dotnet Stream

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

<asp:LoginView ID="LoginView1" Runat="server"> <AnonymousTemplate> <!-- Content seen by unauthenticated users --> </AnonymousTemplate> <LoggedInTemplate> <!-- Content seen by authenticated users --> </LoggedInTemplate> <RoleGroups> <asp:RoleGroup Roles="Administrators"> <ContentTemplate> <!-- Content seen by authenticated users who are administrators --> </ContentTemplate> </asp:RoleGroup> ... </RoleGroups></asp:LoginView>

ASP.NET LoginView Control

Page 1324: Dotnet Stream

1324©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.

Features of Password Recovery Control• Password recovery usually means sending the end user’s password to

him in an e-mail. • Set up an SMTP server

PasswordRecoveryPasswordRecovery

ASP.NET Password Recovery Control

Page 1325: Dotnet Stream

1325©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.

Configuring passwords to be sent via email in the web.config file Configuring passwords to be sent via email in the web.config file

<configuration> <system.web> <!-- Removed for clarity -->

</system.web> <system.net> <mailSettings> <smtp from="[email protected]"> <network host="localhost" port="25" defaultCredentials="true" /> </smtp> </mailSettings>

</system.net> </configuration>

Using the PasswordRecovery control Using the PasswordRecovery control

<asp:PasswordRecovery ID="PasswordRecovery1" Runat="server"> <MailDefinition From="[email protected]"> </MailDefinition> </asp:PasswordRecovery>

Password Recovery Control

Page 1326: Dotnet Stream

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

ASP.NET LoginStatus Control

Features of LoginStatus Control• Displays links for logging in and out

"Login" to unauthenticated users "Logout" to authenticated users

• UI and logout behavior are customizable

LoginStatusLoginStatus

<asp:LoginStatus ID="LoginStatus1" Runat="server" LogoutAction="Redirect" LogoutPageUrl="~/Default.aspx" />

<asp:LoginStatus ID="LoginStatus1" Runat="server" LogoutAction="Redirect" LogoutPageUrl="~/Default.aspx" />

Page 1327: Dotnet Stream

1327©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.

Name Description

LognTextText displayed for login link (default="Login")

LogoutTextText displayed for logout link (default="Logout")

LoginImageUrl URL of image used for login link

LogoutActionAction to take following logout: Redirect, RedirectToLoginPage, or Refresh

(default)

LogOutPageUrlURL of page to go to following logout if LogoutAction="Redirect"

LoginStatus Control

Page 1328: Dotnet Stream

1328©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.

Features of LoginName Control• Displays authenticated user names• Use optional FormatString property to control format of output

LoginNameLoginName

ASP.NET LoginName Control

<asp:LoginView ID="LoginView1" Runat="server"> <AnonymousTemplate> You are not logged in </AnonymousTemplate> <LoggedInTemplate> <asp:LoginName ID="LoginName1" Runat="server" FormatString="You are logged in as {0}" /> </LoggedInTemplate></asp:LoginView>

<asp:LoginView ID="LoginView1" Runat="server"> <AnonymousTemplate> You are not logged in </AnonymousTemplate> <LoggedInTemplate> <asp:LoginName ID="LoginName1" Runat="server" FormatString="You are logged in as {0}" /> </LoggedInTemplate></asp:LoginView>

Page 1329: Dotnet Stream

1329©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.

Features of CreateUserWizard Control• The CreateUserWizard server control is one that can be used in

conjunction with the membership service.• The CreateUserWizard control enables to plug registered users into the

data store for later retrieval.

CreateUserWizardCreateUserWizard

<asp:CreateUserWizard ID="CreateUserWizard1" Runat="server" BorderWidth="1px" BorderColor="#FFDFAD" BorderStyle="Solid" BackColor="#FFFBD6" Font-Names="Verdana"> <TitleTextStyle Font-Bold="True" BackColor="#990000" ForeColor="White"></TitleTextStyle> </asp:CreateUserWizard>

<asp:CreateUserWizard ID="CreateUserWizard1" Runat="server" BorderWidth="1px" BorderColor="#FFDFAD" BorderStyle="Solid" BackColor="#FFFBD6" Font-Names="Verdana"> <TitleTextStyle Font-Bold="True" BackColor="#990000" ForeColor="White"></TitleTextStyle> </asp:CreateUserWizard>

ASP.NET CreateUserWizard Control

Page 1330: Dotnet Stream

1330©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.

ChangePasswordChangePassword

The ChangePassword server control enables end users to change their passwords directly in the browser

<asp:ChangePassword ID="ChangePassword1" Runat="server"> </asp:ChangePassword>

<asp:ChangePassword ID="ChangePassword1" Runat="server"> </asp:ChangePassword>

ASP.NET ChangePassword Control

Page 1331: Dotnet Stream

1331©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.

Features of ChangePassword Control• The ChangePassword control produces a form that asks for the

previous password. • It also requires the end user to type the new password twice. • Clicking the Change Password button launches an attempt to change

the password if the user is logged in. • If the end user isn’t logged into the application yet, he or she is

redirected to the login page. • Only a logged-in user can change a password. After the password is

changed, the end user is notified

ChangePasswordChangePassword

ASP.NET ChangePassword Control

Page 1332: Dotnet Stream

1332©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.

Validation ControlsValidation Controls

ASP.NET Validation Controls

Page 1333: Dotnet Stream

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

ASP.NET Client Vs. Server side ValidationASP.NET can create both client-side and server-side

validationClient-side validation

• Dependent on browser version• Instant feedback• Reduces postback cycles

Server-side validation• Repeats all client-side validation• Can validate against stored data

Valid?Valid?

Valid?Valid?

User Enters Data

User Enters Data

No

No

Yes

Yes

Error Message

Client

Server

Web FormProcessed

Web FormProcessed

Page 1334: Dotnet Stream

1334©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.

Validation ControlsValidation Controls

Custom Validator

Custom Validator

RequiredFieldValidator

RequiredFieldValidator

RangeValidatorRangeValidator

RegularExpressionValidator

RegularExpressionValidatorCompare

Validator

CompareValidator

ValidationSummary

ValidationSummary

Types of Validation Controls

Page 1335: Dotnet Stream

1335©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.

RequiredFieldValidatorRequiredFieldValidator

Ensures that the user does not skip an entry

Name: <asp:TextBox id=Text1 runat="server"/><asp:RequiredFieldValidator id="RequiredFieldValidator1" ControlToValidate="Text1" Font-Names="Arial" Font-Size="11" runat="server"> Required field!</asp:RequiredFieldValidator>

ASP.NET RequiredField Validator

Page 1336: Dotnet Stream

1336©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.

RangeValidatorRangeValidatorChecks that a user's entry is between specified lower and upper boundaries

<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="TextBox1"ErrorMessage="Value must be >1 and <=10" MaximumValue="10" MinimumValue="1"></asp:RangeValidator>

ASP.NET Range Validator

Page 1337: Dotnet Stream

1337©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

•ControlToValidate contains the value to validate

•ValidationExpression contains the regular expression to match.

RegularExpressionValidatorRegularExpressionValidator

Checks that the entry matches a pattern defined by a regular expression

ASP.NET RegularExpression Validator

Page 1338: Dotnet Stream

1338©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 bgcolor="#eeeeee" cellpadding=10> <tr> <td align=right><font face=Verdana size=2>Zip Code:</font> </td> <td><ASP:TextBox id=TextBox1 runat=server /> </td> <td> <asp:RegularExpressionValidator

id="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox1" ValidationExpression="\d{6}" Display="Static" Font-Names="verdana" Font-Size="10pt"> Zip code must be 6 numeric digits </asp:RegularExpressionValidator> </td> </tr> <tr> <td><ASP:Button ID="Button1" text="Validate" OnClick="ValidateBtn_Click" runat=server /> </td><td colspan=3><asp:Label ID="lblOutput" Text="Enter a 5 digit zip code" Font-Names="Verdana" Font-Size="10pt" runat="server"/></td> </tr> </table>

ASP.NET RegularExpression Validator

Page 1339: Dotnet Stream

1339©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.

public void ValidateBtn_Click(Object Src, EventArgs E) { if (Page.IsValid) { lblOutput.Text = "Page is Valid!"; } else { lblOutput.Text = "Page is InValid! :-("; } }

ASP.NET RegularExpression Validator

Page 1340: Dotnet Stream

1340©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• ControlToValidate and ControlToCompare contain the values to

compare. • Operator defines the type of comparison to perform

CompareValidatorCompareValidatorCompares a user's entry with a constant value or a property value of another control

<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="TextBox1“ ControlToValidate="TextBox2" ErrorMessage="Both values are not equal"></asp:CompareValidator>

ASP.NET Compare Validator

Page 1341: Dotnet Stream

1341©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.

CustomValidatorCustomValidator

Checks the user's entry using validation logic

<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="TextBox1“ErrorMessage="The number must be even" OnServerValidate="MyFunction" ValidateEmptyText="True">Enter a even number</asp:CustomValidator>

ASP.NET Custom Validator

Page 1342: Dotnet Stream

1342©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.

Features• For client-side custom validation, the name of the custom function

must be identified in the ClientValidationFunction property. The custom function must have the form function

myvalidator(source, arguments) source is the client-side CustomValidator object

arguments is an object with two properties, Value and IsValid. The Value property is the value to be validated IsValid property is a Boolean used to set the return result of the

validation.

• For server-side custom validation, place your custom validation in the validator's OnServerValidate delegate.

ASP.NET Custom Validator

Page 1343: Dotnet Stream

1343©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.

ValidationSummaryValidationSummary

Displays the validation errors in summary form for all of the validators on a page

<asp:ValidationSummary ID="ValidationSummary1" runat="server" HeaderText="Errors in the Page:" />

ASP.NET ValidationSummary

Page 1344: Dotnet Stream

1344©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.

Navigation ControlsNavigation Controls

ASP.NET Navigation Controls

Page 1345: Dotnet Stream

1345©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.

TreeViewTreeView

MenuMenu

SiteMapPathSiteMapPath

ASP.NET Navigation Controls

Page 1346: Dotnet Stream

1346©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.

Site Map API

Site Maps

Web.sitemapOther

Data Stores

ControlsMenu TreeView SiteMapPath

SiteMap-DataSource

SiteMap

SiteMapNodeSiteMapNode SiteMapNode

XmlSiteMapProvider Other Site MapProviders

Other Site MapProviders

Providers

ASP.NET Navigation Controls-Schema

Page 1347: Dotnet Stream

1347©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.

Features of SiteMap• The new site navigation system includes the capability to define the

web site in an XML file that is called a site map.• Another addition in ASP.NET 2.0 is a new data provider –

SiteMapDataSource that is specifically developed to work with site map files and to bind them to a new series of navigation-based server controls

A site map is an XML description of the web site’s structure. A site map is an XML description of the web site’s structure.

ASP.NET SiteMap

Page 1348: Dotnet Stream

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

<?xml version="1.0" encoding="utf-8" ?>

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" > <siteMapNode title="Home" description="Home Page" url="Default.aspx"> <siteMapNode title="News" description="The Latest News" url="News.aspx"> <siteMapNode title="U.S." description="U.S. News" url="News.aspx?cat=us" /> <siteMapNode title="World" description="World News" url="News.aspx?cat=world" /> <siteMapNode title="Technology" description="Technology

News" url="News.aspx?cat=tech" /> <siteMapNode title="Sports" description="Sports News" url="News.aspx?cat=sport" /> </siteMapNode>

SiteMap

Page 1349: Dotnet Stream

1349©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.

<siteMapNode title="Finance" description="The Latest Financial Information" url="Finance.aspx"> <siteMapNode title="Quotes" description="Get the Latest Quotes" url="Quotes.aspx" /> <siteMapNode title="Markets" description="The Latest Market

Information" url="Markets.aspx"> <siteMapNode title="U.S. Market Report" description="Looking at the U.S. Market" url="MarketsUS.aspx" /> <siteMapNode title="NYSE" description="The New York Stock Exchange" url="NYSE.aspx" /> </siteMapNode> <siteMapNode title="Funds" description="Mutual Funds" url="Funds.aspx" /> </siteMapNode> <siteMapNode title="Weather" description="The Latest Weather" url="Weather.aspx" /> </siteMapNode></siteMap>

SiteMap

Page 1350: Dotnet Stream

1350©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.

Attribute Description

title The title attribute provides a textual description of the link. The String value used here is the text used for the link.

description

The description attribute not only reminds you what the link is for, but it is also used for the ToolTip attribute on the link. The ToolTip attribute is the yellow box that shows up next to the link when the end user hovers the cursor over the link for a couple of seconds.

url The url attribute describes where the file is located in the solution. If the file is in the root directory, simply use the file name, such as “Default.aspx”.

SiteMap Properties

Page 1351: Dotnet Stream

1351©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.

• The SiteMapPath control creates a breadcrumb navigation. This is a linear path defining where the end user is in the navigation structure

SiteMapPath ControlSiteMapPath Control

<asp:SiteMapPath ID="Sitemappath1" runat="server"> </asp:SiteMapPath>

<asp:SiteMapPath ID="Sitemappath1" runat="server"> </asp:SiteMapPath>

ASP.NET SiteMapPath Control

Page 1352: Dotnet Stream

1352©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.

The PathSeparator Property• The SiteMapPath control uses a greater than sign (>) by default to

separate the link elements• <asp:SiteMapPath ID="Sitemappath1" runat="server" PathSeparator=" |

"> </asp:SiteMapPath> Or

The PathDirection Property• This property changes the direction of the links generated in the output.

Only two settings are possible for this property: RootToCurrent and CurrentToRoot.

<asp:SiteMapPath ID="Sitemappath1" runat="server"> <PathSeparatorTemplate> | </PathSeparatorTemplate></asp:SiteMapPath>

<asp:SiteMapPath ID="Sitemappath1" runat="server"> <PathSeparatorTemplate> | </PathSeparatorTemplate></asp:SiteMapPath>

<PathSeparatorTemplate> <asp:Image ID="Image1" runat="server"

ImageUrl="divider.gif" /> </PathSeparatorTemplate>

<PathSeparatorTemplate> <asp:Image ID="Image1" runat="server"

ImageUrl="divider.gif" /> </PathSeparatorTemplate>

SiteMapPath Control Properties

Page 1353: Dotnet Stream

1353©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.

The ParentLevelsDisplayed Property

• This property displays pages only as deep as specified

The ShowToolTips Property

• The SiteMapPath control generates tooltips for each link if a description property is used within the Web.sitemap file.

<asp:SiteMapPath ID="Sitemappath1" runat="server" ShowToolTips="false"></asp:SiteMapPath>

<asp:SiteMapPath ID="Sitemappath1" runat="server" ShowToolTips="false"></asp:SiteMapPath>

<asp:SiteMapPath ID="Sitemappath1" runat="server" ParentLevelsDisplayed="2"></asp:SiteMapPath>

<asp:SiteMapPath ID="Sitemappath1" runat="server" ParentLevelsDisplayed="2"></asp:SiteMapPath>

SiteMapPath Control Properties

Page 1354: Dotnet Stream

1354©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.

Child Element Description

CurrentNodeStyle

Applies styles to the link in the SiteMapPath navigation for the currently displayed page.

CurrentNodeTemplate

Applies a template construction to the link in the SiteMapPath navigation for the currently displayed page.

NodeStyle Applies styles to all links in the SiteMapPath navigation. The settings applied in the CurrentNodeStyle or RootNodeStyle elements supersede any settings placed here.

NodeStyleTemplate

Applies a template construction to all links in the SiteMapPath navigation. The settings applied in the CurrentNodeStyle or RootNodeStyle elements supersede any settings placed here.

Processing SiteMapPath Control Nodes

Page 1355: Dotnet Stream

1355©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.

Child Element Description

PathSeparatorStyle

Applies styles to the link dividers in the SiteMapPath navigation.

PathSeparatorTemplate

Applies a template construction to the link dividers in the SiteMapPath navigation.

RootNodeStyle Applies styles to the first link (the root link) in the SiteMapPath navigation.

RootNodeTemplate

Applies a template construction to the first link in the SiteMap-Path navigation.

Processing SiteMapPath Control Nodes

Page 1356: Dotnet Stream

1356©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.

The TreeView server control is a rich server control for rendering a hierarchy of data, so it is quite ideal for displaying what is contained in the .sitemap file • The first step is to create a SiteMapDataSource control on the page. • The TreeView control doesn’t just bind to the site map file

automatically as the SiteMapPath control does.

TreeView ControlTreeView Control

ASP.NET TreeView Control

Page 1357: Dotnet Stream

1357©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.

Node of a Tree View Conrtol• Every element or entry in the TreeView control is called a node. • The uppermost node in the hierarchy of nodes is the root node.• It is possible for a TreeView control to have multiple root nodes. • Any node, including the root node, is also considered a parent node

if it has any nodes that are directly under it in the hierarchy of nodes.

• The nodes directly under this parent node are referred to as child nodes.

• Each parent node can have one or more child nodes. • If a node contains no child nodes, it is referred to as a leaf node.

<asp:TreeView ID="TreeView1" runat="server" DataSourceID="SiteMapDataSource1"> </asp:TreeView> <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />

<asp:TreeView ID="TreeView1" runat="server" DataSourceID="SiteMapDataSource1"> </asp:TreeView> <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />

TreeView Control

Page 1358: Dotnet Stream

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

<?xml version="1.0" encoding="utf-8"?><Hardware> <Item Category="Motherboards"> <Option Choice="Asus" /> <Option Choice="Abit" /> </Item> <Item Category="Memory"> <Option Choice="128mb" /> <Option Choice="256mb" /> <Option Choice="512mb" /> </Item> </Hardware>

<asp:TreeView ID="Treeview1" runat="server" DataSourceID="Xmldatasource1"> <DataBindings> <asp:TreeNodeBinding DataMember="Hardware" Text="Computer Hardware" /> <asp:TreeNodeBinding DataMember="Item" TextField="Category" /> <asp:TreeNodeBinding DataMember="Option" TextField="Choice" /> </DataBindings> </asp:TreeView> <asp:XmlDataSource ID="Xmldatasource1" runat="server" DataFile="Hardware.xml"> </asp:XmlDataSource>

Binding the TreeView Control to an XML File

Adding XmlDataSource and assigning the filename to “DataFile” AttributeAdding XmlDataSource and assigning the filename to “DataFile” Attribute

Programming with TreeView Control

Page 1359: Dotnet Stream

1359©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.

Value

Description

All Applies check boxes to each and every node within the TreeView control.

Leaf Applies check boxes to only the nodes that have no additional child elements.

None

Applies no check boxes to any node within the TreeView control.

Parent

Applies check boxes to only the nodes considered parent nodes within the TreeView control. A parent node has at least one child node associated with it.

Root Applies a check box to any root node contained within the TreeView control.

<asp:TreeView ID="Treeview1" runat="server" Font-Underline="false" DataSourceID="Xmldatasource1" ShowCheckBoxes="Leaf"> ... </asp:TreeViewTreeView>

<asp:TreeView ID="Treeview1" runat="server" Font-Underline="false" DataSourceID="Xmldatasource1" ShowCheckBoxes="Leaf"> ... </asp:TreeViewTreeView>

TreeView Control-Selecting multiple options

Page 1360: Dotnet Stream

1360©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.

protected void Button1_Click(object sender, System.EventArgs e) {

if (TreeView1.CheckedNodes.Count > 0) {

Label1.Text = "We are sending you information on:<p>"; foreach (TreeNode node in TreeView1.CheckedNodes) {

Label1.Text += node.Text + " " + node.Parent.Text + <br>";

} } else {

Label1.Text = "You didn't select any”;}

}

TreeView Control

Page 1361: Dotnet Stream

1361©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.

protected void Button1_Click(object sender, System.EventArgs e) {

TreeView1.ExpandAll(); }

protected void Button2_Click(object sender, System.EventArgs e) {

TreeView1.CollapseAll(); }

<asp:TreeView ID="TreeView1" runat="server" DataSourceId="SiteMapDataSource1" OnDataBound="TreeView1_DataBound"> </asp:TreeView>

<asp:TreeView ID="TreeView1" runat="server" DataSourceId="SiteMapDataSource1" OnDataBound="TreeView1_DataBound"> </asp:TreeView>

protected void TreeView1_DataBound(object sender, System.EventArgs e) {

TreeView1.CollapseAll(); TreeView1.FindNode("Home").Expand(); TreeView1.FindNode("Home/Finance").Expand(); TreeView1.FindNode("Home/Finance/Markets").Expand();

}

Expanding and Collapsing Nodes Programmatically

TreeView Control-Expanding and Collapsing Nodes

Page 1362: Dotnet Stream

1362©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.

Adding nodes programmatically to the TreeView control

protected void Button3_Click(object sender, System.EventArgs e) {

TreeNode myNode = new TreeNode(); myNode.Text = TextBox1.Text; myNode.NavigateUrl = TextBox2.Text; TreeView1.FindNode("Home/Finance/Markets").ChildNodes.Add(myNode);

}

protected void Button3_Click(object sender, System.EventArgs e) {

TreeNode myNode = new TreeNode(); myNode.Text = TextBox1.Text; myNode.NavigateUrl = TextBox2.Text; TreeView1.FindNode("Home/Finance/Markets").ChildNodes.Add(myNode);

}

TreeView Control-Adding Nodes

Page 1363: Dotnet Stream

1363©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.

Menu ControlMenu Control

This control is ideal for allowing the end user to navigate a larger hierarchy of options while utilizing very little browser space in the process.

<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1"> </asp:Menu>

<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1"> </asp:Menu>

ASP.NET Menu Control

Page 1364: Dotnet Stream

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

<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1"> <StaticHoverStyle BackColor="DarkGray" BorderColor="Black" BorderStyle="Solid" BorderWidth="1"></StaticHoverStyle> </asp:Menu>

<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1"> <StaticHoverStyle BackColor="DarkGray" BorderColor="Black" BorderStyle="Solid" BorderWidth="1"></StaticHoverStyle> </asp:Menu>

Menu Control-Styles

Applying Different Styles to the Menu Control• Using a Predefined Style • Changing the Style for Static Items

<StaticHoverStyle> <StaticMenuItemStyle> <StaticMenuStyle> <StaticSelectedStyle> <StaticTemplate>

Page 1365: Dotnet Stream

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

<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1“ Orientation="Horizontal"> </asp:Menu>

<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1“ Orientation="Horizontal"> </asp:Menu>

Menu Control-Styles

• Adding Styles to Dynamic Items <DynamicHoverStyle> <DynamicMenuItemStyle> <DynamicMenuStyle> <DynamicSelectedStyle> <DynamicTemplate>

• Changing the Layout of the Menu Items

Page 1366: Dotnet Stream

1366©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.

•Changing the Pop-Out Symbol

<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1" Orientation="Horizontal" DynamicPopOutImageUrl="myArrow.gif" StaticPopOutImageUrl="myArrow.gif"> </asp:Menu>

<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1" Orientation="Horizontal" DynamicPopOutImageUrl="myArrow.gif" StaticPopOutImageUrl="myArrow.gif"> </asp:Menu>

<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1" DynamicBottomSeparatorImageUrl="myDivider.gif"> </asp:Menu>

<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1" DynamicBottomSeparatorImageUrl="myDivider.gif"> </asp:Menu>

•Separating Menu Items with Images

Menu Control-Styles

Page 1367: Dotnet Stream

1367©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.

Menu Control-Events

Menu EventsThe Menu control exposes events such as the following:

• DataBinding • DataBound • Disposed • Init • Load • MenuItemClick • MenuItemDataBound • PreRender • Unload

Page 1368: Dotnet Stream

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.

Advanced ControlsAdvanced Controls

Page 1369: Dotnet Stream

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

ASP.NET Advanced Controls

Topics for Discussion• User Controls• Composite Controls• Custom Controls• Web Parts

Page 1370: Dotnet Stream

1370©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.

User ControlsUser Controls

ASP.NET User Controls

Page 1371: Dotnet Stream

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

ASP.NET User Controls

A user control is the grouping of existing server controls into a

single container control

• User controls are included in a Web Forms page using a Register directive:

• <%@ Register TagPrefix=“Ctr" TagName="Message" Src=“Userctrl.ascx" %>

The TagPrefix determines a unique namespace for the user control

The TagName is the unique name for the user control .

The Src attribute is the virtual path to the user control

• User controls have a .ascx extension

• User control is of type System.Web.UI.UserControl, which inherits directly from System.Web.UI.Control .

Page 1372: Dotnet Stream

1372©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.

<%@ Page Language="C#" %> <%@ Register TagPrefix=“Ctr" TagName="Message" Src="userctrl_cs.ascx" %> <html> <body style="font: 10pt verdana"> <h3>A Simple User Control</h3> <Ctr:Message runat="server" id="Message1" /> </body> </html>

A user control imported into another Web Forms page. The user control in this case is just a simple static file.

Importing User Controls

Page 1373: Dotnet Stream

1373©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.

• When a Web Forms page is treated as a control, the public fields and methods of that Web Form are promoted to public properties and methods of the control as well

Exposing User Control Properties

Page 1374: Dotnet Stream

1374©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.

void SubmitBtn_Click(Object sender, EventArgs E) {

MyMessage.Text = "Message text changed!"; MyMessage.Color = "red";

}

<%@ Register TagPrefix=“Ctr" TagName="Message" Src=“Userctrl_cs.ascx" %>

<Ctr:Message id="MyMessage" Text="This is a custom message!" Color="blue" runat="server"/><asp:button text="Change Properties" OnClick="SubmitBtn_Click" runat=server/>

Exposing User Control Properties

Page 1375: Dotnet Stream

1375©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.

public String Color = "blue"; public String Text = "This is a simple message user control!";

UserCtrl.ascx.cs

<span id="Message" style="color:<%=Color%>"><%=Text%></span> <span id="Message" style="color:<%=Color%>"><%=Text%></span>

Exposing User Control Properties

Page 1376: Dotnet Stream

1376©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.

• User controls participate in the complete execution lifecycle of the request, much the way ordinary server controls do.

• A user control can handle its own events, encapsulating some of the page logic from the containing Web Forms page.

<%@ Page Language="C#" %> <%@ Register TagPrefix=“Ctr” TagName="BookList" Src="userctrl_cs.ascx" %> <html>

<body style="font: 10pt verdana"> <h3>A User Control w/ an Event</h3> <form runat="server"> <Ctr:BookList runat="server" id="BookList1" /> </form> </body>

</html>

<%@ Page Language="C#" %> <%@ Register TagPrefix=“Ctr” TagName="BookList" Src="userctrl_cs.ascx" %> <html>

<body style="font: 10pt verdana"> <h3>A User Control w/ an Event</h3> <form runat="server"> <Ctr:BookList runat="server" id="BookList1" /> </form> </body>

</html>

Encapsulating User Control Events

Page 1377: Dotnet Stream

1377©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.

Custom ControlsCustom Controls

ASP.NET Custom Controls

Page 1378: Dotnet Stream

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

ASP.NET Custom Controls

Developing and Using a Custom Server Control  • Create an ASP.NET server control.• Add metadata to the control and its members to control security

and design-time behavior.• Use the App_Code directory in an ASP.NET Web site to test your

control without manual compilation steps.• Specify a tag prefix in a configuration file and in the control's

assembly.• Compile the control into an assembly and add it to the Bin

directory.• Embed a bitmap into the control's assembly as the toolbox icon for

a visual designer.

• Use the compiled control in a page.

Page 1379: Dotnet Stream

1379©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.

Creating a Custom Control

1.Creating an ASP.NET server control.

• A simple control similar to the standard Label control. • The WelcomeLabel class derives from WebControl and defines a

Text property that allows a page developer to provide a text string to welcome a user to a site.

• WelcomeLabel appends the user's name to the text string if the user's name is present in the header sent by the user's browser

Page 1380: Dotnet Stream

1380©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.

Creating a Custom Control-Adding metadata

2.Add metadata to the control and its members to control security

and design-time behavior.(Class Level)• AspNetHostingPermissionAttribute is a code-access security

attribute. It causes the JIT compiler to check that code that links to WelcomeLabel is granted the AspNetHostingPermission permission.

• DefaultPropertyAttribute is a design-time attribute that specifies the default property of a control.

• ToolboxDataAttribute specifies the format string for the element. The string becomes the control's markup when the control is double-clicked in the toolbox or dragged from the toolbox onto the design surface. For WelcomeLabel, the string creates this element: [

AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal),AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal), DefaultProperty("Text"),ToolboxData("<{0}:WelcomeLabel runat=\"server\"> </{0}:WelcomeLabel>") ]

[ AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal),AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal), DefaultProperty("Text"),ToolboxData("<{0}:WelcomeLabel runat=\"server\"> </{0}:WelcomeLabel>") ]

Page 1381: Dotnet Stream

1381©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.

Creating a Custom Control-Adding metadata

public class WelcomeLabel : WebControl

{ [ Bindable(true),

Category("Appearance"),

DefaultValue(""),

Description("The welcome message text."),

Localizable(true) ]

public virtual string Text

{

get {

string s = (string)ViewState["Text"]; return (s == null) ? String.Empty : s;

}

set

{ ViewState["Text"] = value; }

}

Page 1382: Dotnet Stream

1382©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.

Creating a Custom Control-Adding metadata

protected override void RenderContents(HtmlTextWriter writer)

{

writer.WriteEncodedText(Text);

if (Context != null)

{

string s = Context.User.Identity.Name;

if (s != null && s != String.Empty)

{

string[] split = s.Split('\\');

int n = split.Length - 1;

if (split[n] != String.Empty)

{

writer.Write(", "); writer.Write(split[n]);

} } } writer.Write("!"); } }

Page 1383: Dotnet Stream

1383©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.

Creating a Custom Control-Adding metadata

The following attributes applied to the Text property of WelcomeLabel are standard design-time attributes that you will generally apply to all public properties of your controls:

• BindableAttribute, specified as true or false, specifies for visual designers whether it is meaningful to bind the property to data.

• CategoryAttribute specifies how to categorize the property in the visual designer's property browser.

• DescriptionAttribute specifies a brief description of the property. In Visual Studio 2005, the property browser displays the description of the selected property at the bottom of the Properties window.

• DefaultValueAttribute specifies a default value for the property. This value should be the same as the default value you return from the property accessor (getter).

• LocalizableAttribute, specified as true or false, specifies for visual designers whether it is meaningful to localize the property. When a property is marked Localizable(true), the visual designer includes it when serializing localized resources.

Page 1384: Dotnet Stream

1384©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.

Creating a Custom Control -Using App_Code dir

3.Using the App_Code Directory to Test Controls Without Compilation

• Use the ASP.NET dynamic compilation feature to test your control in a page without compiling the control into an assembly.

• ASP.NET dynamically compiles code placed in the App_Code directory under an ASP.NET Web site's root.

• Classes in source files in App_Code can thus be accessed from pages without being manually compiled into assemblies.

Page 1385: Dotnet Stream

1385©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.

Creating a Custom Control-Creating Tag Prefix

4.Creating a Tag Prefix

• A tag prefix is the prefix, such as "asp" in <asp:Table />, that appears before a control's type name when the control is created declaratively in a page.

• To enable the control to be used declaratively in a page, ASP.NET needs a tag prefix that is mapped to your control's namespace.

• A page developer can provide a tag prefix/namespace mapping by adding a @ Register directive on each page that uses the custom control

<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.VB.Controls"%>

• A page developer can specify the tag prefix/namespace mapping in the Web.config file

<configuration>

<system.web>

<pages> <controls>

<add tagPrefix="aspSample" namespace="Samples.AspNet.CS.Controls"> </add>

</controls> </pages>

</system.web>

</configuration>

Page 1386: Dotnet Stream

1386©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.

Creating a Custom Control-Compiling the control

5.To compile the control into an assembly• Set the Windows environment PATH variable of your computer to

include the path to your .NET Framework installation by following these steps:

In Windows, right-click My Computer, select Properties, click the Advanced tab, and click the Environment Variables button.

In the System variables list, double-click the Path variable. In the Variable value text box, add a semicolon (;) to the end of

the existing values in the text box, and then type the path of your .NET Framework installation. The .NET Framework is generally installed in the Windows installation directory at \Microsoft.NET\Framework\versionNumber.

Click OK to close each dialog box.

• Run the following command from the directory you created for source files in the first procedure of this walkthrough

csc /t:library /out:Samples.AspNet.CS.Controls.dll /r:System.dll /r:System.Web.dll *.cs

Page 1387: Dotnet Stream

1387©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.

Creating a Custom Control-Embedding Icon

6.Embed a bitmap into the control's assembly as the toolbox icon for a visual designer

To embed an icon in the control's assembly • Create or obtain a 16-by-16-pixel bitmap as the toolbox icon for your control.

• Name the bitmap WelcomeLabel.bmp.

• Add the bitmap file to the directory (CustomControlsCS or CustomControlsVB) where you have the source files for the WelcomeLabel control.

• Run the following command from the directory that contains the source files:

csc /res:WelcomeLabel.bmp,MyControl.WelcomeLabel.bmp /t:library /out:MyControl.dll /r:System.dll /r:System.Web.dll *.cs

7.To add a namespace/tag prefix mapping using the TagPrefixAttribute

• Create a file named AssemblyInfo.cs or AssemblyInfo.vb in your source code directory and add the following code to the file.

using System;

using System.Web.UI;

[assembly: TagPrefix("Samples.AspNet.CS.Controls", "aspSample")]

Page 1388: Dotnet Stream

1388©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.

Using Custom Control

8.Using the Compiled Custom Control in an ASP.NET PageTo test the compiled version of the custom control, make the control's

assembly accessible to pages in the Web site.

• To make the control's assembly accessible to the Web site Create a Bin directory under the root of the Web site. Copy the control assembly to the Bin directory. Delete the control's source file from the App_Code directory.

Page 1389: Dotnet Stream

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

ASP.NET Web Parts

Web PartsWeb Parts

Page 1390: Dotnet Stream

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

ASP.NET Web Parts“Web parts provides an infrastructure to create

customizable web pages”Topics for discussion:

• Web Part Basics

• Building Web Parts Creating Web Part Manganer Creating Web PartZone

• Changing Layout Orientation and disabling changes

• Zone Templates

• Changing the mode of the Web page Browse (Minimize/Maximize/Restore) Design (Drag and Drop) Catalog (Add webparts/ Add to webparts) Edit (Apperance/ Layout/ Behaviour)

• Web Part Verbs• Connecting Web Parts

Page 1391: Dotnet Stream

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

Web Part Basics• Web parts , part of the larger Portal Framework , provides an

outstanding way to build modular web site that can be customized with dynamically reapplied settings on a per-user basis.

• Web parts are objects in the Portal framework which the end user can open, close, minimize, maximize, or move from one part of the page to another.

• The portal framework enables in the building of web pages that contain multiple web parts – which are part of the ASP.NET server control framework and are used like any other ASP.NET server controls

Web Parts-Basics

Page 1392: Dotnet Stream

1392©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.

The key components of the Web Part framework are: • The System.Web.UI.WebControls.WebParts.WebPart class—The

WebPart is the base class outlining configuration properties that allow sub classes to be members of Web Part Zones.

• The System.Web.UI.WebControls.WebParts.WebPartZone control—The WebPartZone control is a wrapper around a collection of Web Parts.

• The System.Web.UI.WebControls.WebParts.WebPartManager control—One WebPartManager is linked to each page that uses Web Parts.

• These three controls combine together to create Web pages that are visually and functionally similar to complex desktop applications.

Web Parts-Key Components

Page 1393: Dotnet Stream

1393©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.

Creating Web Part Manager• The Portal framework defines everyhting in zones.There are zones

for laying out and editing content.• The zones that a page are incorporates are managed by a Portal

Framework Manager-Web Part Manager• The WebPartManager control is an ASP.NET control that completely

managfes the state and content of zones on per-user basis.• A single WebPartManager manages only one page in the

application that works with the Portal framework• Drag and drop a WebPartManager control from ToolBox to the Web

page yet to contain Webparts

<asp:WebPartManager ID="WebPartManager1" runat="Server" /> </asp:WebPartManager>

<asp:WebPartManager ID="WebPartManager1" runat="Server" /> </asp:WebPartManager>

Web Parts-Creating Web Part Manager

Page 1394: Dotnet Stream

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

<asp:WebPartZone ID="WebPartZone1" runat="server“></asp:WebPartZone>

<asp:WebPartZone ID="WebPartZone1" runat="server“></asp:WebPartZone>

Web Parts-Creating Web Part Zones

Creating Web PartZone

• Web pages are constructed in al linear fashion either horizontally or vertically.

• Web zones define specific rows or columns as individual content areas managed by the WebPart Manager

• Drag and drop a WebPartZone control to each area in a table wherever webparts are necessary

Page 1395: Dotnet Stream

1395©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.

Changing Layout Orientation and disabling changes• The Web Parts within a WebPartZone control can be displayed

either horizontally or vertically using the LayoutOrientaton attribute

• The Web Parts can be prevented from user modification like drag and drop by setting the AllowLayoutChange attribute

<asp:WebPartZone ID="WebPartZone1" runat="server“ AllowLayoutChange=“false”>

</asp:WebPartZone>

<asp:WebPartZone ID="WebPartZone1" runat="server“ AllowLayoutChange=“false”>

</asp:WebPartZone>

<asp:WebPartZone ID="WebPartZone1" runat="server“ LayoutOrientation=“Horizontal”></asp:WebPartZone>

<asp:WebPartZone ID="WebPartZone1" runat="server“ LayoutOrientation=“Horizontal”></asp:WebPartZone>

Web Parts-Web Part Zones Properties

Page 1396: Dotnet Stream

1396©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.

• When using VS2005, by default the IDE creates a Microsoft SQL Server Express Edition file called ASPNETDB.MDF and stores it in the App_Data folder of web Projects.

• This database file is where the Portal Framework stores all the customization points

Building Web Parts

Page 1397: Dotnet Stream

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

Web Parts-Changing mode of web page

Changing the mode of the Web page• Browse (Minimize/Maximize/Restore)

End user cannot edit or move sections of the page• Design (Drag and Drop)

Enables end user to rearrange the order of the page’s modular components,delete items from a zone, or move items from one page zone to another

• Catalog (Add webparts/ Add to webparts) Displays a list of available webparts that can be placed in a

page.• Edit (Apperance/ Layout/ Behaviour)

Enables end user to select particular sections on the page for editing like changing part’s title,color or even setting custom properties

Page 1398: Dotnet Stream

1398©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.

protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DropDownList1.Items.Clear(); DropDownList1.Items.Add("Design"); DropDownList1.Items.Add("Browse"); DropDownList1.Items.Add("Catalog"); DropDownList1.Items.Add("Edit"); } }

Changing the mode of the Web pageprotected void Page_Init(object sender, EventArgs e)

{ foreach (WebPartDisplayMode wp1 in

WebPartManager1.SupportedDisplayModes) { string modeName = wp1.Name; ListItem dd = new ListItem(modeName, modeName); DropDownList1.Items.Add(dd); }

}

Web Parts-Changing mode of web page

Page 1399: Dotnet Stream

1399©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.

protected void DropDownList1_SelectedIndexChanged1(object sender,

EventArgs e) { if (DropDownList1.SelectedValue == "Design") { WebPartManager1.DisplayMode =

WebPartManager.DesignDisplayMode; } else if (DropDownList1.SelectedValue == "Browse") { WebPartManager1.DisplayMode =

WebPartManager.BrowseDisplayMode; }

Web Parts-Changing mode of web page

Page 1400: Dotnet Stream

1400©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.

else if (DropDownList1.SelectedValue == "Catalog") { WebPartManager1.DisplayMode =

WebPartManager.CatalogDisplayMode; } else if (DropDownList1.SelectedValue == "Edit") { WebPartManager1.DisplayMode =

WebPartManager.EditDisplayMode; } else if (DropDownList1.SelectedValue == "Connect") { WebPartManager1.DisplayMode =

WebPartManager.ConnectDisplayMode; } }

Web Parts-Changing mode of web page

Page 1401: Dotnet Stream

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

Web Parts-Catalog Zone

Adding web parts to a page

Catalog zone is further divided into three types:

• Page

• Declarative

• Import.

<asp:PageCatalogPart>

Page catalog displays the number of web parts that are closed by using this option.

• The ASP.NET 2.0 Portal framework enables an end user to add Web parts to a page provided the user has a list of items to add.

• Includes Webparts not displayed on the page by default and web capabilities of the Portal Framework

Page 1402: Dotnet Stream

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

<asp:CatalogZone ID="CatalogZone1" runat="server" > <ZoneTemplate><asp:PageCatalogPart ID="PageCatalogPart1" runat="server“/> </ZoneTemplate>

</asp:CatalogZone>

<asp:CatalogZone ID="CatalogZone1" runat="server" > <ZoneTemplate><asp:PageCatalogPart ID="PageCatalogPart1" runat="server“/> </ZoneTemplate>

</asp:CatalogZone>

Web Parts-Page Catalog Part

PageCatalogPart• Add a CatalogZone to the web page.• Add a PageCatalogPart within a ZoneTemplate.• To get some items in the Catalog delete, some webparts.• Select a webpart and a zone and click “Add” to add a particular

webpart to a zone.

Page 1403: Dotnet Stream

1403©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.

<ZoneTemplate><asp:DeclarativeCatalogPart ID="DeclarativeCatalogPart1" runat="server"><WebPartsTemplate> <asp:Button ID="Button1" runat="server" Text="AnnButton" /></WebPartsTemplate></asp:DeclarativeCatalogPart></ZoneTemplate>

<ZoneTemplate><asp:DeclarativeCatalogPart ID="DeclarativeCatalogPart1" runat="server"><WebPartsTemplate> <asp:Button ID="Button1" runat="server" Text="AnnButton" /></WebPartsTemplate></asp:DeclarativeCatalogPart></ZoneTemplate>

Web Parts-Declarative Catalog Part

Moving Web parts

<asp:DeclarativeCatalogPart>Declarative catalog displays the number of elements that are

added in designmode in catalog zone.

To enable the end user to add more than one of any particular Web part to a page

Place the <asp:DeclarativeCatalogPart> control within the <ZoneTemplate> element of <asp:CatalogZone.>

Page 1404: Dotnet Stream

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

Web Parts-Declarative Catalog Part

• The templated <asp:DeclarativeCatalogPart> control needs a <WebPartsTemplate> to place the controls that needs to be available to the ened user as options.

• The controls appear in a check box list in the same order in which it is declared in the <WebPartsTemplate> section.

Page 1405: Dotnet Stream

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

Web Parts-Import Catalog Part

Importing Web Parts<asp:ImportCatalogPart>Import Catalog displays the number of elements that are

selected to import. You canimport files that have the ".WebPart" extension.

• To export a file as a .WebPart type file, add the following line to web.config.<webParts enableExport="true"></webParts>

• Set the ExportMode property of the control to all. • If the control is derived from WebPart, do the following<aspSample:CustomWebPart id="Sample" runat="server"

ExportMode="All" /> Or, you can write the following code on page load.

GenericWebPart qwp=new GenericWebPart();gwp = WebUserControl2_1.Parentgwp.ExportMode = WebPartExportMode.All

Page 1406: Dotnet Stream

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

Web Parts-Modifying Settings using EditorZone

<asp:EditorZone>• In edit mode, web parts can be edited at runtime as

well. Editing a web part is further divided into four types: Appearance, Behavior, Property, and Layout.

Place editor zone on the page. Place AppearanceEditorPart and LayoutEditorPart in theeditor

zone. Run the application and select edit mode from the option box. Click edit from the menu available for web parts.

Page 1407: Dotnet Stream

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

<asp:EditorZone ID="EditorZone1" runat="server"><ZoneTemplate><asp:AppearanceEditorPart ID="AppearanceEditorPart1" runat="server" /><asp:BehaviorEditorPart ID="BehaviorEditorPart1" runat="server" /><asp:LayoutEditorPart ID="LayoutEditorPart1" runat="server" /><asp:PropertyGridEditorPart ID="PropertyGridEditorPart1" runat="server" /></ZoneTemplate> </asp:EditorZone>

<asp:EditorZone ID="EditorZone1" runat="server"><ZoneTemplate><asp:AppearanceEditorPart ID="AppearanceEditorPart1" runat="server" /><asp:BehaviorEditorPart ID="BehaviorEditorPart1" runat="server" /><asp:LayoutEditorPart ID="LayoutEditorPart1" runat="server" /><asp:PropertyGridEditorPart ID="PropertyGridEditorPart1" runat="server" /></ZoneTemplate> </asp:EditorZone>

Web Parts-Modifying Settings using EditorZone

Page 1408: Dotnet Stream

1408©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.

Modifying The Web Part Settings

<asp:EditorZone>

Web Parts-Modifying Settings using EditorZone

Page 1409: Dotnet Stream

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

Web Part Verbs• Web part verbs declare the actions of the items that

appear in the title.• The <asp:WebPartZone> control allows to control these

verbs by nesting the appropriate verb elements within the <asp:WebPartZone> element

<CloseVerb/>

<ConnectVerb /> <EditVerb /> <ExportVerb /> <HelpVerb /> <MinimizeVerb /> <RestoreVerb />

<CloseVerb Enabled="false" /><CloseVerb Visible="true" /><CloseVerb ImageUrl="bullet.gif" />

<CloseVerb Enabled="false" /><CloseVerb Visible="true" /><CloseVerb ImageUrl="bullet.gif" />

Web Parts-Verbs

Page 1410: Dotnet Stream

1410©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.

Connecting Web parts

Connecting Web Parts

• The <asp:ConnectionsZone> control allows to make property connections between two Web parts on the same page.

Page 1411: Dotnet Stream

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.

Server Side Data AccessServer Side Data Access

Page 1412: Dotnet Stream

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

ASP.NET Server Side Data Access

Data BindingData Binding

Page 1413: Dotnet Stream

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

Data Binding Model

Page 1414: Dotnet Stream

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

ASP.NET Data Controls

Data ControlsData Controls

Page 1415: Dotnet Stream

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

ASP.NET Data Controls

Topics for discussion:• Data Source Controls

SqlDataSource ObjectDataSource AccessDataSource SiteMapDataSource XMLDataSource

• Data Bound Controls DataGrid GridView DataList DetailsView FormView Repeater

Page 1416: Dotnet Stream

1416©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.

DataDataGridViewGridView

DataListDataList

DetailsViewDetailsView

FormViewFormView

RepeaterRepeater

ReportViewerReportViewer

SqlDataSourceSqlDataSource

AccessDataSourceAccessDataSourceObjectDataSourceObjectDataSource

XMLDataSourceXMLDataSource

SiteMapDataSourceSiteMapDataSource

Data ControlsData Controls

Data Source

Data Bound

ASP.NET Data Controls

Page 1417: Dotnet Stream

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

ASP.NET Data Source Controls

Data Source ControlsData Source Controls

Page 1418: Dotnet Stream

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

Data Source Controls

• Data source controls have no rendering, but instead represent a particular backend data store, for example a database, business object, XML file, or XML Web Service

• Data source controls also enable rich capabilities over data - such as sorting, paging, filtering, updating, deleting, and inserting - that data-bound UI controls can automatically use.

ASP.NET Data Source Controls

Page 1419: Dotnet Stream

1419©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.

Name Description

SqlDataSource

Enables binding to a SQL database represented by an ADO.NET provider, such as Microsoft™ SQL Server, OLEDB, ODBC, or Oracle.

ObjectDataSource

Enables binding to a middle-tier object such as a data access layer or business component.

AccessDataSource

Enables binding to a Microsoft™ Access (Jet) database.

SiteMapDataSource

Enables binding to the hierarchy exposed by an ASP.NET 2.0 site navigation provider.

XmlDataSource

Enables binding to an XML file or document.

ASP.NET Data Source Controls

Page 1420: Dotnet Stream

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

ASP.NET SqlDataSource Control

• Data binding to SQL Database

Microsoft SQL Server, Oracle, DB2, etc.

• Two-way data binding supported

SelectCommand

InsertCommand, UpdateCommand, and DeleteCommand

• Optional caching of query results

• Parameterized operation

SqlDataSourceSqlDataSource

Enables binding to a SQL database represented by an ADO.NET provider, such as Microsoft™ SQL Server, OLEDB, ODBC, or Oracle.

Page 1421: Dotnet Stream

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

<asp:SqlDataSource ID="Titles" ConnectionString="<%$ connectionStrings:pubs %>" RunAt="server“ SelectCommand="select title_id, title, price from titles" /><asp:DataGrid

DataSourceID="Titles" RunAt="server" />

<asp:SqlDataSource ID="Titles" ConnectionString="<%$ connectionStrings:pubs %>" RunAt="server“ SelectCommand="select title_id, title, price from titles" /><asp:DataGrid

DataSourceID="Titles" RunAt="server" />

SqlDataSource Control

Page 1422: Dotnet Stream

1422©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.

NameName DescriptionDescription

ConnectionString Connection string used to connect to data source

SelectCommand Command used to perform queries

InsertCommand Command used to perform inserts

UpdateCommand Command used to perform updates

DeleteCommand Command used to perform deletes

DataSourceMode Specifies whether DataSet or DataReader is used(default = DataSet)

ProviderName Specifies provider (default = SQL Server .NET provider)

SqlDataSource Control Properties

Page 1423: Dotnet Stream

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

ASP.NET ObjectDataSource Control

• Most applications encapsulate data logic

Best practice and simplifies maintenance

Embedding SQL code is not recommended

• ObjectDataSource

Bind to custom business objects

Visual Studio data components

Parallels SqlDataSource in object model

Enables binding to a middle-tier object such as a data access layer or business component.

ObjectDataSourceObjectDataSource

<asp:ObjectDataSource ID=“MySource” <asp:ObjectDataSource ID=“MySource” TypeName=“CustomersDB” TypeName=“CustomersDB” SelectMethod=“GetCustomersByRegion” SelectMethod=“GetCustomersByRegion” UpdateMethod=“UpdateCustomer” UpdateMethod=“UpdateCustomer” runat=“server”/>runat=“server”/>

<asp:ObjectDataSource ID=“MySource” <asp:ObjectDataSource ID=“MySource” TypeName=“CustomersDB” TypeName=“CustomersDB” SelectMethod=“GetCustomersByRegion” SelectMethod=“GetCustomersByRegion” UpdateMethod=“UpdateCustomer” UpdateMethod=“UpdateCustomer” runat=“server”/>runat=“server”/>

Page 1424: Dotnet Stream

1424©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.

• The ObjectDataSource control allows developers to structure their

applications using the traditional three-tiered architecture and still

take advantage of the ease-of-use benefits of the declarative

databinding model in ASP.NET.

• Instead of a ConnectionString property, ObjectDataSource exposes

a TypeName property that specifies an object type (class name) to

instantiate for performing data operations.

• The ObjectDataSource control supports properties such as

SelectMethod, UpdateMethod, InsertMethod, and DeleteMethod for

specifying methods of the associated type to call to perform these

data operations.

ObjectDataSource Control

Page 1425: Dotnet Stream

1425©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.

ObjectDataSourceObjectDataSourceWeb Page

DataSourceID DataSourceID = ObjectDataSource1= ObjectDataSource1

Northwind Northwind DatabaseDatabase

OrdersComponentOrdersComponent

OrderItemsComponentOrderItemsComponent

CompaniesComponentCompaniesComponent

<asp:ObjectDataSource<asp:ObjectDataSourceIDID = ObjectDataSource1 = ObjectDataSource1TypeName = TypeName = OrdersComponentOrdersComponentSelectMethodSelectMethod = GetOrders = GetOrdersUpdateMethodUpdateMethod = UpdateOrder = UpdateOrderDeleteMethodDeleteMethod = DeleteOrder = DeleteOrder

Returns IEnumerable of OrdersReturns IEnumerable of Orders• Order.OrderIDOrder.OrderID• Order.OrderNameOrder.OrderName• Order.OrderDateOrder.OrderDate

ObjectDataSource Control

Page 1426: Dotnet Stream

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

ASP.NET AccessDataSource Control

• The AccessDataSource control is a data source control that represents a connection to a Microsoft™ Access database.

• The AccessDataSource control derives from SqlDataSource, but exposes a simple DataFile property for specifying the path to an MDB file, instead of the complete connection string.

Enables binding to a Microsoft™ Access (Jet) database

AccessDataSourceAccessDataSource

Page 1427: Dotnet Stream

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

ASP.NET SiteMapDataSource Control

• The SiteMapDataSource enables to work with data stored in the Web site’s SiteMap configuration file.

• The control does not support any of the data caching options that exist in the other data source controls provided.

• The SiteMapDataSource control does not have any configuration wizards like the other data source controls.

Enables binding to the hierarchy exposed by an ASP.NET 2.0 site navigation provider.

SiteMapDataSourceSiteMapDataSource

Page 1428: Dotnet Stream

1428©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.

The XmlDataSource control belongs to the family of data source controls in ASP.NET, which enables a declarative databinding model against a variety of underlying data stores. The XMLDataSource control supports declarative databinding to XML files. XmlDataSource is an example of a hierarchical data source, which supports the required interfaces to allow hierarchical data-bound controls, such as TreeView and Menu, to traverse the hierarchy of nodes to produce their rendering.

Enables binding to an XML file or document

XMLDataSourceXMLDataSource

ASP.NET XMLDataSource Control

Page 1429: Dotnet Stream

1429©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.

XmlDataSource supports a • DataFile property for specifying the path to an XML data file to be

used as input.• TranformFile property to apply an XSLT transformation to the data • XPath property for specifying a subset of nodes to expose from the

data source.

XMLDataSource Control

Page 1430: Dotnet Stream

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

ASP.NET Data Bound Controls

Data Bound ControlsData Bound Controls

Page 1431: Dotnet Stream

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

Data-bound controls are UI controls that render data as markup

to the requesting client device or browser. • A data-bound control can auto-bind to data exposed from a data

source and will fetch data at the appropriate time in the page request lifecycle.

• These controls can optionally take advantage of data source capabilities such as sorting, paging, filtering, updating, deleting, and inserting.

• A data-bound control connects to a data source control through its DataSourceID property

ASP.NET Data Bound Controls

Page 1432: Dotnet Stream

1432©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.

Name Description

GridView

Renders data in a grid format. This control is an evolution of the DataGrid control, and can automatically take advantage of data source capabilities.

DetailsView

Renders a single data item in a table of label/value pairs, similar to the form view in Microsoft™ Access. This control can also automatically take advantage of data source capabilities.

FormView

Renders a single data item at a time in a form defined by a custom template. Renders a single data item in a table of label/value pairs, similar to the form view in Microsoft™ Access. This control can also automatically take advantage of data source capabilities.

ASP.NET Data Bound Controls

Page 1433: Dotnet Stream

1433©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.

• One of the most powerful server controls in ASP.NET is no doubt the DataGrid control. The DataGrid control is a multi-column, data-bound ASP.NET server control.

• Using the DataGrid control, you can display records from a database using a variety of formats.

• You can also edit, update, and delete records from the database using the DataGrid control. In this first part of the ASP.NET server controls series, I will show you how to use the DataGrid control to develop compelling Web applications.

ASP.NET Data Grid Control

Page 1434: Dotnet Stream

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

Data Grid Control-Auto FormatIn the default Web form, add a DataGrid control. To change the format of the DataGrid control, right-click on it and select

Auto-Format.... Choose any scheme

Page 1435: Dotnet Stream

1435©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.

There are two ways in which you can configure the DataGrid control:

Using the Property Builder • Modifying the HTML codes manually • To modify the HTML codes behind the DataGrid control, switch to

codeview.

Data Grid Control-Configuration

Page 1436: Dotnet Stream

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

<ASP:DataGrid id="MyDataGrid" runat="server"

Width="700px"

CellPadding=4

Font-Name="Verdana"

Font-Size="8pt"

HeaderStyle-BackColor="#aaaadd"

EnableViewState="False" Font-Names="Verdana" ForeColor="#333333" GridLines="None"

>

<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

<EditItemStyle BackColor="#2461BF" />

<SelectedItemStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />

<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />

<AlternatingItemStyle BackColor="White" />

<ItemStyle BackColor="#EFF3FB" />

<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

</ASP:DataGrid>

Data Grid Control-Displaying Data

Page 1437: Dotnet Stream

1437©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.

SqlConnection myConnection = new SqlConnection("server=p3c20014;database=pubs;user id =sa; pwd=sa");

SqlDataAdapter myCommand =

new SqlDataAdapter("select * from Authors", myConnection);

DataSet ds = new DataSet();

try {

myCommand.Fill(ds, "Authors");

MyDataGrid.DataSource=ds.Tables["Authors"].DefaultView;

MyDataGrid.DataBind();

}

catch (Exception ex){

throw (ex);

}

finally{

myConnection.Close();

}

Data Grid Control-Displaying Data

Page 1438: Dotnet Stream

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

Data Grid Control-Parameterized Select

Page 1439: Dotnet Stream

1439©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.

public void GetAuthors_Click(Object sender, EventArgs E)

{

String selectCmd = "select * from Authors where state = @State";

SqlConnection myConnection = new SqlConnection("server=p3c20037;database=pubs;uid=sa;pwd=sa");

SqlDataAdapter myCommand = new SqlDataAdapter(selectCmd, myConnection);

myCommand.SelectCommand.Parameters.Add(new SqlParameter("@State", SqlDbType.NVarChar, 2));

myCommand.SelectCommand.Parameters["@State"].Value = MySelect.Value;

DataSet ds = new DataSet();

try {

myCommand.Fill(ds, "Authors");

MyDataGrid.DataSource= ds.Tables["Authors"].DefaultView;

MyDataGrid.DataBind();

}

catch (Exception ex){ throw (ex);

}

finally{ myConnection.Close(); }

}

Data Grid Control-Parameterized Select

Page 1440: Dotnet Stream

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

Data Grid Control-Edit/Update/Cancel

Page 1441: Dotnet Stream

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

Data Grid Control-Edit/Update/Cancel

Page 1442: Dotnet Stream

1442©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.

protected void MyDataGrid_Edit(Object sender,

DataGridCommandEventArgs e)

{

MyDataGrid.EditItemIndex =

(int)e.Item.ItemIndex;

BindGrid();

}

protected void MyDataGrid_Cancel(Object sender, m

DataGridCommandEventArgs e)

{

MyDataGrid.EditItemIndex = -1;

BindGrid();

}

Data Grid Control-Edit/Update/Cancel

Page 1443: Dotnet Stream

1443©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.

protected void BindGrid()

{

SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors", myConnection);

DataSet ds = new DataSet();

myCommand.Fill(ds, "Authors");

MyDataGrid.DataSource=ds.Tables["Authors"].DefaultView;

MyDataGrid.DataBind();

}

protected void Page_Load(object sender, System.EventArgs e)

{

myConnection = new SqlConnection("server=p3c20037;database=Roy;uid=sa;pwd=sa");

if (!IsPostBack)

BindGrid();

}

Data Grid Control-Edit/Update/Cancel

Page 1444: Dotnet Stream

1444©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.

String updateCmd = "UPDATE Authors SET au_id = @Id, au_lname = @LName,

au_fname = @FName, phone = @Phone, "+ "address = @Address, city = @City,

state = @State, zip = @Zip, contract = @Contract where au_id = @Id";

SqlCommand myCommand = new SqlCommand(updateCmd, myConnection);

myCommand.Parameters.Add(new SqlParameter("@Id", SqlDbType.NVarChar, 11));

myCommand.Parameters.Add(new SqlParameter("@LName", SqlDbType.NVarChar, 40));

myCommand.Parameters.Add(new SqlParameter("@FName", SqlDbType.NVarChar, 20));

myCommand.Parameters.Add(new SqlParameter("@Phone", SqlDbType.NChar, 12));

myCommand.Parameters.Add(new SqlParameter("@Address", SqlDbType.NVarChar, 40));

myCommand.Parameters.Add(new SqlParameter("@City", SqlDbType.NVarChar, 20));

myCommand.Parameters.Add(new SqlParameter("@State", SqlDbType.NChar, 2));

myCommand.Parameters.Add(new SqlParameter("@Zip", SqlDbType.NChar, 5));

myCommand.Parameters.Add(new SqlParameter("@Contract", SqlDbType.NVarChar,1));

myCommand.Parameters["@Id"].Value = MyDataGrid.DataKeys[(int)e.Item.ItemIndex];

Data Grid Control-Edit/Update/Cancel

Page 1445: Dotnet Stream

1445©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.

String[] cols = {"@Id","@LName","@FName","@Phone","@Address","@City","@State","@Zip","@Contract"};

Message.InnerHtml = "";

int numCols = e.Item.Cells.Count;

for (int i=2; i<numCols-1; i++) and last column

{

String colvalue =((System.Web.UI.WebControls.TextBox)

e.Item.Cells[i].Controls[0]).Text;

myCommand.Parameters[cols[i-1]].Value = colvalue;

}

if (String.Compare(((TextBox)e.Item.Cells[numCols-1].Controls[0]).Text, "true", true, CultureInfo.InvariantCulture)==0)

myCommand.Parameters["@Contract"].Value = "1";

else

myCommand.Parameters["@Contract"].Value = "0";

myCommand.Connection.Open();

Data Grid Control-Edit/Update/Cancel

Page 1446: Dotnet Stream

1446©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.

try

{

myCommand.ExecuteNonQuery();

Message.InnerHtml = "<b>Record Updated</b><br>";

MyDataGrid.EditItemIndex = -1;

}

catch (SqlException exc)

{

if (exc.Number == 2627)

Response.Write("ERROR: A record already exists with the same primary key");

else

Response.Write("ERROR: Could not update record, please ensure the fields are correctly filled out");

}

myCommand.Connection.Close();

BindGrid(); }

Data Grid Control-Edit/Update/Cancel

Page 1447: Dotnet Stream

1447©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.

If auto event wireup is set to false - Map the respective events.

If auto event wireup is set to false - Map the respective events.

Data Grid Control-Mapping Events

Page 1448: Dotnet Stream

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

You can add controls to Item and Edit item

template

Data Grid Control-Template Columns

Page 1449: Dotnet Stream

1449©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.

The ASP.NET GridView control is the successor to the v1.x DataGrid, adding the ability to take advantage of specific capabilities of ASP.NET data source controls.

The GridView offers • Functionality improvements over the DataGrid, such as

• The ability to define multiple primary key fields,

• New field types and templating options.

• Exposes a new model for page developers to handle or cancel events.

GridViewGridView

ASP.NET GridView Control

Page 1450: Dotnet Stream

1450©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.

• Enhanced DataGrid control

Renders sets of records as HTML tables

• Built-in sorting, paging, selecting, updating, and deleting support

• Supports rich assortment of field types, including CheckBoxFields

Declared in <Columns> element

• Highly customizable UI

GridView Control

<asp:GridView DataSourceID="Employees" Width="100%" <asp:GridView DataSourceID="Employees" Width="100%" RunAt="server" />RunAt="server" />

<asp:GridView DataSourceID="Employees" Width="100%" <asp:GridView DataSourceID="Employees" Width="100%" RunAt="server" />RunAt="server" />

<asp:SqlDataSource <asp:SqlDataSource ID="Employees" RunAt="server“ ID="Employees" RunAt="server“ ConnectionString= "Provider=SQLOLEDB;Data ConnectionString= "Provider=SQLOLEDB;Data

Source=localhost;Password=sa;User ID=sa;Initial Source=localhost;Password=sa;User ID=sa;Initial Catalog=Northwind“ SelectCommand="SELECT * FROM Employee"Catalog=Northwind“ SelectCommand="SELECT * FROM Employee" ./>./>

Page 1451: Dotnet Stream

1451©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.

Name Description

BoundField Renders columns of text from fields in data source

ButtonField Renders columns of buttons (push button, image, or link)

CheckBoxField Renders Booleans as check boxes

HyperLinkField Renders columns of hyperlinks

TemplateField Renders columns using HTML templates

CommandField Renders controls for selecting and editing GridView data

ImageField Renders columns of images from URL text

GridView Control-Field Types

Page 1452: Dotnet Stream

1452©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.

Displaying Fields with a GridView

<asp:GridView DataSourceID="ProductsSource" AutoGenerateColumns="false" Runat="Server"> <Columns> <asp:BoundField HeaderText="Last Name" DataField="LastName" NullDisplayText="no value" /> <asp:BoundField HeaderText="First Name" DataField="FirstName" NullDisplayText="no value" /></Columns> </asp:GridView> <asp:SqlDataSource ID="ProductsSource" ConnectionString= "Provider=SQLOLEDB;Data Source=localhost;Password=sa;User ID=sa;Initial Catalog=Northwind“ SelectCommand="SELECT * FROM Employees" Runat="Server" />

GridView Control-Displaying Fields

Page 1453: Dotnet Stream

1453©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.

GridView Control-Displaying Fields

Page 1454: Dotnet Stream

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

<asp:GridView DataSourceID="TitlesSource" AllowSorting="true" AllowPaging="true" Runat="Server" /> <asp:SqlDataSource ID="TitlesSource" ConnectionString= "Provider=SQLOLEDB;Data Source=localhost;Password=sa;User ID=sa;Initial Catalog=Northwind“ SelectCommand="SELECT * FROM Titles" Runat="Server" />

<asp:GridView DataSourceID="TitlesSource" AllowSorting="true" AllowPaging="true" Runat="Server" /> <asp:SqlDataSource ID="TitlesSource" ConnectionString= "Provider=SQLOLEDB;Data Source=localhost;Password=sa;User ID=sa;Initial Catalog=Northwind“ SelectCommand="SELECT * FROM Titles" Runat="Server" />

GridView Control -Sorting and Paging

Sorting and Paging Records with the GridView Control • When the GridView control's AllowSorting property has the value

true- sort the columns in a GridView by clicking the header columns.

• When the AllowPaging property has the value true- page through sets of records in a GridView

Page 1455: Dotnet Stream

1455©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.

GridView Control -Sorting and Paging

Page 1456: Dotnet Stream

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

<asp:GridView DataSourceID="TitlesSource" AllowPaging="true" PageSize="4" Runat="Server"> <PagerSettings Mode="NextPreviousFirstLast" FirstPageImageUrl="First.gif" PreviousPageImageUrl="Prev.gif" NextPageImageUrl="Next.gif" LastPageImageUrl="Last.gif" /> </asp:GridView>

<asp:GridView DataSourceID="TitlesSource" AllowPaging="true" PageSize="4" Runat="Server"> <PagerSettings Mode="NextPreviousFirstLast" FirstPageImageUrl="First.gif" PreviousPageImageUrl="Prev.gif" NextPageImageUrl="Next.gif" LastPageImageUrl="Last.gif" /> </asp:GridView>

GridView Control -Interfaces

The GridView control supports the following interfaces: • NextPrevious—Displays a next and previous link. • NextPreviousFirstLast—Displays a next and previous link and a

link to the first and last page. • Numeric—Displays page number links. • NumericFirstLast—Displays page number links and a link to

the first and last page.

Page 1457: Dotnet Stream

1457©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.

GridView Control -Editing

Editing with the GridView Control • Edit the data displayed by a GridView by setting the

AutoGenerateEditButton property.• When the SqlDataSource control associated with the GridView has

its UpdateCommand property set to a valid SQL UPDATE command, the database will be automatically updated.

Page 1458: Dotnet Stream

1458©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.

Editing with the GridView ControlEditing with the GridView Control

<asp:GridView DataSourceID="ProductsSource" AutoGenerateEditButton="true" DataKeyNames="ProductID" Runat="Server" /> <asp:SqlDataSource ID="ProductsSource" ConnectionString= "Provider=SQLOLEDB;Data Source=localhost;Password=sa;User ID=sa;Initial Catalog=Northwind“ SelectCommand= "SELECT ProductID,ProductName,Discontinued FROM Products" UpdateCommand="Update Products SET ProductName=@ProductName,Discontinued=@Discontinued WHERE ProductID=@ProductID" Runat="Server" />

The GridViewUpdated method executes whenever a GridView row is finished being updated The GridViewUpdated method executes whenever a GridView row is finished being updated

GridView Control -Editing

Page 1459: Dotnet Stream

1459©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.

GridView Control -Editing

Page 1460: Dotnet Stream

1460©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.

The DataList control displays a template-defined data bound list. • The DataList control supports selecting and editing.• The contents of the DataList control can be manipulated by using

templates

DataListDataList

ASP.NET Data List Control

Page 1461: Dotnet Stream

1461©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.

Template Name Description

AlternatingItemTemplate

If defined, provides the content and layout for alternating items in the DataList. If not defined, ItemTemplate is used.

EditItemTemplate If defined, provides the content and layout for the item currently being edited in the DataList. If not defined, ItemTemplate is used.

FooterTemplate If defined, provides the content and layout for the footer section of the DataList. If not defined, a footer section will not be displayed.

HeaderTemplate If defined, provides the content and layout for the header section of the DataList. If not defined, a header section will not be displayed.

ItemTemplate Required template that provides the content and layout for items in the DataList.

SelectedItemTemplate

If defined, provides the content and layout for the currently selected item in the DataList. If not defined, ItemTemplate is used.

SeparatorTemplate

If defined, provides the content and layout for the separator between items in the DataList. If not defined, a separator will not be displayed.

Data List Control Templates

Page 1462: Dotnet Stream

1462©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.

Style Property Description

AlternatingItemStyle

Specifies the style for alternating items in the DataList control.

EditItemStyle Specifies the style for the item being edited in the DataList control.

FooterStyle Specifies the style for the footer in the DataList control.

HeaderStyle Specifies the style for the header in the DataList control.

ItemStyle Specifies the style for the items in the DataList control.

SelectedItemStyle

Specifies the style for the selected item in the DataList control.

SeparatorStyle

Specifies the style for the separator between the items in the DataList control

Data List Control Styles

Page 1463: Dotnet Stream

1463©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.

The properties that control which parts are shown or hidden.

Property Description

ShowFooter Shows or hides the footer section of the DataList control.

ShowHeader Shows or hides the header section of the DataList control.

Data List Control Properties

Page 1464: Dotnet Stream

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

Data List Control-Displaying Content

Page 1465: Dotnet Stream

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

<asp:DataList id="ItemsList" BorderColor="black“ CellPadding="5“ CellSpacing="5" RepeatDirection="Vertical" RepeatLayout="Table" RepeatColumns="3“ runat="server"> <HeaderStyle BackColor="#aaaadd"> </HeaderStyle> <AlternatingItemStyle BackColor="Gainsboro"> </AlternatingItemStyle> <HeaderTemplate> List of items </HeaderTemplate> <ItemTemplate> Description: <br /> <%# DataBinder.Eval(Container.DataItem, "StringValue") %> <br /> Price: <%# DataBinder.Eval(Container.DataItem,

"CurrencyValue", "{0:c}") %> <br /> </ItemTemplate> </asp:DataList>

Data List Control-Displaying Content

Page 1466: Dotnet Stream

1466©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.

protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ItemsList.DataSource = CreateDataSource(); ItemsList.DataBind(); } }

Data List Control-Displaying Content

Page 1467: Dotnet Stream

1467©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.

public DataView CreateDataSource() { DataTable dt = new DataTable(); DataRow dr; dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32))); dt.Columns.Add(new DataColumn("StringValue", typeof(String))); dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double))); for (int i = 0; i < 9; i++) { dr = dt.NewRow(); dr[0] = i; dr[1] = "Description for item " + i.ToString(); dr[2] = 1.23 * (i + 1); dt.Rows.Add(dr); } DataView dv = new DataView(dt); return dv; }

Data List Control-Displaying Content

Page 1468: Dotnet Stream

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

ASP.NET DetailsView Control

Renders individual records• Pair with GridView for master-detail views• Or use without GridView to display individual records

Built-in paging, inserting, updating, deletingUses same field types as GridView

• Declared in <Fields> elementHighly customizable UI

DetailsViewDetailsView

Page 1469: Dotnet Stream

1469©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.

DetailsView Control

DetailsView is a data-bound user interface control that renders a single

record at a time from its associated data source, optionally providing

paging buttons to navigate between records.

It is similar to the Form View of an Access database, and is typically

used for updating and/or inserting new records.

It is often used in a master-details scenario where the selected record

of the master control (GridView, for example) determines the

DetailsView display record.

Page 1470: Dotnet Stream

1470©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.

Displaying Database Records with the DetailsView Control • The simplest thing to do with the DetailsView control is to display a

single database record. • The DetailsView control automatically displays labels and values for

every column selected.

• By default, the DetailsView control renders page numbers for navigating through the records

<asp:DetailsView DataSourceID="AuthorsSource" Runat="Server" /> <asp:SqlDataSource ID="AuthorsSource" ConnectionString= "Provider=SQLOLEDB;Data Source=localhost;Password=sa;User ID=sa;Initial Catalog=Northwind“ SelectCommand= "SELECT * FROM Authors WHERE au_id='172-32-1176'" Runat="Server" />

<asp:DetailsView DataSourceID="AuthorsSource" Runat="Server" /> <asp:SqlDataSource ID="AuthorsSource" ConnectionString= "Provider=SQLOLEDB;Data Source=localhost;Password=sa;User ID=sa;Initial Catalog=Northwind“ SelectCommand= "SELECT * FROM Authors WHERE au_id='172-32-1176'" Runat="Server" />

DetailsView Control

Page 1471: Dotnet Stream

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

<asp:DetailsView ID="DetailsView1" DataSourceID="AuthorsSource" AutoGenerateRows="false" Runat="Server"> <Fields> <asp:BoundField DataField="au_id" HeaderText="SS#:" ReadOnly="true" /> <asp:BoundField DataField="au_lname" HeaderText="Last Name:" /> <asp:BoundField DataField="au_fname" HeaderText="Last Name:" /> </Fields> </asp:DetailsView>

<asp:DetailsView ID="DetailsView1" DataSourceID="AuthorsSource" AutoGenerateRows="false" Runat="Server"> <Fields> <asp:BoundField DataField="au_id" HeaderText="SS#:" ReadOnly="true" /> <asp:BoundField DataField="au_lname" HeaderText="Last Name:" /> <asp:BoundField DataField="au_fname" HeaderText="Last Name:" /> </Fields> </asp:DetailsView>

DetailsView Control-Listing Fields

Explicitly Listing Fields with the DetailsView Control • To explicitly list the fields that the control must display set the control's AutoGenerateRows property to false and adding a <Fields> tag.

Page 1472: Dotnet Stream

1472©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.

DetailsView Control-Editing Records

Editing Database Records with the DetailsView Control

• The AutoGenerateEditButton, AutoGenerateDeleteButton, and AutoGenerateInsertButton properties are used to create the user interface for editing records.

• When using the DetailsView control for editing, an UpdateCommand, InsertCommand, and DeleteCommand must be supplied for the DataSource control associated with the DetailsView.

Page 1473: Dotnet Stream

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

<asp:DetailsView DataSourceID="AuthorsSource" AllowPaging="true" AutoGenerateEditButton="true" AutoGenerateDeleteButton="true" AutoGenerateInsertButton="true" DataKeyNames="au_id" Runat="Server" />

<asp:SqlDataSource ID="AuthorsSource" ConnectionString= "Provider=SQLOLEDB;Data Source=localhost;Password=sa;User ID=sa;Initial Catalog=Northwind“ SelectCommand= "SELECT au_id,au_lname,au_fname,contract FROM Authors" UpdateCommand= "UPDATE Authors SET au_lname=@au_lname, au_fname=@au_fname, contract=@contract WHERE au_id=@au_id" DeleteCommand="DELETE Authors WHERE au_id=@au_id" InsertCommand= "INSERT Authors (au_id,au_lname,au_fname,contract) VALUES (@au_id,@au_lname,@au_fname,@contract)" Runat="Server" />

Editing Database Records with the DetailsView Control

DetailsView Control-Editing Records

Page 1474: Dotnet Stream

1474©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.

GridView

Details View

DetailsView Control -Master/Detail FormCreating a Master/Detail Form with the DetailsView Control

• GridView control to display a list of employees. When an employee's name is clicked, the DetailsView control will display the employee's last name, and first name

Page 1475: Dotnet Stream

1475©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.

DetailsView Control -Master/Detail Form

Creating a Master/Detail Form with the DetailsView ControlCreating a Master/Detail Form with the DetailsView Control

<asp:DetailsView DataSourceID="DetailsSource" AutoGenerateRows="false" CellPadding="5" FieldHeaderStyle-Font-Bold="true" FieldHeaderStyle-HorizontalAlign="Right" Runat="Server"> <Fields> <asp:BoundField DataField="LastName" HeaderText="Last Name:" /> <asp:BoundField DataField="FirstName" HeaderText="First Name:" /> <asp:BoundField DataField="Extension" HeaderText="Extension:" /> </Fields> </asp:DetailsView>

Page 1476: Dotnet Stream

1476©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.

Creating a Master/Detail Form with the DetailsView ControlCreating a Master/Detail Form with the DetailsView Control

<asp:GridView ID="MasterGridView" DataSourceID="MasterSource" AutoGenerateColumns="false" DataKeyNames="EmployeeID" CellPadding="5" SelectedRowStyle-BackColor="#eeeeee" Runat="Server"> <Columns>

<asp:TemplateField HeaderText="Employee"> <ItemTemplate>

<asp:LinkButton CommandName="Select" Runat="Server"> <%# Eval("LastName") %>, <%# Eval("FirstName") %>

</asp:LinkButton> </ItemTemplate>

</asp:TemplateField> </Columns> </asp:GridView>

DetailsView Control -Master/Detail Form

Page 1477: Dotnet Stream

1477©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.

Creating a Master/Detail Form with the DetailsView ControlCreating a Master/Detail Form with the DetailsView Control

<asp:SqlDataSource ID="MasterSource" EnableCaching="true" CacheDuration="600" ConnectionString= "Server=localhost;database=Northwind;Trusted_Connection=true" SelectCommand="SELECT * FROM Employees" Runat="Server" /> <asp:SqlDataSource ID="DetailsSource" EnableCaching="true" CacheDuration="600" ConnectionString= "Provider=SQLOLEDB;Data Source=localhost;Password=sa;User ID=sa;Initial Catalog=Northwind“SelectCommand="SELECT * FROM Employees" FilterExpression="EmployeeID=@EmployeeID" Runat="Server"> <FilterParameters>

<asp:ControlParameter Name="EmployeeID" ControlID="MasterGridView" PropertyName="SelectedValue" />

</FilterParameters> </asp:SqlDataSource>

DetailsView Control -Master/Detail Form

Page 1478: Dotnet Stream

1478©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.

DetailsView Control -Master/Detail Form

Creating a Master/Detail Form with the DetailsView ControlThe GridView control contains a single TemplateField.

• The TemplateField displays the employee's first and last name with a LinkButton control.

• The LinkButton control's CommandName property is set to the value Select.

• When the LinkButton is clicked, the selected row is formatted with the value of the SelectedRowStyle property.

• The DetailsView control displays information on the employee currently selected in the GridView.

• The correct employee is selected by the FilterParameter defined in the SqlDataSource that is associated with the DetailsView control.

• One SqlDataSource is associated with the GridView control, and the other SqlDataSource is associated with the DetailsView control.

• Both SqlDataSource controls have the same SELECT command declared for their SelectCommand property.

Page 1479: Dotnet Stream

1479©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.

The FormView control is used to display a single record from a data source. It displays user-defined templates instead of row fields.

The FormView control supports the following features:

• Binding to data source controls, such as SqlDataSource and ObjectDataSource.

• Built-in inserting capabilities.

• Built-in updating and deleting capabilities.

• Built-in paging capabilities.

• Programmatic access to the FormView object model to dynamically set properties, handle events.

• Customizable appearance through user-defined templates, themes, and styles.

FormViewFormView

ASP.NET FormView Control

Page 1480: Dotnet Stream

1480©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.

Template type Description

EditItemTemplate

Defines the content for the data row when the FormView control is in edit mode. This template usually contains input controls and command buttons with which the user can edit an existing record.

EmptyDataTemplate

Defines the content for the empty data row displayed when the FormView control is bound to a data source that does not contain any records. This template usually contains content to alert the user that the data source does not contain any records.

FooterTemplate

Defines the content for the footer row. This template usually contains any additional content you would like to display in the footer row.

FormView Control Templates

Page 1481: Dotnet Stream

1481©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.

Template type Description

HeaderTemplate

Defines the content for the header row. This template usually contains any additional content you would like to display in the header row.

ItemTemplate Defines the content for the data row when the FormView control is in read-only mode. This template usually contains content to display the values of an existing record.

InsertItemTemplate

Defines the content for the data row when the FormView control is in insert mode. This template usually contains input controls and command buttons with which the user can add a new record.

PagerTemplate Defines the content for the pager row displayed when the paging feature is enabled (when the AllowPaging property is set to true).

FormView Control Templates

Page 1482: Dotnet Stream

1482©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.

FormView Control –Binding to Data

Binding to Data• The FormView control can be bound to a data source control (such

as SqlDataSource, AccessDataSource, ObjectDataSource and so on), or to any data source that implements the System.Collections.IEnumerable interface

• The FormView control can take advantage of the data source control's capabilities and provide automatic updating, deleting, inserting, and paging functionality.

• The FormView control recognizes certain buttons that have their CommandName properties set to specific values to generate command buttons to perform updating, deleting, or inserting operations

Include these command buttons in the appropriate template• The FormView control provides a paging feature, which allows the

user to navigate to other records in the data source.

Page 1483: Dotnet Stream

1483©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.

Style property Description

EditRowStyle The style settings for the data row when the FormView control is in edit mode.

EmptyDataRowStyle

The style settings for the empty data row displayed in the FormView control when the data source does not contain any records.

FooterStyle The style settings for the footer row of the FormView control.

HeaderStyle The style settings for the header row of the FormView control.

InsertRowStyle The style settings for the data row when the FormView control is in insert mode.

PagerStyle The style settings for the pager row displayed in the FormView control when the paging feature is enabled.

RowStyle The style settings for the data row when the FormView control is in read-only mode.

FormView Control User Interface

Page 1484: Dotnet Stream

1484©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.

Event Description

ItemCommand

Occurs when a button within a FormView control is clicked. This event is often used to perform a task when a button is clicked in the control.

ItemCreated Occurs after all FormViewRow objects are created in the FormView control. This event is often used to modify the values of a record before it is displayed.

ItemDeleted Occurs when a Delete button (a button with its CommandName property set to "Delete") is clicked, but after the FormView control deletes the record from the data source. This event is often used to check the results of the delete operation.

ItemDeleting

Occurs when a Delete button is clicked, but before the FormView control deletes the record from the data source. This event is often used to cancel the delete operation.

FormView Control- Events

Page 1485: Dotnet Stream

1485©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.

Event Description

ItemInserted Occurs when an Insert button (a button with its CommandName property set to "Insert") is clicked, but after the FormView control inserts the record. This event is often used to check the results of the insert operation.

ItemInserting

Occurs when an Insert button is clicked, but before the FormView control inserts the record. This event is often used to cancel the insert operation.

ItemUpdated

Occurs when an Update button (a button with its CommandName property set to "Update") is clicked, but after the FormView control updates the row. This event is often used to check the results of the update operation.

ItemUpdating

Occurs when an Update button is clicked, but before the FormView control updates the record. This event is often used to cancel the update operation.

FormView Control- Events

Page 1486: Dotnet Stream

1486©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.

Event Description

ModeChanged Occurs after the FormView control changes modes (to edit, insert, or read-only mode). This event is often used to perform a task when the FormView control changes modes.

ModeChanging Occurs before the FormView control changes modes (to edit, insert, or read-only mode). This event is often used to cancel a mode change.

PageIndexChanged

Occurs when one of the pager buttons is clicked, but after the FormView control handles the paging operation. This event is commonly used when you need to perform a task after the user navigates to a different record in the control.

PageIndexChanging

Occurs when one of the pager buttons is clicked, but before the FormView control handles the paging operation.

FormView Control- Events

Page 1487: Dotnet Stream

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

<asp:formview id="EmployeeFormView" datasourceid="EmployeeSource" allowpaging="true" datakeynames="EmployeeID" runat="server"> <itemtemplate> <asp:image id="EmployeeImage" imageurl='<%# Eval("PhotoPath") %>' alternatetext='<%# Eval("LastName") %>' runat="server"/> <h3><%# Eval("FirstName") %><%# Eval("LastName") %></h3> <%# Eval("Title") %> </itemtemplate> <pagersettings position="Bottom" mode="NextPrevious"/> </asp:formview>

FormView Control

Page 1488: Dotnet Stream

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

<asp:sqldatasource id="EmployeeSource" selectcommand="Select [EmployeeID], [LastName], [FirstName], [Title], [PhotoPath] From [Employees]" ConnectionString= "Provider=SQLOLEDB;Data Source=localhost;Password=sa;User ID=sa;Initial Catalog=Northwind“ runat="server"/>

FormView Control

Page 1489: Dotnet Stream

1489©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.

The Repeater control is a basic templated data-bound list. • It has no built-in layout or styles, so you must explicitly declare all

layout, formatting, and style tags within the control's templates.• The Repeater control is the only Web control that allows you to split

markup tags across the templates• The Repeater control has no built-in selection capabilities or editing

support

RepeaterRepeater

ASP.NET Repeater Control

Page 1490: Dotnet Stream

1490©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.

Repeater Control• A Repeater control binds its ItemTemplate and

AlternatingItemTemplate to either the data model declared and referenced by its DataSource property or the data source control specified by its DataSourceID property.

The HeaderTemplate, FooterTemplate, and SeparatorTemplate are not data-bound.

If the Repeater control's data source is set but no data is returned, the control renders the HeaderTemplate and FooterTemplate with no items.

If the data source is a null reference (Nothing in Visual Basic), the Repeater is not rendered.

At a minimum, every Repeater control must define an ItemTemplate

Page 1491: Dotnet Stream

1491©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.

Repeater Control

Page 1492: Dotnet Stream

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

<asp:repeater id="Repeater1" datasourceid="SqlDataSource1“ runat="server"> <headertemplate> <table border="1"> <tr> <td><b>Product ID</b></td> <td><b>Product Name</b></td> </tr> </headertemplate> <itemtemplate> <tr><td> <%# Eval("ProductID") %> </td><td> <%#

Eval("ProductName") %> </td></tr></itemtemplate> <footertemplate> </table> </footertemplate> </asp:repeater> <asp:sqldatasource id="SqlDataSource1" connectionstring="Provider=SQLOLEDB;Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind" selectcommand="SELECT ProductID, ProductName FROM [Products] Where ProductID <= 10“ runat="server" ProviderName="System.Data.OleDb"> </asp:sqldatasource>

Repeater Control

Page 1493: Dotnet Stream

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

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

Web Application Management Web Application Management

Page 1494: Dotnet Stream

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

ASP.NET Web Application Management

• State Management Client Side state Management Server Side state Management

• Caching Techniques OutputCaching FragmentCaching DataCaching PostCacheSubstitution

• Tracing and Logging• Exception Handing

ErrorPages CustomExceptions

Page 1495: Dotnet Stream

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

ASP.NET State Management

State Management State Management

Page 1496: Dotnet Stream

1496©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.

“The Web is inherently stateless; each request for a page is treated as a new request, and information from one request is not available by default to the next request”

“The Web is inherently stateless; each request for a page is treated as a new request, and information from one request is not available by default to the next request”

ASP.NET State Management

Page 1497: Dotnet Stream

1497©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.

State Management Server side vs. Client side

Page 1498: Dotnet Stream

1498©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.

State Management-Architecture

Page 1499: Dotnet Stream

1499©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.

View StateView State

Query StringQuery String

Hidden FieldHidden Field

Control StateControl State

CookiesCookies

Client SideState Management

ASP.NET Client Side State Management

Page 1500: Dotnet Stream

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

ASP.NET allows stores information in a HiddenField control, which renders as a standard HTML hidden field. • A hidden field does not render visibly in the browser, but its

properties can be set just as a standard control. • When a page is submitted to the server, the content of a hidden

field is sent in the HTTP form collection along with the values of other controls.

• A HiddenField control stores a single variable in its Value property and must be explicitly added to the page.

• In order for hidden-field values to be available during page processing, submit the page using an HTTP POST command

Hidden FieldsHidden Fields

ASP.NET Hidden Field

Page 1501: Dotnet Stream

1501©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.

The ViewState property provides a dictionary object for retaining values

between multiple requests for the same page. This is the default method that

the page uses to preserve page and control property values between round trips.

• When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field, or multiple hidden fields if the amount of data stored in the ViewState property exceeds the specified value in the MaxPageStateFieldLength property.

• When the page is posted back to the server, the page parses the view-state string at page initialization and restores property information in the page.

• Any objects put into the ViewState must be marked Serializable. ViewState serializes the objects with a special binary formatter called the LosFormatter. LOS stands for limited object serialization. It serializes any kind of object, but it is optimized to contain strings, arrays, and hashtables.

View stateView state

ASP.NET View State

Page 1502: Dotnet Stream

1502©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.

View State

<asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>

<asp:Button ID="Button1" Runat="server" Text="Button" />

<asp:HiddenField ID="HiddenField1" Runat="server" />

[Serializable]

public class Person

{

public string firstName;

public string lastName;

}

Page 1503: Dotnet Stream

1503©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.

View State

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if (!Page.IsPostBack)

{

HiddenField1.Value = "foo"; ViewState["AnotherHiddenValue"] = "bar";

Person p = new Person();

p.firstName = "Scott";

p.lastName = "Hanselman";

ViewState["HiddenPerson"] = p;

}

} }

Page 1504: Dotnet Stream

1504©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.

The ControlState property allows you to persist property

information that is specific to a control and cannot be turned

off like the ViewState property.

Control stateControl state

ASP.NET Control State

Page 1505: Dotnet Stream

1505©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.

A cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client browser session. • It contains site-specific information that the server sends to the

client along with page output. Cookies can be temporary (with specific expiration times and dates) or persistent.

• Cookies can store information about a particular client, session, or application.

• The cookies are saved on the client device, and when the browser requests a page, the client sends the information in the cookie along with the request information. The server can read the cookie and extract its value.

CookiesCookies

ASP.NET Cookies

Page 1506: Dotnet Stream

1506©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.

Limitations:

Despite being a useful tool in identifying users across web requests, cookies

also have certain limitations.

• Most browsers support cookies of up to 4096 bytes. Because of this small limit, cookies are best used to store small amounts of data, or better yet, an identifier such as a user ID. The user ID can then be used to identify the user and read user information from a database or other data store.

• Browsers also impose limitations on how many cookies your site can store on the user's computer. Most browsers allow only 20 cookies per site

• Some browsers also put an absolute limit, usually 300, on the number of cookies they will accept from all sites combined.

• A cookie limitation that users can set their browser to refuse cookies. If a P3P privacy policy is defined and placed in the root of the Web site, more browsers will accept cookies from the site.

ASP.NET Cookies-Limitations

Page 1507: Dotnet Stream

1507©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.

• The browser is responsible for managing cookies on a user system.

• Cookies are sent to the browser via the HttpResponse object that exposes a collection called Cookies .

• Cookies can be created by instantiating the HttpCookie class.Collection of cookies belong to the HttpCookieCollection class.

• When creating a cookie,specify a Name and Value.

• Each cookie must have a unique name so that it can be identified later when reading it from the browser.

• Since cookies are stored by name, naming two cookies the same will cause one to be overwritten.

• Also set a cookie's date and time expiration. Expired cookies are deleted by the browser when a user visits the site that wrote the cookies.

• If cookie's expiration is not set, the cookie is created but it is not stored on the user's hard disk. Instead, the cookie is maintained as part of the user's session information. When the user closes the browser, the cookie is discarded.

Cookies

Page 1508: Dotnet Stream

1508©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.

Writing Cookies:

In the above example 2 cookies are created namely userName and OurCookie.

Cookies can be created either of the 2 ways. For the first Cookie the values are added directly to the Collection. This is possible because Cookies derive from specialized collection of type NameObjectCollectionBase.

For the second cookie, the code creates an instance of an object of type HttpCookie, sets its properties, and then adds it to the Cookies collection via the Add method. When you instantiate an HttpCookie object, you must pass the cookie name as part of the constructor.

Writing Cookies

Response.Cookies["userName"].Value = “Peter"; Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1); HttpCookie aCookie = new HttpCookie(“OurCookie"); aCookie.Value = DateTime.Now.ToString(); aCookie.Expires = DateTime.Now.AddDays(10); Response.Cookies.Add(aCookie);

Response.Cookies["userName"].Value = “Peter"; Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1); HttpCookie aCookie = new HttpCookie(“OurCookie"); aCookie.Value = DateTime.Now.ToString(); aCookie.Expires = DateTime.Now.AddDays(10); Response.Cookies.Add(aCookie);

Page 1509: Dotnet Stream

1509©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.

More than one name-value pairs can be stored in a Cookie. Such name-value pairs in a single cookie are referred to as subkeys. Reasons.

• First, it is convenient to put related or similar information into a single cookie.

• In addition, because all the information is in a single cookie, cookie attributes such as expiration apply to all the information.

• A cookie with subkeys also helps you limit the size of cookie files on the client .

Cookies-Storing Multiple Values

Response.Cookies["userInfo"]["userName"] =“Peter"; Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString(); Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(10);HttpCookie aCookie = new HttpCookie("userInfo"); aCookie.Values["userName"] = “Peter"; aCookie.Values["lastVisit"] = DateTime.Now.ToString(); aCookie.Expires = DateTime.Now.AddDays(10); Response.Cookies.Add(aCookie);

Response.Cookies["userInfo"]["userName"] =“Peter"; Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString(); Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(10);HttpCookie aCookie = new HttpCookie("userInfo"); aCookie.Values["userName"] = “Peter"; aCookie.Values["lastVisit"] = DateTime.Now.ToString(); aCookie.Expires = DateTime.Now.AddDays(10); Response.Cookies.Add(aCookie);

Page 1510: Dotnet Stream

1510©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.

When a browser makes a request to the server, it sends the cookies for that server along with the request.

• In the ASP.NET applications,read the cookies using the HttpRequest object, which is available as the Request property of the Page class.

• Before trying to get the value of a cookie, make sure that the cookie exists; if the cookie does not exist, a NullReferenceException exception is thrown.

• HtmlEncode method was called to encode the contents of a cookie before

displaying it in the page

Reading Cookies

if(Request.Cookies["userName"] != null) Label1.Text=Server.HtmlEncode(Request.Cookies["userName“].Value;if(Request.Cookies["userName"] != null) { HttpCookie aCookie = Request.Cookies["userName"]; Label1.Text = Server.HtmlEncode(aCookie.Value); }

if(Request.Cookies["userName"] != null) Label1.Text=Server.HtmlEncode(Request.Cookies["userName“].Value;if(Request.Cookies["userName"] != null) { HttpCookie aCookie = Request.Cookies["userName"]; Label1.Text = Server.HtmlEncode(aCookie.Value); }

Page 1511: Dotnet Stream

1511©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.

• A query string is information that is appended to the end of a page URL .

• Query String is used to pass information from one web page to the another. The part after the “?” in the page URL is the query string. It contains the information to be transferred to another page in name-value pairs for processing.

• A typical query string might look like the following example: http://www.caritor.com/listwidgets.aspx?category=basic&price=100

• However, some browsers and client devices impose a 2083-character limit on the length of the URL.

• Information that is passed in a query string can be tampered with by a malicious user. Do not rely on query strings to convey important or sensitive data.

Query StringQuery String

ASP.NET Query String

Page 1512: Dotnet Stream

1512©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.

• Create a web form with a label and a TextBox. Change the label text to Enter name.

• Add another label and change the id to lblMessage.• Drag a button on the same form.• In the button click event type the following

Query String

if (TextBox1.Text.Equals("")) { lblMessage.Text = "Please enter your name"; } else { Response.Redirect("Default3.aspx?name=" +

HttpUtility.UrlEncode(TextBox1.Text)); }

if (TextBox1.Text.Equals("")) { lblMessage.Text = "Please enter your name"; } else { Response.Redirect("Default3.aspx?name=" +

HttpUtility.UrlEncode(TextBox1.Text)); }

Page 1513: Dotnet Stream

1513©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.

Client-Side

Option

Pros Cons

Cookie Simple Can be rejected by browser. Not appropriate for large amounts of data. Inappropriate for sensitive data.

Hidden Field

Simple for page-scoped data

Not appropriate for large amounts of data. Inappropriate for sensitive data.

ViewState

Simple for page-scoped data

Encoding of serialized object as binary Base64-encoded data adds approximately 30 percent overhead.

ControlState

Simple for page-scoped control-specific data

Like ViewState, but used for controls that require ViewState even if the developer has turned it off.

QueryString (URL)

Incredibly simple

Comparatively complex. Can’t hold a lot of information. Inappropriate for sensitive data. Easily modified by the end user.

ASP.NET Client Side State Management-Pros and Cons

Page 1514: Dotnet Stream

1514©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.

Session StateSession State

Profiler PropertiesProfiler Properties

Application StateApplication State Server SideState Management

ASP.NET Server Side State Management

Page 1515: Dotnet Stream

1515©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.

Application state is a data repository available to all classes in an ASP.NET application.• All web pages within a specific web application share the data

stored in the application state variables. • Unlike session state, which is specific to a single user session,

application state applies to all users and sessions. • Application state is a useful place to store small amounts of often-

used data that does not change from one user to another.

Application StateApplication State

ASP.NET Application State

Page 1516: Dotnet Stream

1516©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.

Application State-Considerations

Resources• Although storing data in Application state variables is faster as

compared to storing data in database, storing large amount of data in Application variables can fill up the server memory and cause the application to slow down.

• Unless necessay, Application variables should not be created as they are a memory overhead. Application variable created can be destroyed by the following ways.

Either the Web Application is closed or the server is shut down. Explicity by using the Application.Remove(),

Application.RemoveAll() or Application.RemoveAt() methods. By modifying the Global.asax file.

Page 1517: Dotnet Stream

1517©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.

Application State-Considerations

Volatility • Because application state is stored in server memory, it is lost whenever the

application is stopped or restarted.

• For example, if the Web.config file is changed, the application is restarted and all application state is lost unless application state values have been written to a non-volatile storage medium such as a database.

Scalability• Application state is not shared among multiple servers serving the same

application, Web farm, or among multiple worker processes serving the

same application on the same server, as in a Web garden.

Concurrency• Application state is free-threaded, which means that application state data

can be accessed simultaneously by many threads.

• To ensure that when to update application state data,do so in a thread-safe manner by including built-in synchronization support.

• Use the Lock and UnLock methods to ensure data integrity by locking the data for writing by only one source at a time.

Page 1518: Dotnet Stream

1518©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.

Application State-Creation• Application state is stored in an instance of the

HttpApplicationState class.

• Application variables can be created by prefixing the Application keywordbefore the variable name.

Application[“UserName”]=“Peter”;

• To read values from the Application variables in the page load event

protected void Page_Load(object sender, EventArgs e){ Application["AppStartTime"] = System.Convert.ToString(System.DateTime.Now); if (Application["AppStartTime"] != null) { Response.Write("Server start time is

+Application["AppStartTime"].ToString()); }

protected void Page_Load(object sender, EventArgs e){ Application["AppStartTime"] = System.Convert.ToString(System.DateTime.Now); if (Application["AppStartTime"] != null) { Response.Write("Server start time is

+Application["AppStartTime"].ToString()); }

Page 1519: Dotnet Stream

1519©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.

Application State-Concurrency• Since Application state variables are accessible to all the users

accessing the application, there has to be an explicit synchronization mechanism to restrict concurrent users from updating the application variable.

• In the load event of the Web form

if (!Page.IsPostBack) { Application.Lock(); if(Application["AppCounter"]==null) Application["AppCounter"] = 0; Application["AppCounter"] =(int)Application["AppCounter"] + 1; Response.Write("Value of Application Counter is "

+ Application["AppCounter"].ToString()); Application.UnLock(); }

if (!Page.IsPostBack) { Application.Lock(); if(Application["AppCounter"]==null) Application["AppCounter"] = 0; Application["AppCounter"] =(int)Application["AppCounter"] + 1; Response.Write("Value of Application Counter is "

+ Application["AppCounter"].ToString()); Application.UnLock(); }

Page 1520: Dotnet Stream

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

• ASP.NET session state identifies requests received from the same browser during a limited period of time as a session, and provides the ability to persist variable values for the duration of that session.

• Unlike the Application state, Session state is not specific to the Application but to the browser session.

• Each user opening a new browser session is allocated a SessionID which is stored in a 120 bit value stored in a cookie ASPNET_SessionID. In cookieless session it is transmitted via the URL.

• When the user closes the browser or logs out and re-returns access the same application he might get a different SessionID.

• The SessionID can be accessed by the SessionID property of Session object. Response.Write(Session.SessionID);

Session StateSession State

ASP.NET Session State

Page 1521: Dotnet Stream

1521©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.

Session State Considerations• Session variables can be created in a similar manner like

Application variables.

• Session variables can be used to transfer values across multiple pages of a Web application.

• The life of a session variable exists until The browser is closed thereby terminating the session. The value of session variable is set to 0 in Global.asax. Explicit method of the Session object is used such as

Session.Abandon() . The default time for a session i.e 20 minutes expires. This can

be modified in the web.config file.

Session State Considerations

Session[“SesCounter”] = 0;Session["FirstName"] = FirstNameTextBox.Text; Session["LastName"] = LastNameTextBox.Text;

Session[“SesCounter”] = 0;Session["FirstName"] = FirstNameTextBox.Text; Session["LastName"] = LastNameTextBox.Text;

Page 1522: Dotnet Stream

1522©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.

Session State Identifiers• Sessions are identified by a unique session identifier that can be

read using the SessionID property.• When session state is enabled for an ASP.NET application, each

request for a page in the application is examined for a SessionID value sent from the browser.

• If no SessionID value is supplied, ASP.NET starts a new session and the SessionID for that session is sent to the browser with the response.

• The SessionID is stored in a non-expiring session cookie in the browser by default.

• You can specify that session identifiers not be stored in a cookie by setting the cookieless attribute to true in the sessionState section of the Web.config file.

Session State Identifiers

Page 1523: Dotnet Stream

1523©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.

Session State Events and Modes• ASP.NET provides two events in the Global.asax file that help you

manage user sessions: the Session_OnStart event, which is raised when a new session begins, and the Session_OnEnd event, which is raised when a session is abandoned or expires.

• ASP.NET session state supports several different storage options for session data. Each option is identified by a value in the SessionStateMode enumeration. The following list describes the available session state modes in the web.config file:

InProc mode, which stores session state in memory on the Web server. This is the default.

StateServer mode, which stores session state in a separate process called the ASP.NET state service.

SQLServer mode stores session state in a SQL Server database. Custom mode, which enables you to specify a custom storage

provider Off mode, which disables session state.

Session State Events and Modes

Page 1524: Dotnet Stream

1524©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.

In the Application_StartApplication[“AppCtr]=0;

In the Session_Start typeSession[“SessCtr”]=0;

Session[“SessCtr”]=(int) Session[“SessCtr”]+1;

Application[“AppCtr”]=(int) Application[“AppCtr”]+1

In the Session_End typeSession[“SessCtr”]=(int) Session[“SessCtr”]-1;

Application[“AppCtr”]=(int) Application[“AppCtr”]-1

In the page load event typeResponse.Write(“The Application counter value is “+Application[“AppCtr”].toString();

Response.Write(“The Session counter value is “+Session[“SessCtr”].toString();

Session State

Page 1525: Dotnet Stream

1525©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.

Server-Side

Option

Pros Cons

Application State

Fast. Shared among all users.

State is stored once per server in multiple server configurations.

Cache Object (Application Scope)

Like the Application but includes expiration via Dependencies

State is stored once per server in multiple server configurations.

Session State

Three choices: in process, out of process, DB-backed. Can be configured as cookieless.

Can be abused.In process requires Web Server affinity. Cookieless configuration makes it easier to hijack.

Database State can be accessed by any server in a Web farm.

Pay a serialization and persistence cost when objects leave the process.

ASP.NET Server Side State Management-Pros and Cons

Page 1526: Dotnet Stream

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

Web Application Caching TechniquesWeb Application Caching Techniques

ASP.NET Caching Techniques

Page 1527: Dotnet Stream

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

ASP.NET Caching Techniques

“Caching is a technique widely used in computing to increase performance by keeping frequently accessed or expensive data in memory. In the context of a Web application, caching is used to retain pages or data across HTTP requests and reuse them without the expense of recreating them”

Page 1528: Dotnet Stream

1528©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.

Type Description

Output Caching Output caching is useful when the contents of an entire page can be cached

Fragment Caching

Identify objects or data that are expensive to construct and are eligible for caching. Fragment caching can be used to cache regions of a page's output.

Data Caching the cache items can be given an expiration policy that causes them to be removed from the cache when they have expired. Code that accesses the cache item simply checks for the absence of the item and recreates it, if necessary.

Cache Configuration

Cache profiles are used to configure cache profiles in the configuration system, and then use those profiles on pages. This enables changes to caching for sets of pages to be made on a global basis.

ASP.NET Caching Techniques

Page 1529: Dotnet Stream

1529©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.

Caching Techniques-Output Caching

Output CachingCaches the static result of an ASP.NET page

• Declarative <%@ OutputCache %> directive• Optional Output Cache APIs can also be called

Caching Options:• Duration -Time item exists in the cache• VaryByParam

Varies cache entries by Get/Post params Name param, separate by semi-colons, supports *

• VaryByHeader Varies cache entries by Http header

• VaryByCustom Override method within Global.asax to custom vary by whatever

you want (you control the cache key)

Page 1530: Dotnet Stream

1530©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.

Caching Techniques-Output Caching

Output Caching Location: This attribute is used to specify the location where the

data needs to be cached.This attribute can take one of the following values.

Client : It specifies the output cache to be located on the client browser that set the request.

Downstream: It specifies the output cache to be located on the server downstream to the server where the request is processed.

Server: It specifies the output cache to be located on the web server where the request is processed.

Any : It specifies the output cache to be located on the Client browser, the downstream server or the web server where the request is processed.

None : It specifies the output caching to be disabled for the current page

Page 1531: Dotnet Stream

1531©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.

Caching Techniques-Output Caching• Add a new Web form from the Project menu. Add a DataGrid to the

Web form.Add a label to the web form. Change its ID to DisplayLabel.

• Add the following in the HTML view of the web form:<%@ OutputCache Duration=“120” VaryByParam=“none”

%>• Import the System.Data.SqlClient namespace to the application.• Add the following in the load event of the web page.

String dsn ,sqlEmp;dsn=“server=localhost;uid=sa;pwd=sa;Database=pubs”;SqlConnection objConn=new SqlConnection(dsn);sqlEmp=“Select * from authors”;SqlDataAdapeter objadap=new SqlDataAdapter(sqlEmp,objConn);DataSet ds=new DataSet();Objadap.Fill(ds);DataGrid1.DataSource=ds;DataGrid1.DataBind();DisplayLabel.Text=“Page Cached at : “+System.DateTIme.Now.ToString();

String dsn ,sqlEmp;dsn=“server=localhost;uid=sa;pwd=sa;Database=pubs”;SqlConnection objConn=new SqlConnection(dsn);sqlEmp=“Select * from authors”;SqlDataAdapeter objadap=new SqlDataAdapter(sqlEmp,objConn);DataSet ds=new DataSet();Objadap.Fill(ds);DataGrid1.DataSource=ds;DataGrid1.DataBind();DisplayLabel.Text=“Page Cached at : “+System.DateTIme.Now.ToString();

Page 1532: Dotnet Stream

1532©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.

Caching Techniques-Fragment CachingFragment CachingThe main features of fragment caching are:

• In this type of caching,data for only specific sections of the page is cached.

• It can be implemented when you need to cache different portions of a single web form for different durations or when you need to cache only specific portions of the web form.

• Caching the entire page isn’t always possible Partial page personalization.

• Fragment Caching allows caching regions of a page by using user controls (.ascx)

User controls define <%@ OutputCache %> directive• Additional Features

VaryByControl – Varies cached items by controls VaryByCustom – Allows user cache key method

Page 1533: Dotnet Stream

1533©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.

Caching Techniques-Fragment Caching

To demonstrate the effect of fragment caching:

• A user controls needs to be created to display data from the authors table. The control should display the order details and time when the control was created.

• This user control needs to be displayed on a web page which does not implements Output Caching. The page should display the time when it was created.

To create a custom control , perform the following steps:• Select Project > Add Web User Control from the menu bar. The Add new

Item dialog box is displayed.

• Enter the name of the control as MyCustomControl.ascx.

• Switch to the design mode and drag the DataGrid control on the web form. Change the ID of DataGrid to AuthorGrid .

• Also drag a label and change its ID to DisplayLabel.

• In the HTML view of the user control, write the @OutputCache directive

<%@ OutputCache Duration=“180” VaryByParam=“none” %>

Page 1534: Dotnet Stream

1534©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.

Caching Techniques-Fragment Caching

Import the System.Data.SqlClient namespace and add the following code to the Page_Load event

string dsn, qrystr;

dsn=“server=localhost;user id=sa;pwd=sa;Initial Catalog=pubs”;

SqlConnection objSql=new SqlConnection(dsn);

qrystr=“Select * from authors”;

SqlDataAdapter sqladap=new SqlDataAdpater(qrystr,objSql);

DataSet dsAuthor=new DataSet();

Sqladap.Fill(dsAuthor);

AuthorGrid.DataSource=dsAuthor;

AuthorGrid.DataBind();

DisplayLabel.Text=“Control cached at ”+DateTime.Now.ToString();

Page 1535: Dotnet Stream

1535©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.

Caching Techniques-Fragment Caching

DisplayLabel.Text=“Page created at :”+DateTime.Now.ToString();

Since, we have used the OutputCache element to cache the data for the user control when the page is refreshed the time of creation of the control will be the same and will not be changed till 180 secs. However,with each page refresh, the label on the web page shows the changed timings since the page gets refreshed not from the cache.

Create a web form that will display the user control createdAdd the following Text in the DisplayLabel in the load event of the form

Create a web form that will display the user control createdAdd the following Text in the DisplayLabel in the load event of the form

Page 1536: Dotnet Stream

1536©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.

Caching Techniques-Data Caching

Data CachingThe main features of Data Caching are

• Frequently accessed data is cached in server-side memory variables.

• This type of caching is implemented programmatically.• The Cache class encapsulates data caching.• The Cache object stores each item as key/value pairs. E.g.

Cache[“unamekey”]=uname• The lifetime of the Cache object is associated with an application.• The cache object exists only while an application runs and the

Cache object is recreated when the application is restarted.

Page 1537: Dotnet Stream

1537©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.

Caching Techniques-Data Caching

Add a DataGrid to a web form.Import the System.Data.SqlClient namespace In the load event of the form write the code:

DataView AuthorSource;

AuthorSource=(DataView)Cache[“OrderSourceKey”];

if(AuthorSource==null)

{ string dsn=“server=localhost;uid=sa;pwd=sa;Database=pubs”;

SqlConnection objSConn=new SqlConnection(dsn);

string strcmd=“Select * from Authors”;

SqlDataAdapter objAda=new SqlDataAdapter(strcmd,objSConn);

DataSet dsauthor=new DataSet();

objAda.fill(dsauthor);

AuthorSource=new DataView(dsauthor.Tables[“Authors”]);

Cache[“OrderSourceKey”]=AuthorSource;

DisplayLabel.Text=“Data accessed from the database”;

}

Page 1538: Dotnet Stream

1538©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.

Caching Techniques-Data Caching

else

{

DisplayLabel.Text=“Data accessed from the cache”;

}

DataGrid1.DataSource=AuthorSource;

DataGrid1.DataBind();

In the given code, an object of DataView is created,which stores the cache OrderSourceKey.Next a check is done to see whether the cache object is null.If so,the records are retrieved from the authors table and are stored in the dataset dsauthor and its cache is stored in the variable AuthorSource.

Page 1539: Dotnet Stream

1539©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.

A substitution involves writing a callback method in the code-behind that returns HTML. • Use Response.WriteSubstitution() method, then, • In the form layout,the callback method is called for each request to

the page, even the rest of the page is being served from the output cache. The HTML returned from the method is embedded into the overall HTML for the page.<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Caching.aspx.cs" Inherits="Caching" %><%@ OutputCache Duration="5" VaryByParam="none" %><% Response.Write(DateTime.Now); %><% Response.WriteSubstitution(new HttpResponseSubstitutionCallback(WriteCurrentTime)); %>

Caching Techniques-Substitution Caching

Page 1540: Dotnet Stream

1540©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.

Caching Techniques-Substitution Caching

• Write a callback method called WriteCurrentTime. This method is added to your code-behind for the current page,

and must: return a string (i.e. the HTML)  Have one parameter of type HttpContext . Be static

protected static string WriteCurrentTime(HttpContext context){   return DateTime.Now.ToString();}

Page 1541: Dotnet Stream

1541©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.

Caching Techniques-Substitution Caching

• Alternatively to using WriteSubstitution in the page layout, you can use the Substitution control to declaratively perform the same thing:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Caching.aspx.cs" Inherits="Caching" %><%@ OutputCache Duration="5" VaryByParam="none" %>

<asp:Substitution MethodName="WriteCurrentTime" runat="server" />  

Page 1542: Dotnet Stream

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

Web Application TracingWeb Application Tracing

ASP.NET Tracing

Page 1543: Dotnet Stream

1543©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.

“Tracing is a way to monitor the execution of your ASP.NET application”

• It is often helpful to be able to insert debugging print statements into the

• code to output variables or structures, assert whether a condition is met, or

• just generally trace through the execution path of the application.

• ASP.NET provides two levels of tracing services Page-level Tracing Application-level Tracing

• There is a class called System.Diagnostics.Trace and there is also a public property on System.Web.UI.Page called Trace. The Trace property on the Page class gives access to the System.Web.TraceContext and the ASP.NET-specific tracing mechanism.

The TraceContext class collects all the details and timing of a Web request. It contains a number of methods,

Trace. Write() Trace.Warn(), which simply calls Write(), and also ensures that the output

generated by Warn is colored red.

ASP.NET Tracing

Page 1544: Dotnet Stream

1544©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.

Page-level Tracing: • At the page level, developers can use the TraceContext

intrinsic to write custom debugging statements that appear at the end of the client output delivered to the requesting browser.

• ASP.NET also inserts some helpful statements regarding the start/end of lifecycle methods, like Init, Render, and PreRender, in addition to the inputs and outputs to a page, such as form and QueryString variables or headers, and important statistics about the page's execution (control hierarchy, session state, and application state).

• ASP.NET tracing can be enabled on a page-by-page basis by adding Trace=”true” to the Page directive in any ASP.NET page:

<%@ Page Language="C#" Inherits="System.Web.UI.Page" Trace="true" %>

TraceMode attribute that sets SortByCategory or the default, SortByTime

Tracing-Page level

Page 1545: Dotnet Stream

1545©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.

Application-level Tracing: • Application-level tracing provides a view of several requests to an

application's pages at once.

• Application-level tracing is enabled through the ASP.NET configuration system, and accessed as a special mapped URL into that application (Trace.axd).

• When application tracing is enabled, page-level tracing is automatically enabled for all pages in that application (provided there is no page-level directive to explicitly disable trace).

Tracing-Application Level

Page 1546: Dotnet Stream

1546©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.

Application-level Tracing: • Enable tracing for the entire application by adding tracing settings

in web.config. In the following example, pageOutput=”false” and

requestLimit=”20” are used, so trace information is stored for 20 requests, but not displayed on the page:

<configuration>

<system.web>

<trace enabled="true" pageOutput="false" requestLimit="20" traceMode="SortByTime" localOnly="true" />

</system.web>

</configuration>• The page-level settings take precedence over settings in

web.config, so if enabled=”false” is set in web.config but trace=”true” is set on the page, tracing occurs.

Tracing-Application Level

Page 1547: Dotnet Stream

1547©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.

Tracing can be viewed for multiple page requests at the application level by requesting a special page (of sorts) called trace.axd.

• It is actually provided by System.Web.Handlers.TraceHandler, a special IHttpHandler to which trace.axd is bound.

• When ASP.NET detects an HTTP Request for trace.axd, that request is handled by the TraceHandler rather than by a page.

Tracing using Page.Trace <configuration>

<system.web>

<trace enabled="true" pageOutput="true" />

</system.web>

</configuration>

protected void Page_Load(object sender, EventArgs e)

{

Trace.Write("This message is from the START of the Page_Load method!");

}

Tracing-Using Trace.Write()

Page 1548: Dotnet Stream

1548©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.

Tracing

Page 1549: Dotnet Stream

1549©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.

Tracing

Page 1550: Dotnet Stream

1550©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.

Tracing

Page 1551: Dotnet Stream

1551©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.

Section Description

Request Details

Includes the ASP.NET Session ID, the character encoding of the request and response, and the HTTP conversation’s returned status code.

Trace Information

Includes all the Trace.Write methods called during the life-time of the HTTP request and a great deal of information about timing. This is probably the most useful section for debugging. The timing information located here is valuable when profiling and searching for methods in your application that take too long to execute.

Control Tree

Presents an HTML representation of the ASP.NET Control Tree. Shows each control’s unique ID, runtime type, the number of bytes it took to be rendered, and the bytes it requires in View-State and ControlState.The weight of the control indicates the number of bytes occupied in ViewState and/or ControlState by that particular Control.

Trace Sections and Description

Page 1552: Dotnet Stream

1552©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.

Section Description

Session State

Lists all the keys for a particular user’s session, their types, and their values. Shows only the current user’s Session State.

Application State

Lists all the keys in the current application’s Application object and their types and values.

Request Cookies

Lists all the cookies passed in during the page’s request.

Response Cookies

Lists all the cookies that were passed back during the page’s response.

Headers Collection

Shows all the headers that might be passed in during the request from the browser, including Accept-Encoding, indicating whether the browser supports compressed HTTP responses; Accept-Languages, a list of ISO language codes that indicate the order of the user’s language preferences; and User-Agent, the identifying string for the user’s browser.

Trace Sections and Description

Page 1553: Dotnet Stream

1553©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.

Section Description

Form Collection

Displays a complete dump of the Form collection and all its keys and values.

Querystring Collection

Displays a dump of the Querystring collection and all its contained keys and values.

Server Variables

A complete dump of name-value pairs of everything that the Web server knows about the application and the requesting browser.

Trace Sections and Description

Page 1554: Dotnet Stream

1554©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.

Trace Sections and Description

Page 1555: Dotnet Stream

1555©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.

Attribute Options Description

Enabled true/false Specifies whether the tracing service is enabled or disabled. The default setting in machine.config is false.

localOnly true/false Specifies whether you can view trace resultsonly from local host or remotely. The defaultis true.

pageOutput

true/false Specifies whether trace results are appendedto the end of a page or available only throughthe trace utility. The default is false.

requestLimit

Places a limit on the number of trace requests to store on the server. The default is 10.

traceMode

SortByTime/ SortByCatego

ry

Specifies whether to sort the trace results by Time or Category. The default is SortByTime.

Trace Attributes and Options

Page 1556: Dotnet Stream

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

Web Application LoggingWeb Application Logging

ASP.NET Logging

Page 1557: Dotnet Stream

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

ASP.NET Logging• ASP.NET writes messages to the event log in certain

conditions in which ASP.NET infrastructure encounters a fatal failure, such as when it does not have access to required resources, or is unable to create worker processes to host ASP.NET applications.

• The information in these events may be used to solve such problems, especially when first deploying ASP.NET applications to new machines where permission and installation issues may exist.

Page 1558: Dotnet Stream

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

Web Application DebuggingWeb Application Debugging

ASP.NET Debugging Techniques

Page 1559: Dotnet Stream

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

ASP.NET Debugging Techniques

Design Time Support• Syntax Notification• Immediate and Command Window• Task List

Exception Handing• ErrorPages• CustomExceptions

Page 1560: Dotnet Stream

1560©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.

VS2005 Design Time Support for Debugging

• Syntax Notification C# editors show squiggles and tooltips for many syntax errors

well before compilation XML Editor with enhancements like the following:

Full XML 1.0 syntax checking Support for DTD as well as XSD validation Support for XSLT 1.0 syntax checking

• Immediate Window The Immediate Window enables to run arbitrary bits of code in

Design mode without compiling the application. It can be a great way to test a line of code or a static method quickly.

Access the Immediate Window from Debug Windows Immediate. To evaluate a variable or run a method, simply click in the Immediate Window and type a question mark (?) followed by the expression, variable, or method you want to evaluate

Page 1561: Dotnet Stream

1561©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.

VS2005 Design Time Support for Debugging

• Command Window The immediate window can also be switched into the Command

Window by prefacing commands with a greater-than sign (>). When a greater-than sign in the Immediate/Command Window is entered, an IntelliSense drop-down appears exposing the complete Visual Studio object model as well as any macros that have been recorded.

• Task List User Tasks view enables to add and modify tasks, which can

include anything from “Remember to Test” to “Buy Milk.” These tasks are stored in the .SUO (solution user options) that is a parallel partner to the .SLN files.

The Comments view shows text from the comments in the code where those lines are prefixed with a specific token. Visual Studio comes configured to look for the TODO: token, but we can add our own in Tools Options Environment Task List.

Page 1562: Dotnet Stream

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

ASP.NET Error Pages

When an error occurs on a page, ASP.NET sends information about the

error to the client. Errors are divided into four categories: • Configuration errors: Occur when the syntax or structure of a

Web.config file in the configuration hierarchy is incorrect. • Parser errors: Occur when the ASP.NET syntax on a page is

malformed. • Compilation errors: Occur when statements in a page's target

language are incorrrect. • Run-time errors: Occur during a page's execution, even though the

errors could not be detected at compile time.

Page 1563: Dotnet Stream

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

ASP.NET Error Pages• By default, errors are shown only to local clients (those clients on

the same computer as the server). To specify a custom error page to redirect clients to if an error occurs.

• Custom errors are enabled in the Web.config file for an application. For example:

<configuration> <system.web> <customErrors defaultRedirect="genericerror.htm"

mode="RemoteOnly" /> </system.web> </configuration>

• Only files mapped to the aspnet_isapi.dll extension in IIS generate these errors. Files not served through the aspnet_isapi.dll are not processed by ASP.NET and generate IIS errors

Page 1564: Dotnet Stream

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

ASP.NET Error Pages• Configuration attributes and values for the <customErrors> tag.

mode Indicates whether custom errors are enabled, disabled, or only shown to remote computers. Values: On, Off, RemoteOnly (default).

defaultRedirect Indicates the default URL to which a browser should be redirected if an error occurs. This attribute is optional.

• The Mode attribute determines whether errors are shown to local clients, remote clients, or both. The effects of each setting are described in the following table.

Mode Local host request Remote host request

On Custom error page. Custom error page.

Off ASP.NET error page. ASP.NET error page.

RemoteOnly ASP.NET error page. Custom error page.

Page 1565: Dotnet Stream

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

ASP.NET Error Pages• The <customErrors> configuration section supports an inner

<error> tag that associates HTTP status codes with custom error pages

<configuration>

<system.web>

<customErrors mode="RemoteOnly" defaultRedirect="/genericerror.htm">

<error statusCode="500" redirect="/error/callsupport.htm"/>

<error statusCode="404" redirect="/error/notfound.aspx"/>

<error statusCode="403" redirect="/error/noaccess.aspx"/>

</customErrors>

</system.web>

</configuration>

StatusCode HTTP status code of errors for which the custom error page should be used. Examples: 403 Forbidden, 404 Not Found, or 500 Internal Server Error.

Redirect URL to which the client browser should be redirected if an error occurs.

Page 1566: Dotnet Stream

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

ASP.NET Error Pages

public void Error_500(Object sender, EventArgs e)

{ String foo = null; Response.Write(foo.ToString());

}

public void Page_Error(Object sender, EventArgs e)

{ String message = "<font face=verdana color=red>" +

"<h4>" + Request.Url.ToString() +

"</h4>" + "<pre><font color='red'>" +

Server.GetLastError().ToString() + "</pre>" + "</font>";

Response.Write(message); Server.ClearError(); }

Handling Errors at Page LevelHandling Errors at Page Level

<asp:button text="500 Server Error" OnClick="Error_500" width="150" runat="server"/> <asp:button text="500 Server Error" OnClick="Error_500" width="150" runat="server"/>

Page 1567: Dotnet Stream

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

ASP.NET Error Pages

Use the Application_Error event in Global.asax void Application_Error(Object sender, EventArgs e)

{

//...Do something here

}

Handling Errors at Application LevelHandling Errors at Application Level

Page 1568: Dotnet Stream

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

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

Web site Management Web site Management

Page 1569: Dotnet Stream

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

ASP.NET Web site Management• Web site Configuration

Web Administration Tool

• Security Authentication

Windows Forms Digest

Authorization Allow/Roles/Verbs

• Health Monitoring• Deployment

Page 1570: Dotnet Stream

1570©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.

Configuration Management Configuration Management

ASP.NET Configuration

Page 1571: Dotnet Stream

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

ASP.NET Configuration Tools & Files

ASP.NET 2.0 provides tools and APIs that enable developers to

configure and manage ASP.NET 2.0–based applications with reliability

and comfort.Two powerful configuration tools are explored:

• The new ASP.NET Web Site Administration Tool, a Web-based application

• The new MMC ASP.NET Snap-In, a plug-in configuration tab for IIS.

Two configuration files are explored• Machine.config• Web.config

Page 1572: Dotnet Stream

1572©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.

The ASP.NET Web Site Administration Tool helps to manage Web site

configuration through a simple, easy-to-use Web interface. • It eliminates the need for manually editing the web.config file. • If no web.config file exists when using the administration tool for

the first time, it creates one. • The ASP.NET Web Site Administration Tool also creates the

standard ASPNETDB.MDF SQL Server Express Edition file in the App_Data folder of the Web site to store application data.

• The changes made to most settings in the ASP.NET Web Site Administration Tool take effect immediately.

• The default settings are automatically inherited from any configuration files that exist in the root folder of a Web server.

ASP.NET Configuration Tool-Web Administration Tool

Page 1573: Dotnet Stream

1573©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.

• The ASP.NET Web Site Administration Tool is automatically installed during installation of the .NET Framework version 2.0.

• To use the administration tool to administer your own Web site, you must be logged in as a registered user of the site and must have read and write permissions to web.config.

• Access WAT with Visual Studio 2005, which, in turn, uses the new built-in server (formally Cassini) to access the administration tool.

• In order to access this tool through Visual Studio 2005, click the ASP.NET Configuration button found in the menu provided in the Solution Explorer.

(or)http://localhost/MyShop/Webadmin.axd

Web Administration Tool

Page 1574: Dotnet Stream

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

Web Administration Tool

Page 1575: Dotnet Stream

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

Web Administration Tool

Page 1576: Dotnet Stream

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

Web Administration Tool-Security Tab

Page 1577: Dotnet Stream

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

Web Administration Tool-Security Tab

Page 1578: Dotnet Stream

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

Web Administration Tool-Security Tab

Page 1579: Dotnet Stream

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

Web Administration Tool-Security Tab

Page 1580: Dotnet Stream

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

Web Administration Tool-Security Tab

Page 1581: Dotnet Stream

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

Web Administration Tool-Application Tab

Page 1582: Dotnet Stream

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

Web Administration Tool-Application Tab

Page 1583: Dotnet Stream

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

Web Administration Tool-Provider Tab

Page 1584: Dotnet Stream

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

Web Administration Tool-Provider Tab

Page 1585: Dotnet Stream

1585©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.

machine.config :

• This is an XML based file is automatically installed with Visual

Studio.NET. The machine.config file is installed on the server in the

location

%windir%\ Microsoft.NET \ Framework \ v2.0\CONFIG

• The machine.config file is located at the highest level in the

configuration hierarchy

• Machine.config contains the default configuration settings for all

the applications hosted on the web server.

• This file is called the machine level configuration file.

ASP.NET Configuration File-Machine.config

Page 1586: Dotnet Stream

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

ASP.NET Configuration File-Web.config

web.config

• This file is created in the Application’s root directory and contain

settings specific to a particular web application.

• This file contain settings specific to an application and therefore

called Application Level configuration file.

• On a single web server there exists as many as web.config files as

the No. of web applications hosted on it.

• The settings applied in the web.config file overrides the same

settings applied in the higher –level machine.config file

Page 1587: Dotnet Stream

1587©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.

Configuration Tag

Description

<appSettings> Allows the configuration of Application custom settings for your applications

<authentication>

Allows configuration of ASP.NET’s Securityauthentication support.

<authorization>

Allows configuration of ASP.NET’s Securityauthorization support.

<browserCaps> Allows configuration of settings for the browser capabilities component.

<compilation> allows configuration of all ASP.NET compilation settings.

<sessionState> Allows configuration of the Systemsession state HTTP module

<trace> Allows configuration of the ASP.NET Applicationtrace service.

ASP.NET Configuration File Tags

Page 1588: Dotnet Stream

1588©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.

Configuration Tag

Description

<customErrors> Allows the definition of custom Errors for a web application.

<compilation> Allows configuration of all ASP.NET compilation settings.

<globalization> Allows the configuration of globalization Settings for an application.

<pages> Allows configuration of page specific settings.

<securityPolicy>

Allows the mapping of defined security to policy files.

<trust> Allows configuration of the code Securityaccess security permission set used to run your application.

<webServices> Allows configuration of ASP.NET SystemWeb Services settings.

<httpRuntime> Allows the configuration of HttpRuntime Settings.

ASP.NET Configuration File Tags

Page 1589: Dotnet Stream

1589©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.

Configuration Tag

Description

<forms> Specifies things such as the loginUrl, the type of protection and the timeout of inactivity.

<credentials>

specifies the username/password combinations .The credentials tag also has an attribute called passwordFormat. Password format are: Clear|SHA1|MD5

<user> Contains name attribute for the username and password attribute for the password..

<location> The location tag has one attribute, path, which is the path to apply a different set of security rules to

ASP.NET Configuration File Tags

Page 1590: Dotnet Stream

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

Web site SecurityWeb site Security

ASP.NET Security

Page 1591: Dotnet Stream

1591©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.

An important aspect of security is how to handle the authentication and authorization for accessing application

An important aspect of security is how to handle the authentication and authorization for accessing application

ASP.NET Security

Page 1592: Dotnet Stream

1592©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.

IISIIS(inetinfo.exe)(inetinfo.exe)

ASP.NETASP.NET(aspnet_wp.exe)(aspnet_wp.exe)

AuthenticationAuthenticationBasicBasicDigestDigest

IntegratedIntegratedCertificateCertificate

AuthorizationAuthorizationWeb PermissionsWeb Permissions

NTFS PermissionsNTFS PermissionsIP RestrictionsIP Restrictions

AuthenticationAuthenticationWindowsWindows

FormsFormsPassportPassport

NoneNone

AuthorizationAuthorizationFile AuthZFile AuthZURL AuthZURL AuthZ.NET Roles.NET RolesHT

TP R

eque

sts

HTTP

Req

uest

s

Local orLocal orRemoteRemote

ResourceResource

7777

4444

66665555

1111

AuthorizationWeb Permissions

NTFS PermissionsIP Restrictions

AuthenticationBasicDigest

IntegratedCertificate

33332222

ASP.NET Security

Page 1593: Dotnet Stream

1593©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.

Authentication is the process that determines the identity of the user.

• The different authentication modes are established through settings that can be applied to the applications web.config file or in conjunction with the application server’s Internet Information Services (IIS) instance.

• The different authentication modes are as follows

Provider Description

Windows Used together with IIS authenticationPerformed by IIS as: Basic,Digest or Integrated Windows.(Default)

Forms Requested that are authenticated are redirected to an HTML form using HTTP client-side redirection

Passport A centralized authentication service provided by Microsoft that offers single login and core profile services for member sites

ASP.NET Security-Authentication

Page 1594: Dotnet Stream

1594©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.

The Windows-Based Authentication is handled between the windows server where the ASP.NET application resides and the client machine.

• In this model,the request go directly to IIS to provide the authentication process.

• Useful in Intranet environments where users are already logged onto a network.IIS takes the user’s credentials from the domain logic.

Security-Windows Authentication

Page 1595: Dotnet Stream

1595©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.

Creating Users and Groups:

Steps to create a user:

1. From Windows Server 2003/XP Choose Control Panel->Administrative tool->Computer Management(Manages and controls resources on the local web server)

2. Expand System Tools node

3. Expand Local users and Groups node

4. Select Users folder

5. Right click and select New Users

6. Give username, password and description.Uncheck “User must change password at the next login”

7. Click Create button

Steps to create a group

1. Right click the Groups folder under “System Tools” to select New Group and add Users.

Security-Windows Authentication

Page 1596: Dotnet Stream

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

ASP.NET is used to control client access to URL resources. It is configurable for the HTTP method used to make the request (GET or POST) and can be configured to allow or deny access to groups of users or roles.

• Permissible elements for authorization directives are either allow or deny.

• Each allow or deny element must contain a users or a roles attribute.

• Multiple users or roles can be specified in a single element by providing a comma-separated list

• The HTTP method can be indicated using the Verb attribute:

<authorization> <allow users="[email protected]" /> <allow roles="Admins" /> <deny users="*" /> </authorization>

<authorization> <allow users="[email protected]" /> <allow roles="Admins" /> <deny users="*" /> </authorization>

<allow users="John,Mary" /> <allow users="John,Mary" />

<allow VERB="POST" users="John,Mary" /> <deny VERB="POST" users="*" /> <allow VERB="GET" users="*" />

<allow VERB="POST" users="John,Mary" /> <deny VERB="POST" users="*" /> <allow VERB="GET" users="*" />

Security-Windows Authentication

Page 1597: Dotnet Stream

1597©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.

Security-Windows AuthenticationIntegrated Windows Authentication

• This was previously known as NTLM or windows NT Challenge/Response Authentication.

• This model has the client prove its identity by sending a has of its credentials to the server that is hosting the ASP.NET application.

Basic Authentication• This model requires a username and password form the client for

authentication.• The drawback is that it passes the username and password to the

server as• clear text.To implement,

Open IIS-the properties dialog for the Web site Select the Directory “Security Tab” and click Edit button in the

Anonymous Access and Authentication Control Box Uncheck the “Integrated Windows Authentication” check box at

the bottom and check the “Basic Authentication” checkbox

Page 1598: Dotnet Stream

1598©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.

Security-Windows AuthenticationDigest Authentication

• This model uses an algorithm to encrypt the clients credentials before they are sent to the application server. To use this model, it is necessary to have Windows domain controller and browsers must confirm to HTTP1.1 specification

Page 1599: Dotnet Stream

1599©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.

The Forms-Based Authentication is used to authenticate users to access an entire application or resources within an application.

ASP.NET Security-Form Based Authentication

Page 1600: Dotnet Stream

1600©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.

<authentication mode="Forms">

<forms name=".ASPXCOOKIEDEMO" loginUrl="login.aspx"

defaultUrl="default.aspx"

protection="All"

timeout="30"

path="/"

requireSSL="false"

slidingExpiration="true"

enableCrossAppRedirects="false"

cookieless="UseDeviceProfile"

domain="">

<!-- protection="[All|None|Encryption|Validation]" -->

<!-- cookieless="[UseUri | UseCookies | AutoDetect | UseDeviceProfile]" -->

</forms>

</authentication>

Security-Form Based Authentication

Page 1601: Dotnet Stream

1601©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.

Attribute Description

name Cookie name saved to remember the user from request to request

loginUrl Specifies the URL to which the request is redirected for login

protection Specifies the amount of protection to be applied for the authentication cookieAll-application uses both validation and encryptionEncryption-cookie is encrypted but no data validationValidation-Validation of cookie but no encryptionNone-no encryption to the cookie

path Path for cookies issued by the application

timeout Specifies amount of time in minutes after which the cookie expires

Security-Form Based Authentication

Page 1602: Dotnet Stream

1602©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.

Attribute Description

cookieless Specifies whether form-based authentication process should use cookies

defaultURL Specifies the default URL

domain Specifies the domain name to be sent with forms authentication cookies

slidingExpiration The expiration of the cookie is reset with each request made to the server if this value is true. Default is false

enableCrossAppsRedirect

Specifies whether to allow for cross-application redirection

requireSSL Specifies whether a Secure Sockets Layer connection is requires when transmitting authentication information

Security-Form Based Authentication

Page 1603: Dotnet Stream

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

<html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <div> <asp:TextBox ID="username" runat="server"></asp:TextBox> <asp:TextBox ID="password" runat="server"></asp:TextBox> <asp:Button ID="loginButton" runat="server" OnClick="loginButton_Click" Text="Button" /> </form></body></html>

Security-Form Based Authentication

Page 1604: Dotnet Stream

1604©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.

protected void loginButton_Click(object sender, EventArgs e){if (FormsAuthentication.Authenticate(username.Text, password.Text)){ FormsAuthentication.RedirectFromLoginPage(username.Text, true); Response.Redirect(“Home.aspx");} else{ Response.Write("Invalid Login"); } }

<authentication mode="Forms" > <forms name="First" loginUrl="First" path="/"> <credentials passwordFormat="Clear"> <user name="anny" password="praveen"/> </credentials> </forms> </authentication>

passwordFormat: Clear: Passwords are stored MD5:Passwords are stored using a Message Digest5 hash digestSHA1:Passwords are stored using a SHA1 hash digest

passwordFormat: Clear: Passwords are stored MD5:Passwords are stored using a Message Digest5 hash digestSHA1:Passwords are stored using a SHA1 hash digest

Authenticating against values contained in the web.config file

Security-Form Based Authentication

Page 1605: Dotnet Stream

1605©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.

Authenticating against values in a Database

private void login_Click(object sender, System.EventArgs e){

String sqlStmt = "Select username from Users where username='" + username.Text + "' and password='" + password.Text + "'";SqlConnection sqlConn = new SqlConnection("Data source=localhost;User ID=sa;Initial Catalog=myshop;");SqlCommand sqlCmd = new SqlCommand(sqlStmt, sqlConn);sqlCmd.Connection.Open();SqlDataReader sqlReader = sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);if (sqlReader.Read()){FormsAuthentication.RedirectFromLoginPage(username.Text, true);Response.Redirect(“Home.aspx");}elseResponse.Write("Invalid Login");

}

Security-Form Based Authentication

Page 1606: Dotnet Stream

1606©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.

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) { if (Login1.UserName == "anny" && Login1.Password == "praveen") { Response.Redirect("Sample.aspx"); FormsAuthentication.RedirectFromLoginPage(Login1.UserName,

Login1.RememberMeSet); } else { Response.Write("Invalid user"); } }

Authenticating using Login Control

Security-Form Based Authentication

Page 1607: Dotnet Stream

1607©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.

<configuration><location> <system.web>

<authentication mode="None"></authentication>

</system.web> <location path="Default.aspx">

<system.web> <authentication mode="Windows">

</authentication> <authorization>

<deny users="*"/> </authorization> </system.web>

</location></configuration>

Authenticating specific files and folders

Security-Form Based Authentication

Page 1608: Dotnet Stream

1608©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.

Page objects “User” property provides the following property and method

Identity: :This property provides an instance of

System.Security.Principal.IIdentitty Object to get specific

properties of the authenticated user.

IsInRole: This method takes a single parameter ,a system

representation of system role

User.Identity provides the following properties

AuthenticationType :Provides authentication type of the current

user(Basic/Forms/..)

IsAuthenticated :Returns a boolean value specifying whether the user has

been authenticated

Name :Provides the username of the user as well as the domain of

the user

ASP.NET Security-Authorization

Page 1609: Dotnet Stream

1609©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.

To work with roles & Authentication, System.Security.Principal provides

1.WindowsBuiltInRole enumeration

Values: :AccountOperator, Administrator, BackupOperator, Guest, PowerUser, PrintOperator,

Replicator, SystemOperator,User

2.WindowsIdentity object

Properties:ImpersonationLevel, IsAnonymous, IsAuthenticated, IsGuest, IsSytem, Name

IsInRole()IsInRole()IdentityIdentityIsInRole()IsInRole()IdentityIdentity

NameNameIsAuthenticatedIsAuthenticatedAuthenticationTypeAuthenticationType

NameNameIsAuthenticatedIsAuthenticatedAuthenticationTypeAuthenticationType

IIdentityIIdentity

IPrincipalIPrincipal

Security-Authorization

Page 1610: Dotnet Stream

1610©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.

protected void Page_Load(object sender, EventArgs e) { Response.Write(User.Identity.AuthenticationType.ToString()); if (User.Identity.IsAuthenticated) { Response.Write("Name of user" + User.Identity.Name.ToString()+"<br>"); Response.Write("Authentication Type" + User.Identity.AuthenticationType.ToString()+"<br>"); WindowsIdentity AuthUser = WindowsIdentity.GetCurrent(); Response.Write(AuthUser.AuthenticationType.ToString()+"<br>"+ AuthUser.ImpersonationLevel.ToString()+"<br>"+ AuthUser.IsAnonymous.ToString() + "<br>" + AuthUser.IsAuthenticated.ToString() + "<br>" + AuthUser.IsGuest.ToString() + "<br>" + //Guest Account AuthUser.IsSystem.ToString() + "<br>" + //System Account AuthUser.Name.ToString()); } }

Security-Authorization

Page 1611: Dotnet Stream

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

Web site DeploymentWeb site Deployment

ASP.NET Deployment

Page 1612: Dotnet Stream

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

ASP.NET contains a lot of pieces that are all possible parts of the overall application and need to be deployed with the application in order for it to run properly • .aspx pages• The code-behind pages for the .aspx pages (.aspx.vb or .aspx.cs

files)• User controls (.ascx)• Web service files (.asmx and .wsdl files)• .htm or .html files• Image files such as .jpg or .gif • ASP.NET system folders such as App_Code and App_Themes • JavaScript files (.js)• Cascading Style Sheets (.css)• Configuration files such as the web.config file• .NET components and compiled assemblies• Data files such as .mdb files

ASP.NET Deployment

Page 1613: Dotnet Stream

1613©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.

Steps to Take before Deploying • The first step you should take is to turn off debugging in the

web.config file <configuration

xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">

• The second step is to build the application in Release mode. This can be accomplished by changing the Active Solution Configuration from Debug to Release through the drop-down list in the Visual Studio menu

<system.web> <compilation debug="false" /> </system.web> </configuration>

ASP.NET Deployment

Page 1614: Dotnet Stream

1614©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.

Methods of Deploying Web Applications • Use the XCopy capability that simply wows audiences when

demonstrated (because of its simplicity).

• Use Visual Studio 2005’s capability to copy a Web site from one location to another using the Copy Web Site feature, as well as an alternative method that uses Visual Studio to deploy a precompiled Web application.

• Use Visual Studio to build an installer program that can be launched on another machine

ASP.NET Deployment Methods

Page 1615: Dotnet Stream

1615©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.

XCopy Option• Applications in .NET compile down to assemblies, and

these assemblies contain code that is executed by the Common Language Runtime (CLR). The great thing about assemblies is that they are self-describing. All the details about the assembly are stored within the assembly itself.

XCOPY is the command-line way of basically doing a copy-and-paste of the files needed to move.

XCOPY helps to move files, directories, and even entire drives from one point to another.

ASP.NET Deployment-XCopy

Page 1616: Dotnet Stream

1616©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.

• The default syntax of the XCOPY command is as follows:

• When using XCOPY, this method does not allow for the automatic creation of any virtual directories in IIS.

xcopy [source] [destination] [/w] [/p] [/c] [/v] [/q]

[/f] [/l] [/g] [/d[:mm-dd-yyyy]] [/u] [/i] [/s [/e]] [/t]

[/k] [/r] [/h] [{/a|/m}] [/n] [/o] [/x] [/exclude:file1[+

[file2]][+file3]] [{/y|/-y}] [/z]

xcopy [source] [destination] [/w] [/p] [/c] [/v] [/q]

[/f] [/l] [/g] [/d[:mm-dd-yyyy]] [/u] [/i] [/s [/e]] [/t]

[/k] [/r] [/h] [{/a|/m}] [/n] [/o] [/x] [/exclude:file1[+

[file2]][+file3]] [{/y|/-y}] [/z]

ASP.NET Deployment-XCopy

Page 1617: Dotnet Stream

1617©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.

Parameter

Description

/w Displays the message: Press any key to begin copying file(s). It waits for your response to start the copying process.

/p Asks for a confirmation on each file being copied. This is done in a file-by-file manner.

/c Ignores errors that might occur in the copying process.

/v Performs a verification on the files being copied to make sure they are identical to the source files.

/q Suppresses any display of the XCOPY messages.

/f Displays the file names for the source and destination files while the copying process is occurring.

/l Displays a list of the files to be copied to the destination drive.

/g Builds decrypted files for the destination drive.

/d When used as simply /d, the only files copied are those newer than the existing files located in the destination location.

ASP.NET Deployment-XCopy Parameters

Page 1618: Dotnet Stream

1618©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.

Parameter Description

/u Copies only source files that already exist in the destination location.

/i If what is being copied is a directory or a file that contains wildcards and the same item does not exist in the destination location, a new directory is created. The XCOPY process also copies all the associated files into this directory.

/s Copies all directories and their subdirectories only if they contain files. All empty directories or subdirectories are not copied in the process.

/e Copies all subdirectories regardless of whether these directories contain files.

/t Copies the subdirectories only and not the files they might contain.

/k By default, the XCOPY process removes any read-only settings that might be contained in the source files.

/r Copies only the read-only files to the destination location.

/h Specifies that the hidden and system files, which are usually excluded by default, are included.

ASP.NET Deployment-XCopy Parameters

Page 1619: Dotnet Stream

1619©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.

Parameter Description

/exclude Allows you to exclude specific files. The construction used for this is exclude:File1.aspx+File2.aspx+File3.aspx.

/y Suppresses any prompts from the XCOPY process that ask whether to overwrite the destination file.

/-y Adds prompts in order to confirm an overwrite of any existing files in the destination location.

/z Copies files and directories over a network in restartable mode.

/? Displays help for the XCOPY command.

ASP.NET Deployment-XCopy Parameters

Page 1620: Dotnet Stream

1620©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.

Parameter Description

/a Copies only files that have their archive file attributes set, and leaves the archive file attributes in place at the XCOPY destination.

/m Copies only files that have their archive file attributes set, and turns off the archive file attributes.

/n Copies using the NTFS short file and short directory names.

/o Copies the discretionary access control list (DACL) in addition to the files.

/x Copies the audit settings and the system access control list (SACL) in addition to the files.

ASP.NET Deployment-XCopy Parameters

Page 1621: Dotnet Stream

1621©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.

VS Copy Web Site Option• This GUI enables you to copy Web sites from your

development server to either the same server or a remote server (as you can when you use the XCOPY command).

Pull up this Copy Web Site dialog in Visual Studio in two ways. Click in the Copy Web Site icon in the Visual Studio Server

Explorer. Open the Copy Web Site GUI is to choose Website Copy Web

Site from the Visual Studio menu.

ASP.NET Deployment-Copy Web Site

Page 1622: Dotnet Stream

1622©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.

VS Copy Web Site OptionClick the Connect To a Remote Server button

ASP.NET Deployment-Copy Web Site

Page 1623: Dotnet Stream

1623©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.

• File System: Allows navigating through a file explorer view of the computer. To install on a remote server from this view, a drive must be mapped to the installation location.

• Local IIS: This option enables to use local IIS in the installation of Web application. The Local IIS option does not permit to work with IIS installations on any remote servers.

• FTP Site: This option enables to connect to a remote server using FTP capabilities. From this dialog, specify the server to contact using a URL or IP address, the port to use, and the directory on the server. Also specify the username and password to access the server via FTP.

• Remote Site: This option enables to connect to a remote site using FrontPage Server Extensions. Also connection to the remote server is possible using Secure Sockets Layer (SSL).

ASP.NET Deployment-Copy Web Site

Page 1624: Dotnet Stream

1624©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 Installer Option• Setup Project: This project type helps in creating a standard Windows

Installer setup for a Windows application.• Web Setup Project: It’s the type of setup project used to create an

installer for an ASP.NET Web application.• Merge Module Project: This project type creates a merge module

similar to a cabinet file.This project type produces a file type with an extension of .msm.

• Setup Wizard: This selection actually gives a wizard to assist the installer through one of the other defined project types.

• Cab Project: This project type creates a cabinet file (.cab) that packages a group of files for distribution.

• Smart Device Cab Project: This new project type allows for the creation of a cabinet file that is installed on a smart device instead of on a typical operating system.

ASP.NET Deployment-Visual Studio Installer

Page 1625: Dotnet Stream

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

Web Setup Project

• Open up the project for which a deployment project has to be created in Visual Studio. Choose FileNewProject from the Visual Studio menu.

• From the New Project dialog, Expand Other Project Types from the left-hand pane in the dialog and then select Setup and Deployment.

• Select Web Setup Project

• The File System Editor shows a single folder: the Web Application Folder.

• Choose ProjectAddProject Output from the Visual Studio menu.

• The Add Project Output Group dialog opens

• Highlight the Content Files option and click OK. This adds all the files from the MyShop project to the WebSetup1 installer program

• Click the Launch Conditions Editor but-ton in the Solution Explorer to open the editor

• To add conditions->Right-click the Requirements On Target Machine node. Then select Add .NET Framework Launch Condition

ASP.NET Deployment-Visual Studio Installer

Page 1626: Dotnet Stream

1626©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.

• Highlight the WebSetup1 program in the Visual Studio Solution Explorer so you can modify some of the properties that appear in the Properties window

• Select ‘Release’ as the active solution configuration in the Visual Studio toolbar

• Build the installer program by choosing BuildBuild WebSetup1 from the menu.

• Look in C:\Documents and Settings\Administrator\My Documents\Visual Studio\Projects\MyShop\WebSetup1\Release,

Setup.exe: This is the installation program. It is meant for machines that don’t have the Windows Installer service installed.

WebSetup1.msi: This is the installation program for those that have the Windows Installer service installed on their machine.

ASP.NET Deployment-Visual Studio Installer

Page 1627: Dotnet Stream

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

Web Site Health MonitoringWeb Site Health Monitoring

ASP.NET Health Monitoring

Page 1628: Dotnet Stream

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

ASP.NET provides an easy way to monitor the health of deployed ASP.NET applications, providing detailed run-time information about ASP.NET resources.

ASP.NET health-monitoring features can be used to perform the following tasks:

• Monitor live ASP.NET applications, individually or across a Web farm, to ensure that they are working properly.

• Diagnose ASP.NET applications that appear to be failing.• Log events that do not necessarily relate to errors in an ASP.NET

application but can be useful for examination.

ASP.NET Health Monitoring

Page 1629: Dotnet Stream

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

Web ServicesWeb Services

ASP.NET Web Services

Page 1630: Dotnet Stream

1630©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 for Discussion• Web Service Architecture

• Building Blocks of Web Service Protocols

• Web Service Development Designing a Web Service Creating a Web Service

• Web Service Deployment and Consumption of a Web Service In an Web Application In an Windows Application

ASP.NET Web Services

Page 1631: Dotnet Stream

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

Web Services

• Traditional middleware platforms such as DCOM,CORBA / IIOP and

Java RMI are used to build distributed systems. When exposed to

the World Wide Web they encounter the following problems:

Getting through firewalls.

Communicating across platforms.

Keeping systems components independent of each other.

• Web Service technology is the result of extensive collaboration

between industry leaders such as Microsoft and IBM and has

received widespread industry support.

• Web Service is loosely coupled, reusable software components that

semantically encapsulate discrete functionality and are distributed

and programmatically accessible over standard Internet protocols.

ASP.NET Web Services

Page 1632: Dotnet Stream

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

Web Services• Web services are a stack of emerging standards that describe a

service-oriented, component-based application architecture.

• A Component That Uses XML & HTTP To Define and Deliver A

Service

Global reach

Based on open set of standards

Reuse across platforms

Works with any operating system, programming language, or

network

Expose legacy code

• Different systems can actually talk

ASP.NET Web Services

Page 1633: Dotnet Stream

1633©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.

Architecture

• The browser sends a HTTP request to the Web server.

• Upon receiving the request the web server parses it.

• The Web server then sends a SOAP (Simple Object Access Protocol) request over HTTP to the web service provider.

• The web service provider parses the request and extracts the required information from its database.

• The Web service provider then sends the headlines in a SOAP response to the web server.

• The Web server parses the response and creates an HTML page and sends it via HTTP to the browser.

Web Service Architecture

Page 1634: Dotnet Stream

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

Web Services-Usage

Static Content

Web

Dynamic Interactive

Web

Integrated Programmable

Web

HTML Dynamic HTML (JavaScript)

CGI (using Perl, etc.) ColdFusion, ASP, Java Servlet, JSP ASP.NET XML (Document interchange)

XML Web Services (SOAP, WSDL, UDDI)

Page 1635: Dotnet Stream

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

Web Services-Protocols

Page 1636: Dotnet Stream

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

Web Services-Protocols

Business &

services info.

URL to WSDL

SOAP Response

SOAP Request

Publish

Find

Invoke

WSDL URLsSea

rch cr

iteria

for web

servi

ces

WSDL URL

WSDL File

Service Registries

• Public UDDI• Private UDDI

WebService

Consumers

WebService

Providers

Role Operation Data flow Data/Message

Bind

n

Page 1637: Dotnet Stream

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

Web Services-Protocols

Communication Protocol(HTTP, FTP, SMTP, etc.)

Service Description(WSDL)

Service Directory(UDDI)

Service Composition(BPEL4WS)

Secu

rity

(SA

ML,

WS-

Secu

rity)

(SOAP)

SOAP ExtensionReliability, Transaction

(WS-ReliableMessaging, WS-Transaction)

Messaging Protocol

Stan

dard

Def

initi

on L

angu

ages

(XM

L 1.

0 Sp

ecifi

catio

n an

d XM

L Sc

hem

a)

Man

agem

ent

(WS-

Man

agea

bilit

y )

Page 1638: Dotnet Stream

1638©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.

Protocols

• The SOAP specification was designed by industry leaders such as Microsoft , IBM and Lotus.

• SOAP: "Simple Object Access Protocol“

SOAP 1.1

SOAP 1.2

• XML-based lightweight protocol for exchanging information in a decentralized, distributed, heterogeneous environment

Encapsulates the ability to make RPC Calls

Data Encoding (serializing and de-serializing)

Message Structure

Message-Processing

• SOAP is used by the following .NET technologies.

ATL web services ( Active Template Library).

.NET remoting.

ASP.NET Web services.

Web Services Protocols-SOAP

Page 1639: Dotnet Stream

1639©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.

• Simple Object Access Protocol (SOAP) is the protocol used by consumers for sending requests to, and receiving responses from, XML Web services.

• It defines an XML grammar for specifying the names of methods that a consumer wants to invoke on an XML Web service; for defining the parameters and return values; and for describing the types of parameters and return values.

• When a client calls an XML Web service, it must specify the method and parameters by using this XML grammar.

• SOAP is being adopted as an industry standard. Its function is to improve cross- platform interoperability. The strength of SOAP is its simplicity and also the fact that it is based on other industry standard technologies: HTTP and XML.

• The SOAP specification defines a number of things. The most important are the following:

The format of a SOAP message How data should be encoded How to send messages (method calls) How to receive responses

Web Services Protocols-SOAP

Page 1640: Dotnet Stream

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

Web Services Protocols-SOAP

Proxyobject

XML WebServiceobject

SOAPmessage

XML

SOAPmessage

XML

SOAPmessage

XML

SOAPmessage

XML

SOAP Envelope HTTP Header

SOAPrequest

XML Data

Attachments

SOAPresponse

Phase 2Deserialize

Phase 3Serialize

Phase 1Serialize

Phase 4Deserialize

Web Server

Client

Page 1641: Dotnet Stream

1641©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.

The SOAP request sent by the client might look like this: POST /NorthwindServices/ProductService.asmx 

HTTP/1.1 Host: localhost

Content-Type: text/xml; charset=utf-8

Content-Length: 633

SOAPAction: "http://www.contentmaster.com/webservices/HowMuchWillItCost" <?

xml version="1.0" encoding="utf-8"?>

<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:xsd="http://www.w3.org/2001/ XMLSchema" xmlns:soap="

http://schemas.xmlsoap.org/soap/envelope/">   

<soap:Body>     

<HowMuchWillItCost xmlns="http://www.contentmaster.com/webservices">       

<productName>Chai</productName>       

<howMany>39</howMany>     

</HowMuchWillItCost>   

</soap:Body>

</soap:Envelope>

Web Services Protocols-SOAP Request

Page 1642: Dotnet Stream

1642©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.

The Web server will receive this request, identify the XML Web service and method to run, run the method, obtain the results, and send them back to the client as the following SOAP result:

HTTP/1.1 200 OK

Content-Type: text/xml; charset=utf-8Content-Length: 515

<?xml version="1.0" encoding="utf-8"?>

<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:xsd="http://www.w3.org/2001/ XMLSchema"

xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">  

<soap:Body>    

<HowMuchWillItCostResponse xmlns=     

"http://www.contentmaster.com/webservices">      

<HowMuchWillItCostResult>529</HowMuchWillItCostResult>    

</HowMuchWillItCostResponse>  

</soap:Body>

</soap:Envelope>

Web Services Protocols-SOAP Response

Page 1643: Dotnet Stream

1643©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.

WSDL• WSDL (Web Services Description Language) was created to address

the problem of describing web services in a comprehensive , understandable and formalized manner.

• It is a XML based language that describes the interfaces of web services , their input and output parameters and their protocol bindings.

• The structure and format of WSDL documents is formally specified – making every document machine readable.

• WSDL description documents can describe the following type of web service protocol bindings- HTTP GET,HTTP POST,SOAP,MIME

• A client can submit a request to an XML Web service with the query string wsdl appended to it:http://localhost/NorthwindServices/ProductService.asmx?wsdl

• The XML Web service will reply with a description • This description provides enough information to allow a client to

construct a SOAP request in a format that the Web server should understand.

Web Services Protocols-WSDL

Page 1644: Dotnet Stream

1644©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.

WSDL Document Structure• Each WSDL document id divided into distinct sections-Types,

Messages, Port types, Bindings and Services.• The root element of a WSDL description is <definitions>. Below this

element are a list of XML namespaces.• The <message> element occurs within the Messages section. It

comprises a group of parameters to a web service operation, which is essentially a function.

• The Port Types section optionally comprises <portType> elements, which provide abstract definitions of operations.

• There can be zero or more <binding> elements in the Binding section-if there are no binding elements, the web service will be functional but not accessible.

• The Services section comprises <port> elements, which associate with <binding> elements in the binding section.

Web Services Protocols-WSDL

Page 1645: Dotnet Stream

1645©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.

UDDI• UDDI (Universal Description Discovery and Integration) is a platform independent,

open framework for discovering businesses and services using the internet. It acts as a functional business and service registry.

• It enables applications to locate the Web Services, either within the internal system or over the internet by referencing WSDL formatted protocol descriptions.

• UDDI is maintained by the UDDI community, which is a consortium of more than 200 companies that includes all industry leaders.

• Since the technology used is XML based, its searching and describing potential is extensible.

• UUDI was jointly launched by Microsoft, IBM and Ariba.

• Its purpose is to standardize how businesses describe and publish the Web Service.

• The UDDI tool has 2 main elements : UDDI XML schema for business description. Web based registry.

• There are currently 2 public versions of UDDI registry hosted by Microsoft and IBM.

• To access the Microsoft UDDI and located the Microsoft services type

http://uddi.microsoft.com in the browser.

Web Services Protocols-UDDI

Page 1646: Dotnet Stream

1646©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.

Designing a Web Service• This involves breaking the entire process into smaller design stages

and completing each stage before moving on to the next. It involves the following stages:

Vision Document. Conceptual Design. Logical Design. Physical Design. Architecture. Security Design

Designing a Web Service

Page 1647: Dotnet Stream

1647©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.

Vision Document• The vision document establishes the goals of the service. It should

cover the following areas: The user base for your service. The business objectives. Its specific functions. Accessing running costs. How long it would take to attract users and what they would

pay for it. Deciding how Managers and maintainers would access the

service. The end users of the service. Any third party companies that might not pay for the service

but would need to access the same for security and authentication.

Designing a Web Service

Page 1648: Dotnet Stream

1648©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.

Conceptual Design• The purpose of conceptual design is to plan how your service will

actually be used.• This can be done by identifying users and their requirements.• The advantages of the conceptual design is

Identify common system access points. Have a better idea about how the different elements of a

service will work together. Logical components that would comprise the web service.

Designing a Web Service

Page 1649: Dotnet Stream

1649©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.

Logical and Physical DesignLogical Design involves

Analyzing the functions the service will have to perform . Breaking the functions into logical components. Determining the relation among objects of a web service.

Physical Design• Examine the components of the web service identified earlier and

decide about their physical implementation.• There are certain criteria that should be applied while selecting

components Scalability High performance. High availability.

Designing a Web Service

Page 1650: Dotnet Stream

1650©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.

Security Design and Architecture• While designing the Web service the security requirements must be

considered regarding the following issues Authentication: The identity of a user should be checked before

letting them access personal data. Could be one among the following: Web Forms, Integrated Windows, clear text, certificates.

Privacy : The information sent by the web service should be seen by the user for which it is intended.

Authorization : Only authorized users should be provided access to certain code and the privilege to change data.

Designing a Web Service

Page 1651: Dotnet Stream

1651©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.

AuthenticationWeb services can use either one or more of the following

authentication methods:• Web Forms: When the user attempts to access a Web service, he is redirected to an

HTML Form, usually containing simple user name and password. Use for protecting the user’s custom settings rather than for protecting valuable data.

• Integrated Windows Authentication: Performed by IIS ( Internet Information Server). Accounts are created for users who can then access the services. It allows us to group accounts for users.

• Clear text authentication: Uses user names and passwords to identify users and encode the information using Base64 encoding before sending it to the internet.

• Certificates : Issued by third parties and users can use them to identify themselves to the web service. The authentication work is handled by the issuing authority.

• Advanced Authentication methods : HTTPS or SOAP can be used . SOAP provides Greater customization. Protocol Independence.

Designing a Web Service

Page 1652: Dotnet Stream

1652©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.

Authentication• Malicious users would try to gain access to the web service through

spoofing. A strong encryption method is one of the best defenses.• Hackers might try to detect the common passwords to gain

unauthorized access. This is called dictionary attack. This can be checked by frequently changing the passwords and frequent system audits.

• Denial of service attacks might be used to bring down services and servers. This can be done by issuing a ping request to another computer. To deal with the menace denial of ping request can be done.

• Another alternative could be to place your web service behind a firewall. This can be useful if the No. of users are lesser and within a range e.g. employees of a particular company.

• The best way could be to remove all non essential software from your machine and distributing the services across multiple servers

Designing a Web Service

Page 1653: Dotnet Stream

1653©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.

Design Issues• While designing a web service client, you can use two methods of

invoking the service methods: Synchronous Asynchronous

• In the synchronous web service, communication between client and server occurs at regular intervals.

• In an asynchronous communication, the client connects at irregular intervals. Client is free to call other methods before the service responds. Writing these web services is more complex for parallel execution.

• However, asynchronous programming has these advantages Efficient use of processing resources. Better use of threads in Server side programming. Ability of a single program to exploit multiple processors.

Designing a Web Service

Page 1654: Dotnet Stream

1654©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.

Design Issues-Exception Handling• Using the wsdl.exe tool of Microsoft Framework, for a single web

method present in the Web service, 3 methods are generated: The first method is a synchronous method. The other 2 are asynchronous method-one to begin the request

and other to end it.• Web services are subjected to failure due to bugs, network

problems or other reasons. The SOAP specifications communicates these exceptions to the web client. These are called SOAP faults.

• By default, when the web client receives a SOAP fault, it generates an error message.

• For displaying Custom error messages from the client, the SOAP fault message can be trapped using the SOAPException class located in the System.Web.Services.Protocols namespace.

Designing a Web Service

Page 1655: Dotnet Stream

1655©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.

Creating the ProductService Web Service• Create a new project using the ASP.NET Web Service template. Call

the project NorthwindServices, and create it on your local Web server.• In Solution Explorer, change the name of the Web service class file

from Service1.asmx to  ProductService.asmx.• In Class View, rename the Service1 class to ProductService. • Select the class, and then on the View menu, click Code to display the

Code And Text Editor window for ProductService. Notice that it is held in a file called  ProductService.asmx.cs.

• Examine the ProductService class; it is descended from System.Web. Services.WebService. Scroll to the bottom of the class. A method has been commented out because this is just a sample Web method.

• Add the following WebService attribute to the ProductService class. This attribute indicates the namespace used to identify the XML Web service:[WebService     (Namespace="http://www.contentmaster.com/NorthwindServices")] public class ProductService : System.Web.Services.WebService {      } ⋮

Creating Web Services

Page 1656: Dotnet Stream

1656©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.

Define the HowMuchWillItCost Web method • Delete the sample Web method (HelloWorld, which is commented

out) in the ProductService class. In its place, add the following method:

[WebMethod] public decimal HowMuchWillItCost(string productName,     int howMany) { }

• All methods exposed by an XML Web service must be tagged with the WebMethod attribute. This method will expect the client to pass in the name of a product found in the Products table in the Northwind Traders database and a quantity of that product. The method will use the information in the database to calculate the cost of supplying this quantity of the product and pass it back as the return value of the method.

• Add the following using statement to the top of the file:

using System.Data.SqlClient;

• This is the namespace that contains the Microsoft ADO.NET classes for gaining access to the Microsoft SQL Server computer.

Creating Web Services

Page 1657: Dotnet Stream

1657©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.

Define the HowMuchWillItCost Web method In the HowMuchWillItCost Web method, type the following

statements:try {     

SqlConnection sqlConn = new SqlConnection( "data source=localhost;" +         "initial catalog=Northwind;integrated security=true");     

SqlCommand sqlCmd = new SqlCommand();     

sqlCmd.CommandText = "SELECT UnitPrice FROM Products " +         "WHERE ProductName = ’" + productName + "‘";     

sqlCmd.Connection = sqlConn;     

sqlConn.Open();     

decimal price = (decimal)sqlCmd.ExecuteScalar();     

sqlConn.Close();     

return price * howMany;

} catch(Exception e)

{     

throw new Exception("Error calculating cost: " + e.Message);

}

Creating Web Services

Page 1658: Dotnet Stream

1658©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.

Define the HowMuchWillItCost Web method • This code connects to the Northwind Traders database and runs an

SQL SELECT statement to retrieve the UnitPrice column for the selected product in the Products table. The ExecuteScalar method is the most efficient way of running a SELECT statement that returns a single value. The UnitPrice column is stored in the price variable, which is then multiplied by the howMany parameter that is passed in to calculate the cost.

• Although the Web service uses a try...catch block to trap any database access errors, it does not validate the parameters passed in (for example, the client might supply a negative value for the howMany parameter). You should add the necessary code yourself.

• On the Build menu, click Build Solution to compile the XML Web service.

Creating Web Services

Public Function HelloWorld() as String

return “Hello World”

End Function

[WebMethod]WSDLWSDL

WebServiceObject

WebServiceObject

TestPage

TestPage

Compiler

Page 1659: Dotnet Stream

1659©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.

Creating Web Services

Page 1660: Dotnet Stream

1660©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.

Creating Web Services

Page 1661: Dotnet Stream

1661©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.

Creating Web Services

Page 1662: Dotnet Stream

1662©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.

Creating Web Services

Page 1663: Dotnet Stream

1663©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.

Consuming Web Services

Create XML Web service client application • In the Visual Studio .NET

programming environment, create a new project using the Windows Application template. Call the project OrderCost

• Change the Text property of Form1 to Order Cost.

• Add and set the properties of these controls using the values in the following table.

• On the Project menu, click Add Web Reference. In the Add Web reference dialog box, type http://localhost/NorthwindServices/ProductService.asmx in the URL text box and press Enter.

• Click Add Reference. The localhost Web Reference will be added to the project.

Control Property Value

label1 Text Product Name

Location 16, 40

label2 Text Number Required

Location 16, 80

label3 Text Total Cost

Location 16, 200

textBox1 Name ProductName

Location 128, 40

Text Leave blank

numericUpDown1 Name NumberRequired

Location 128, 80

textBox2 Name TotalCost

Location 128, 200

Text Leave blank

button1 Name HowMuchButton

Location 16, 136

Text How Much

Page 1664: Dotnet Stream

1664©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.

Consuming Web Services

Page 1665: Dotnet Stream

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

Web Services-Deployment

Add Web RefHTTP/WSDL

WSClass.Method(…) as Method Return Type

HTTP-SOAP-IN Message

Web Services Provider

Web Services Consumer

Web ServiceSource Code

(Server)

Compiler

VS.NET

.NET ClientPlatform

Web ServiceProxy Code

ClientApplication

Web ServiceProxy Code

(client)Compiler

ClientSource Code

VS.NET

Web ServicesApplication Server

Web ServiceExecutablesDeploy

WSDL

HTTP-SOAP-OUT

Page 1666: Dotnet Stream

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.

Best Practices with Best Practices with .NET Framework.NET Framework

Page 1667: Dotnet Stream

1667©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.

How do I… • Create an n-tier design for my Web site?• Store and retrieve application settings?• Create a dynamic and flexible user interface?• Ensure common code runs each time a page is loaded?• Track users’ actions throughout my Web application?• Track and notify tech support of exceptions that occur?• Provide bullet-proof access to Session variables?• Ensure unexpected errors are handled gracefully?• Assign roles to users and secure Web pages?• Provide the best performance?

Web Application Development with ASP.NETASP.NET Best Practices-Planning

Page 1668: Dotnet Stream

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.

QuizQuiz

Page 1669: Dotnet Stream

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

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

Final Case StudyFinal Case Study

Page 1670: Dotnet Stream

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

DotNet Schedule

Page 1671: Dotnet Stream

1671©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.

Evaluation Criteria

Appraisals Weightage Pass Criteria

Mini Case study 15 Marks 10 Marks

Final Case study 35 Marks 23 Marks

Test 50 Marks 32 Marks

Total 100 Marks 65 Marks

Page 1672: Dotnet Stream

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.

Thank YouThank You