CSharp Handout v1.0

Share Embed Donate


Short Description

Download CSharp Handout v1.0...

Description

Handout: C# Version: C#/Handout/0308/1.0 Date: 10-04-08

Cognizant 500 Glen Pointe Center West Teaneck, NJ 07666 Ph: 201-801-0233 www.cognizant.com

Handout - C#

TABLE OF CONTENTS

Introduction ...................................................................................................................................8  About this Module .........................................................................................................................8  Target Audience ...........................................................................................................................8  Module Objectives ........................................................................................................................8  Pre-requisite .................................................................................................................................8  Session 02: Overview of .NET Framework...................................................................................9  Learning Objectives ......................................................................................................................9  Overview of .Net Framework ........................................................................................................9  Common Language Runtime........................................................................................................9  CommonTypeSystem .................................................................................................................10  Common Language Specification...............................................................................................11  Assembly ....................................................................................................................................12  Application Domains ...................................................................................................................13  Runtime Hosts ............................................................................................................................14  Garbage Collection .....................................................................................................................15  Summary ....................................................................................................................................16  Test Your Understanding............................................................................................................16  Session 03: Introduction to C# ...................................................................................................17  Learning Objectives ....................................................................................................................17  C# Variables, Identifiers and Keywords .....................................................................................17  C# Statements ............................................................................................................................18  Identifiers ....................................................................................................................................23  Keywords ....................................................................................................................................23  Console Applications ..................................................................................................................24  Summary ....................................................................................................................................25  Test Your Understanding............................................................................................................25  Session 05: Data Types and Control Flow .................................................................................26  Learning Objectives ....................................................................................................................26  Data Types .................................................................................................................................26  Boxing and UnBoxing .................................................................................................................33  Operators ....................................................................................................................................35  Control Flow................................................................................................................................37  Summary ....................................................................................................................................44 

Page 2 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Test your Understanding ............................................................................................................44  Session 08: Arrays, Methods and Parameters ..........................................................................45  Learning Objectives ....................................................................................................................45  Arrays .........................................................................................................................................45  Methods ......................................................................................................................................50  Parameters .................................................................................................................................51  Method Overloading ...................................................................................................................53  Summary ....................................................................................................................................54  Test your Understanding ............................................................................................................54  Session 11: Creating Value with Enumerations and Structs ...................................................55  Learning Objectives ....................................................................................................................55  Enumerations..............................................................................................................................55  Structs.........................................................................................................................................57  Summary ....................................................................................................................................58  Test your Understanding ............................................................................................................58  Session 12: Classes and Objects ...............................................................................................59  Learning Objectives ....................................................................................................................59  Fundamentals of object-oriented programming..........................................................................59  Characteristics of an object-oriented language ..........................................................................60  Inheritance, Overriding and Overloading ....................................................................................61  Polymorphism .............................................................................................................................64  Summary ....................................................................................................................................66  Test your Understanding ............................................................................................................66  Session 13: Classes and Objects ...............................................................................................67  Learning Objectives ....................................................................................................................67  Classes and Objects ...................................................................................................................67  Properties ...................................................................................................................................68  Indexers ......................................................................................................................................69  Access Modifiers.........................................................................................................................72  Summary ....................................................................................................................................78  Test your Understanding ............................................................................................................78  Session 14: Classes and Objects ...............................................................................................79  Learning Objectives ....................................................................................................................79  Static Methods, Variables and Classes ......................................................................................79 

Page 3 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Partial Classes ............................................................................................................................80  Nested Classes...........................................................................................................................82  Summary ....................................................................................................................................83  Test your Understanding ............................................................................................................83  Session 17: Inheritance and Interface ........................................................................................84  Learning Objectives ....................................................................................................................84  Inheritance ..................................................................................................................................84  Abstract Class.............................................................................................................................85  Interface ......................................................................................................................................86  Summary ....................................................................................................................................88  Test Your Understanding............................................................................................................88  Session 21: Nunit .........................................................................................................................89  Learning Objectives ....................................................................................................................89  Nunit: ..........................................................................................................................................89  Summary ..................................................................................................................................102  Test your Understanding ..........................................................................................................102  Session 23: Generics and Collections .....................................................................................103  Learning Objectives ..................................................................................................................103  Generics ...................................................................................................................................103  Classes in Generics ..................................................................................................................105  Summary ..................................................................................................................................111  Test Your Understanding..........................................................................................................112  Session 24: Generics and Collections .....................................................................................113  Learning Objectives ..................................................................................................................113  Collections ................................................................................................................................113  Defining Collections ..................................................................................................................113  Commonly Used Collection Types ...........................................................................................113  Creating and manipulating collection .......................................................................................114  When to use Generics collections ............................................................................................114  Classes in collections ...............................................................................................................114  Summary ..................................................................................................................................122  Test Your Understanding..........................................................................................................122  Session 27: Exception Handling ...............................................................................................123  Learning Objectives ..................................................................................................................123 

Page 4 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Exception handling in C# ..........................................................................................................123  Throw Statement ......................................................................................................................125  Finally Statement ......................................................................................................................125  User Defined Exceptions ..........................................................................................................126  Exception Type .........................................................................................................................126  Summary ..................................................................................................................................128  Test your Understanding ..........................................................................................................129  Session 30: File Handling ..........................................................................................................130  Learning Objectives ..................................................................................................................130  Stream Class ............................................................................................................................130  Binary Reader ...........................................................................................................................132  Binary Writer .............................................................................................................................133  Text Reader ..............................................................................................................................134  Text Writer ................................................................................................................................136  File I/O Operations ...................................................................................................................139  Stream Reader Class ...............................................................................................................139  Stream Writer Class ................................................................................................................140  Summary ..................................................................................................................................142  Test Your Understanding..........................................................................................................142  Learning Objectives ..................................................................................................................143  XML ..........................................................................................................................................143  XML Document Object Model...................................................................................................146  Reading XML with the XmlReader ...........................................................................................149  Writing XML with the XmlWriter ................................................................................................150  Summary ..................................................................................................................................152  Test your Understanding ..........................................................................................................152  Session 34: Delegates and Events ...........................................................................................153  Learning Objectives ..................................................................................................................153  Events and Delegates: .............................................................................................................153  Summary ..................................................................................................................................160  Test your Understanding ..........................................................................................................160  Session 37: Multithreading ........................................................................................................161  Learning Objectives ..................................................................................................................161  Multithreading ...........................................................................................................................161  Thread States: ..........................................................................................................................161  How Threading Works: .............................................................................................................162 

Page 5 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

The Thread Pool class ..............................................................................................................162  Multithreading in C# ..................................................................................................................162  Advantages and Disadvantages of Multithreading ...................................................................164  Summary ..................................................................................................................................164  Test Your Understanding..........................................................................................................165  Session 40: Reflection and Serialization .................................................................................166  Learning Objectives ..................................................................................................................166  Reflection ..................................................................................................................................166  Summary ..................................................................................................................................169  Test Your Understanding..........................................................................................................169  Session 42: Reflection and Serialization .................................................................................170  Learning Objectives ..................................................................................................................170  Overview ...................................................................................................................................170  What is Serialization and De-serialization? ..............................................................................170  Working with formatters: ...........................................................................................................173  Advantages and disadvantages of serialization .......................................................................174  Summary ..................................................................................................................................174  Test Your Understanding..........................................................................................................174  Session 45: .NET Interoperability .............................................................................................175  Learning Objectives ..................................................................................................................175  Overview of .NET and COM interoperability ............................................................................175  Interoperability through Runtime wrappers ..............................................................................175  Programming Model comparison of .NET-COM interoperability ..............................................176  .NET Marshalling ......................................................................................................................177  Interop marshaler .....................................................................................................................177  COM Marshaler ........................................................................................................................178  Summary ..................................................................................................................................178  Test your Understanding ..........................................................................................................179  Session 47: Remoting ................................................................................................................180  Learning Objectives ..................................................................................................................180  .NET Remoting basics ..............................................................................................................180  .NET Remoting concepts..........................................................................................................180  .NET Remoting Architecture .....................................................................................................183  Summary ..................................................................................................................................184  Test your Understanding ..........................................................................................................185 

Page 6 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Session 48: Remoting ................................................................................................................186  Learning Objectives ..................................................................................................................186  Remoting Application: ...............................................................................................................186  Summary ..................................................................................................................................190  Test your Understanding ..........................................................................................................190  Session 50: Garbage Collection and Memory Management ..................................................191  Learning Objectives ..................................................................................................................191  Memory Management ...............................................................................................................191  Allocating Memory ....................................................................................................................191  Releasing Memory ....................................................................................................................191  Garbage Collection: ..................................................................................................................193  Summary ..................................................................................................................................200  Test your Understanding ..........................................................................................................200  Glossary ......................................................................................................................................201  References ..................................................................................................................................208  Websites ...................................................................................................................................208  Books ........................................................................................................................................208  STUDENT NOTES: ......................................................................................................................209 

Page 7 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Introduction About this Module This module provides developer with the knowledge and skills that are needed to develop and implement applications using C#.NET.

Target Audience This module is designed for entry level developers using C# and .NET technologies.

Module Objectives After completing this module, you will be able to: ‰

Describe features of C#

‰

Apply .NET Framework technologies like BCL, Remoting, Reflection, and Interop in C#

‰

Explain and write C# programs using variables, arrays, operators, and namespaces

‰

Write C# programs implementing exceptions handling

‰

Describe Object oriented programming in C#

‰

Explain threading concept and write multi-threaded programs

‰

Explain input output operations in C#

‰

Interoperate with legacy COM

‰

Define the concepts of Delegates, Events, Reflection, and Remoting

Pre-requisite Working knowledge in any object oriented programming language and a basic understanding of .NET technologies.

Page 8 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Session 02: Overview of .NET Framework Learning Objectives After completing this session, you will be able to: ‰

Describe the .NET Framework

‰

Explain Common Language Runtime (CLR), Explain Common Type System (CTS), and Common Language system (CLS)

‰

Explain Assembly and Application Domain

‰

Describe Runtime Host and Garbage Collection

Overview of .Net Framework The .NET Framework is an integral Windows component that supports building and running the next generation of applications and XML Web services. The .NET Framework is designed to fulfill the following objectives: ‰

To provide a consistent object-oriented programming environment whether object code is stored and executed locally, executed locally but Internet-distributed, or executed remotely.

‰

To provide a code-execution environment that minimizes software deployment and versioning conflicts.

‰

To provide a code-execution environment that promotes safe execution of code, including code created by an unknown or semi-trusted third party.

‰

To provide a code-execution environment that eliminates the performance problems of scripted or interpreted environments.

‰

To make the developer experience consistent across widely varying types of applications, such as Windows-based applications and Web-based applications.

‰

To build all communication on industry standards to ensure that code based on the .NET Framework can integrate with any other code.

The .NET Framework has two main components: ‰

Common language runtime

‰

.NET Framework class library.

Common Language Runtime The common language runtime makes it easy to design components and applications whose objects interact across languages. Objects written in different languages can communicate with each other and their behaviors can be tightly integrated.

Page 9 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

For example, you can define a class and then use a different language to derive a class from your original class or call a method on the original class and also pass an instance of a class to a method of a class written in a different language. This cross-language integration is possible because language compilers and tools that target the runtime use a common type system defined by the runtime, and they follow the runtime's rules for defining new types, as well as for creating, using, persisting, and binding to types. Benefits of the CLR are as follows: ‰

Performance improvements.

‰

The ability to easily use components developed in other languages.

‰

Extensible types provided by a class library.

A CLR feature includes the following: ‰

Cross-language integration, especially cross-language inheritance.

‰

Garbage collection, which manages object lifetime so that reference counting is unnecessary.

‰

Self-describing objects, which make using Interface Definition Language (IDL) unnecessary.

‰

The ability to compile once and run on any CPU and operating system that supports the runtime.

CommonTypeSystem The common type system defines how types are declared, used, and managed in the runtime, and is also an important part of the runtime's support for cross-language integration. The common type system performs the following functions: ‰

Establishes a framework that helps enable cross-language integration, type safety, and high performance code execution.

‰

Provides an object-oriented model that supports the complete implementation of many programming languages.

‰

Defines rules that languages must follow, which helps ensure that objects written in different languages can interact with each other.

Classification of Types: The common type system supports two general categories of types, each of which is further divided into subcategories: ‰

Value types: Value types directly contain their data, and instances of value types are either allocated on the stack or allocated inline in a structure. Value types can be builtin (implemented by the runtime), user-defined or enumerations

‰

Reference types: Reference types store a reference to the value's memory address, and are allocated on the heap. Reference types can be self-describing types, pointer types, or interface types. The type of a reference type can be determined from values of self-describing types. Self-describing types are further split into arrays and class types. The class types are user-defined classes, boxed value types, and delegates.

Page 10 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

The following example shows the difference between reference types and value types: using System; class Class1 { public int Value = 0; } class Test { static void Main() { int val1 = 0; int val2 = val1; val2 = 123; Class1 ref1 = new Class1(); Class1 ref2 = ref1; ref2.Value = 123; Console.WriteLine("Values: {0}, {1}", val1, val2); Console.WriteLine("Refs: {0}, {1}", ref1.Value, ref2.Value); } } Type classification:

Common Language Specification It is a set of basic language features needed by many applications, has been defined. The CLS rules define a subset of the Common Type System. All the rules that apply to the common type system apply to the CLS, except where stricter rules are defined in the CLS.

Page 11 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Assembly Assemblies are a fundamental part of programming with the .NET Framework. It contains code that the common language runtime executes. Microsoft intermediate language (MSIL) code in a portable executable (PE) file will not be executed if it does not have an associated assembly manifest. Assemblies can be static or dynamic. Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in portable executable (PE) files. We can also use the .NET Framework to create dynamic assemblies, which are run directly from memory and are not saved to disk before execution. We can save dynamic assemblies to disk after they have executed. Assembly Benefits: ‰

Assemblies are designed to simplify application deployment

‰

It solves versioning problems that can occur with component-based applications

‰

It provides the infrastructure to allow multiple versions of a component to be run simultaneously.

Assembly Manifest: Every assembly, whether static or dynamic, contains a collection of data that describes how the elements in the assembly relate to each other. The assembly manifest contains this assembly metadata. The following illustration shows the different ways the manifest can be stored:

For an assembly with one associated file, the manifest is incorporated into the PE file to form a single-file assembly. You can create a multifile assembly with a standalone manifest file or with the manifest incorporated into one of the PE files in the assembly. Each manifest of assembly performs the following functions: ‰

Enumerates the files that make up the assembly.

‰

Governs how references to the assembly's types and resources map to the files that contain their declarations and implementations.

‰

Enumerates other assemblies on which the assembly depends.

Page 12 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

‰

Provides a level of indirection between consumers of the assembly and the assembly's implementation details.

‰

Renders the assembly self-describing.

Assembly Manifest Contents: The following table shows the information contained in the assembly manifest. The first four items—the assembly name, version number, culture, and strong name information—make up the assembly's identity.

Information

Description

Assembly name

A text string specifying the assembly's name.

Version number

A major and minor version number, and a revision and build number. The common language runtime uses these numbers to enforce version policy.

Culture

Information on the culture or language the assembly supports. This information should be used only to designate an assembly as a satellite assembly containing culture- or language-specific information. (An assembly with culture information is automatically assumed to be a satellite assembly.)

Strong name information

The public key from the publisher if the assembly has been given a strong name.

List of all files in the assembly

A hash of each file contained in the assembly and a file name. Note that all files that make up the assembly must be in the same directory as the file containing the assembly manifest.

Type reference information

Information used by the runtime to map a type reference to the file that contains its declaration and implementation. This is used for types that are exported from the assembly.

Information on referenced assemblies

A list of other assemblies that are statically referenced by the assembly. Each reference includes the dependent assembly's name, assembly metadata (version, culture, operating system, and so on), and public key, if the assembly is strong named.

Application Domains Application domains provide a flexible and secure method of isolating running applications. Application domains are usually created and manipulated by run-time hosts. Application domains aid security, separating applications from each other and each other's data. A single process can run several application domains, with the same level of isolation that would exist in separate processes. Running multiple applications within a single process increases server scalability. In the following code example, you create a new application domain and then load and execute a previously built assembly, HelloWorld.exe that is stored on drive C. static void Main() { // Create an Application Domain: System.AppDomain newDomain=

Page 13 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

System.AppDomain.CreateDomain("NewApplicationDomain"); // Load and execute an assembly: newDomain.ExecuteAssembly(@"c:\HelloWorld.exe"); // Unload the application domain: System.AppDomain.Unload(newDomain); } Application domains have the following properties: ‰

An assembly must be loaded into an application domain before it can be executed.

‰

Faults in one application domain cannot affect other code running in another application domain.

‰

Individual applications can be stopped and code unloaded without stopping the entire process. Cannot unload individual assemblies or types, only entire application domains.

Advantages of Application Domain: ‰

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.

‰

Individual applications can be stopped without stopping the entire process. Using application domains enables you to unload the code running in a single application.

‰

Code running in one application cannot directly access code or resources from another application.

‰

The behaviour 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.

‰

Permissions granted to code can be controlled by the application domain in which the code is running.

Runtime Hosts The common language runtime has been designed to support a variety of different types of applications from Web server applications to applications with a traditional rich Windows user interface. Each type of application requires a runtime host to start it. The runtime host loads the runtime into a process, creates the application domains within the process, and loads user code into the application domains.

Page 14 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

The .NET Framework ships with a number of different runtime hosts, including the hosts listed in the following table:

Runtime Host

Description

ASP.NET

Loads the runtime into the process that is to handle the Web request. ASP.NET also creates an application domain for each Web application that will run on a Web server.

Microsoft Internet Explorer

Creates application domains in which to run managed controls. The .NET Framework supports the download and execution of browser-based controls. The runtime interfaces with the extensibility mechanism of Microsoft Internet Explorer through a mime filter to create application domains in which to run the managed controls. By default, one application domain is created for each Web site.

Shell executables

Invokes runtime hosting code to transfer control to the runtime each time an executable is launched from the shell.

Garbage Collection The .NET Framework's garbage collector manages the allocation and release of memory for your application. Each time you use the new operator to create an object, the runtime allocates memory for the object from the managed heap. As long as address space is available in the managed heap, the runtime continues to allocate space for new objects. However, memory is not infinite. Eventually the garbage collector must perform a collection in order to free some memory. The garbage collector's optimizing engine determines the best time to perform a collection, based upon the allocations being made. When the garbage collector performs a collection, it checks for objects in the managed heap that are no longer being used by the application and performs the necessary operations to reclaim their memory. Automatic memory management is one of the services that the common language runtime provides during Managed Execution. The common language runtime's garbage collector manages the allocation and release of memory for an application. For developers, this means do not have to write code to perform memory management tasks when develop managed applications. Automatic memory management can eliminate common problems, such as forgetting to free an object and causing a memory leak, or attempting to access memory for an object that has already been freed.

Page 15 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Summary ‰

.Net Framework: A common environment for building, deploying, and running Web Services and Web Applications.

‰

Common Language Runtime (CLR): It provides a common runtime for all .NET languages.

‰

Common Type System (CTS): It defines how types are declared, used, and managed in the runtime.

‰

Common Language System (CLS): It specifies the interoperability or the ability to exchange and use information between .NET languages.

‰

Application Domain: It is a logical and physical boundary created around every .NET application by CLR.

‰

Runtime Host: It loads user code into the application domains.

Test Your Understanding 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.

What are the components of .Net Framework? What is the purpose of CLR? What are main functions of CLR? What is CTS? What is CLS? What is an Assembly? What is an Application Domain? What is Runtime Host? What are types of Runtime Host in .Net Framework? How many generations are there in GC?

Page 16 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Session 03: Introduction to C# Learning Objectives After completing the session, you will be able to: ‰

Define Variables, statements, Identifiers, and Keywords of C#

‰

Explain the Console Application of C#

C# Variables, Identifiers and Keywords Variables represent storage locations. Every variable has a type that determines the values that can be stored in the variable. C# is a type-safe language and the C# compiler guarantees that values stored in variables are always of the appropriate type. C# defines seven categories of variables: static variables, instance variables, array elements, value parameters, reference parameters, output parameters, and local variables. The following sample depicts each of these categories. C# Variables: class A { public static int x; int y; void F(int[] v, int a, ref int b, out int c) { int i = 1; c = a + b++; } } Where x is a static variable: A field declared with the static modifier. A static variable comes into existence before execution of the static constructor for its containing type, and ceases to exist when the associated application domain ceases to exist. y is an instance variable: A field declared without the static modifier is called an instance variable. An instance variable of a class comes into existence when a new instance of that class is created, and ceases to exist when there are no references to that instance and the instance's destructor (if any) has executed. v[0] is an array element: The elements of an array come into existence when an array instance is created, and cease to exist when there are no references to that array instance. a is a value parameter: A parameter declared without a ref or out modifier is a value parameter.

Page 17 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

b is a reference parameter: A parameter declared with an ref modifier is an reference parameter. c is an output parameter: A parameter declared with an out modifier is an output parameter. And finally i is a local variable. A local variable is declared by a local-variable-declaration, which may occur in a block, a forstatement, a switch-statement or a using-statement. The lifetime of a local variable is the portion of program execution during which storage is guaranteed to be reserved for it. The types of the C# language are divided into two main categories: value types and reference types. A third category of types, pointers, is available only in unsafe code. Value types differ from reference types in that variables of the value types directly contain their data, whereas variables of the reference types store references to their data, the latter being known as objects. With reference types, it is possible for two variables to reference the same object, and thus possible for operations on one variable to affect the object referenced by the other variable. With value types, the variables each have their own copy of the data and it is not possible for operations on one to affect the other.

C# Statements Statements are program instructions and they are executed in sequence. C# has the following categories of statements: S.No

Category

Purpose

C# keywords

1. Selection statements

Causes the program control to be transferred to a specific flow based upon whether a certain condition is true or not.

if, else, switch, case

2. Iteration statements

You can create loops by using the iteration statements. Iteration statements cause embedded statements to be executed a number of times, subject to the loop-termination criteria. These statements are executed in order, except when a jump statement is encountered.

do, for, foreach, in, while

3. Jump statements

Branching is performed using jump statements, which cause an immediate transfer of the program control.

break, continue, default, goto, return, yield

4. Exception handling statements

C# provides built-in support for handling anomalous situations, known as exceptions, which may occur during the execution of your program. These exceptions are handled by code that is outside the normal flow of control.

throw, trycatch, tryfinally, trycatch-finally

Page 18 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

S.No

Category

Purpose

C# keywords

5. Checked and unchecked

C# statements can execute in either checked or unchecked context. In a checked context, arithmetic overflow raises an exception. In an unchecked context, arithmetic overflow is ignored and the result is truncated. If neither checked nor unchecked is specified, the default context depends on external factors such as compiler options.

checked, unchecked

6. fixed Statement

The fixed statement prevents the garbage collector from relocating a movable variable. The fixed statement is only permitted in an unsafe context. Fixed can also be used to create fixed size buffers.

fixed

7. lock Statement

The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock.

lock

// statements_if_else.cs // if-else example using System; class IfTest { 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("Not an alphabetic character."); } } }

Page 19 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Iteration statements: // cs_foreach.cs class ForEachTest { static void Main(string[] args) { int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 }; foreach (int i in fibarray) { System.Console.WriteLine(i); } } } Jump statements: // statements_continue.cs using System; class ContinueTest { static void Main() { for (int i = 1; i

6

Relational

==

!=

7

Assignment

= =

+ , &

- , |

* ,

^

!

/ , % ~

&&

||

true

false

+ ++ , --

+= *=

8

Member access

9

Indexing

[ ]

10

Cast

()

11

Conditional

?:

12

Delegate Concatenation and Removal

+ , -

13

Object creation

new

14

Type information

16

Indirection and Address

<

>

/=

%=

= |=

^=

=

??

.

as , is , Typeof() , sizeof() * ,

-> ,

[ ] , &

Note that while writing classes it is possible to change the default behavior of some of these operators, although this should only be done where the resultant semantics makes sense. The earlier table also indicates which of the operators are overloadable.

Page 35 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Operator precedence and their associability: When an expression contains multiple operators, the precedence of the operators controls the order in which the individual operators are evaluated. For example, the expression x + y * z is evaluated as x + (y * z) because the * operator has higher precedence than the binary + operator. The following table summarizes all operators in order of precedence from highest to lowest: Category Primary

Operators x.y

Unary

f(x) +

Associability

a[x] x++ x-- new typeof checked unchecked

-

!

Multiplicative

~

++x

*

/

Additive

--x

Left

(T)x

Left

%

Left

+ -

Shift



Equality

> >=

==

Left

is

Left

as

Right

!=

Logical AND

&

Left

Logical XOR

^

Left

Logical OR

|

Left

Conditional AND

&&

Left

Conditional OR

||

Left

Conditional

?:

Right

Assignment

=

*=

/=

%=

+=

-= |=

=

&=

^=

Right

When an operand occurs between two operators with the same precedence, the associability of the operators controls the order in which the operations are performed: ‰

Except for the assignment operators, all binary operators are left-associative, meaning that operations are performed from left to right. For example, x + y + z is evaluated as (x + y) + z.

‰

The assignment operators and the conditional operator (?:) are right-associative, meaning that operations are performed from right to left. For example, x = y = z is evaluated as x = (y = z).

Precedence and associability can be controlled using parentheses. For example, x + y * z first multiplies y by z and then adds the result to x, but (x + y) * z first adds x and y and then multiplies the result by z.

Page 36 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Overloadable Operators: C# allows user-defined types to overload operators by defining static member functions using the operator keyword. Not all operators can be overloaded, however, and others have restrictions, as listed in this table: S.No

Operators

Overloadability

1

+, -, !, ~, ++, -, true, false

These unary operators can be overloaded.

2

+, -, *, /, %, &, |, ^,

These binary operators can be overloaded.

3

==, !=, , =

The comparison operators can be overloaded

4

&&, ||

The conditional logical operators cannot be overloaded, but they are evaluated using & and |, which can be overloaded.

5

[ ]

The array indexing operator cannot be overloaded, but you can define indexers.

6

()

The cast operator cannot be overloaded, but you can define new conversion operators (see explicit and implicit).

7

+=, -=, *=, /=, %=, &=, |=, ^=, =

Assignment operators cannot be overloaded, but +=, for example, is evaluated using +, which can be overloaded.

8

=, ., ?:, ->, new, is, sizeof, typeof

These operators cannot be overloaded.

Control Flow Control flow statements control the execution path of the program. The following table lists the Control flow statements: S.No

Category

C# keywords

1

Selection statements

if, else, switch, case

2

Iteration statements

do, for, foreach,, while

3

Jump statements

break, continue, goto, return, throw

Selection Statements--If else: The if statement selects a statement for execution based on the value of a Boolean expression. Example: // statements_if_else.cs // if-else example using System; class IfTest { static void Main()

Page 37 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

{ 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("Not an alphabetic character."); } } } Switch case: The switch statement is a control statement that handles multiple selections and enumerations by passing control to one of the case statements within its body Example: // statements_switch.cs using System; class SwitchTest { static void Main() { 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; switch(n) { case 1: cost += 25; break; case 2: cost += 25;

Page 38 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

goto case 1; case 3: cost += 50; goto 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."); } } Iteration Statements--do: The do statement executes a statement or a block of statements enclosed in {} repeatedly until a specified expression evaluates to false. Example: // statements_do.cs using System; public class TestDoWhile { public static void Main () { int x = 0; do { Console.WriteLine(x); x++; } while (x < 5); } } for: The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. The for loop is handy for iterating over arrays and for sequential processing. In the following example, the value of int i is written to the console and i is incremented each time through the loop by 1.

Page 39 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Example: // statements_for.cs // for loop using System; class ForLoopTest { static void Main() { for (int i = 1; i compile.out"; psi.Arguments = String.Format(compileString, fileName); psi.WindowStyle = ProcessWindowStyle.Minimized; Process proc = Process.Start(psi); proc.WaitForExit( ); // wait at most 2 seconds // Open the file, and get a

Page 168 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

// pointer to the method info Assembly a = Assembly.LoadFrom(fileName + ".dll"); theClass = a.CreateInstance(className); theType = a.GetType(className); } //reflect the type and invoke the method GenerateCode(theType, theClass); // with the reference to the dynamically // created class you can invoke the method object[] arguments = new object[0]; object retVal = theType.InvokeMember("Hello", BindingFlags.Default | BindingFlags.InvokeMethod, null, theClass, arguments);

Summary ‰

Reflection is the mechanism of discovering class information solely at run time.

‰

Using Reflection, you can obtain class and type information, member information.

Test Your Understanding 1. What are the uses of Reflection? 2. What is Reflection?

Page 169 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Session 42: Reflection and Serialization Learning Objectives After completing this session, you will able to: ‰

Describe overview of Serialization

‰

Identify the types of Serialization

Overview Serialization is a process of converting an object into a stream of data so that it can be is easily transmittable over the network or can be continued in a persistent storage location. This storage location can be a physical file, database or ASP.NET Cache. Serialization is the technology that enables an object to be converted into a linear stream of data that can be easily passed across process boundaries and machines. This stream of data needs to be in a format that can be understood by both ends of a communication channel so that the object can be serialized and reconstructed easily. Serialization is used by Remoting, Web Services SOAP for transmitting data between a server and a client. The Remoting technology of .NET makes use of serialization to pass objects by value from one application domain to another.

What is Serialization and De-serialization? Serialization is the process of saving the state of an object in a persistent storage media by converting the object to a linear stream of bytes. The object can be persisted to a file, a database or even in the memory. The reverse process of serialization is known as de-serialization and enables us to re-construct the object from the previously serialized instance of the same in the persistent or non-persistent storage media. Serialization in .NET is provided by the System.Runtime.Serialization namespace. This namespace contains an interface called IFormatter which in turn contains the methods Serialize and De-serialize that can be used to save and load data to and from a stream. In order to implement serialization in .NET, you basically require a stream and a formatter. While the stream acts as a container for the serialized objects, the formatter is used to serialize these objects onto the stream. The basic advantage of serialization is the ability of an object to be serialized into a persistent or a non-persistent storage media and then reconstructing the same object if required at a later point of time by de-serializing the object. Remoting and Web Services depend heavily on Serialization and De-serialization.

Page 170 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Types of Serialization Serialization can be of the following types: ‰

Binary Serialization

‰

SOAP Serialization

‰

XML Serialization

‰

Custom Serialization

Binary Serialization: Binary serialization is a mechanism which writes the data to the output stream such that it can be used to re-construct the object automatically. The term binary in its name implies that the necessary information that is required to create an exact binary copy of the object is saved onto the storage media. public void BinarySerialize(string filename, Employee emp) { FileStream fileStreamObject; try { fileStreamObject = new FileStream(filename, FileMode.Create); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(fileStreamObject, emp); } finally { fileStreamObject.Close(); } }

Page 171 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Advantages and Disadvantages of Binary Serialization: The following are the major advantages of using Binary Serialization: ‰

The object can be de-serialized from the same data you serialized it to.

‰

Enhanced performance as it is faster and even more powerful

‰

Provides support for complex objects, read only properties and even circular references.

The following is the drawback of using Binary Serialization ‰

Not easily portable to another platform.

Soap Serialization: The SOAP protocol is ideal for communicating between applications that use heterogeneous architectures. In order to use SOAP serialization in .NET we have to add a reference to System.Runtime.Serialization.Formatters.Soap in the application. The basic advantage of SOAP serialization is portability. The SoapFormatter serializes objects into SOAP messages or parses SOAP messages and extracts serialized objects from the message. public void SOAPSerialize(string filename,Employee employeeObject) { FileStream fileStreamObject = new FileStream(filename, FileMode.Create); SoapFormatter soapFormatter = new SoapFormatter(); soapFormatter.Serialize(fileStreamObject, employeeObject); fileStreamObject.Close(); } XML Serialization: "XML serialization converts (serializes) the public fields and properties of an object or the parameters and returns values of methods, into an XML stream that conforms to a specific XML Schema definition language (XSD) document. XML serialization results in strongly typed classes with public properties and fields that are converted to a serial format (in this case, XML) for storage or transport. Because XML is an open standard, the XML stream can be processed by any application, as needed, regardless of platform." Implementing XML Serialization in .Net is quite simple. The basic class that we need to use is the XmlSerializer for both serialization and de-serialization. The Web Services use the SOAP protocol for communication and the return types and the parameters are all serialized using the XmlSerializer class. XML Serialization is however, much slower compared to Binary serialization. public void XMLSerialize(Employee emp, String filename) { XmlSerializer serializer = null; FileStream stream = null; try { serializer = new XmlSerializer(typeof(Employee)); stream = new FileStream(filename, FileMode.Create, FileAccess.Write); serializer.Serialize(stream, emp); } finally

Page 172 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

{ if (stream != null) stream.Close(); } } The advantages of XML Serialization are as follows: ‰

XML based

‰

Support for cross platforms

‰

Easily readable and editable

Custom Serialization: In some cases, the default serialization techniques provided by .NET may not be sufficient in real life. This is when we require implementing custom serialization. It is possible to implement custom serialization in .NET by implementing the ISerializable interface. This interface allows an object to take control of its own serialization and de-serialization process. It gives us a great deal of flexibility in the way we can save and restore objects. public class Employee: ISerializable { private int empCode; private string empName; protected Employee(SerializationInfo serializationInfo, StreamingContext streamingContext) { this.empCode = serializationInfo.GetInt32("empCode"); this.empName = serializationInfo.GetString("empName"); } public void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) { serializationInfo.AddValue("empCode", this.empCode); serializationInfo.AddValue("empName", this.empName); } }

Working with formatters: A formatter is used to determine the serialization format for objects. In other words, it is used to control the serialization of an object to and from a stream. They are the objects that are used to encode and serialize data into an appropriate format before they are transmitted over the network. They expose an interface called the IFormatter interface. IFormatter's significant methods are Serialize and De-serialize which perform the actual serialization and de-serialization.There are two formatter classes provided within .NET, the BinaryFormatter and the SoapFormatter. Both these classes extend the IFormatter interface.

Page 173 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

The Binary Formatter: The Binary formatter provides support for serialization using binary encoding. The BinaryFormater class is responsible for binary serialization and is used commonly in .NET's Remoting technology. This class is not appropriate when the data is supposed to be transmitted through a firewall. The SOAP Formatter: The SOAP formatter provides formatting that can be used to serialize objects using the SOAP protocol. It is used to create a Soap envelop and it uses an object graph to generate the result. It is responsible for serializing objects into SOAP messages or parsing the SOAP messages and extracting these serialized objects from the SOAP messages. SOAP formatters in .NET are widely used by the Web Services.

Advantages and disadvantages of serialization The following are the basic advantages of serialization: ‰

Facilitate the transportation of an object through a network

‰

Create a clone of an object

The primary disadvantages of serialization are: ‰

Resource overhead (both the CPU and the IO devices)

‰

Latency issues that are involved for transmitting the data over the network

‰

Serialization is quite slow.

‰

XML serialization is insecure, consumes a lot of space on the disk and it works on public members and public classes and not on the private or internal classes.

Summary ‰

.NET provides built-in object serialization services.

‰

Serialization will moves from field-level to object-level.

‰

You can generalize serialization to allow XML, SOAP, Binary formats and other future formats.

‰

Various types of Serialization are Binary Serialization, SOAP Serialization, XML Serialization, and Custom Serialization.

Test Your Understanding 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.

What is Serialization? What is Deserialization? What are the Types of serialization? What is a Binary Serialization? What are the advantages and disadvantages of using Binary Serialization? What is Soap Serialization? What is XML Serialization? What is Custom Serialization? What is Binary Formatter? What is Soap Formatter? What are the advantages and disadvantages of Serialization?

Page 174 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Session 45: .NET Interoperability Learning Objectives After completing this session, you will be able to: ‰

Work with Unmanaged Code

‰

Describe the Interoperability through Runtime wrappers

‰

Explain programming model comparison of .NET-COM interoperability

‰

Describe .NET Marshalling

Overview of .NET and COM interoperability The .NET framework is a natural progression from COM because the two models share many central themes, including component reuse and language neutrality. For backward compatibility, COM interop provides access to existing COM components without requiring that the original component be modified. We can incorporate COM components into a .NET Framework application by using COM interop tools to import the relevant COM types. Once imported, the COM types are ready to use. COM interop also introduces forward compatibility by enabling your COM clients to access managed code as easily as they access other COM objects. Again, COM interop provides the means to seamlessly export metadata in an assembly to a type library and registers the managed component as a traditional COM component. Both the import and export utilities produce results consistent with COM specifications. At run time, the common language runtime marshals data between COM objects and managed objects as needed.

Interoperability through Runtime wrappers The common language runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW). Although the RCW appears to be an ordinary object to .NET clients, its primary function is to marshal calls between a .NET client and a COM object. The runtime creates exactly one RCW for each COM object, regardless of the number of references that exist on that object. As the following illustration shows, any number of managed clients can hold a reference to the COM objects that expose INew and INewer interfaces. The runtime maintains a single RCW for each object.

Page 175 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Accessing COM objects through the runtime callable wrapper

Using metadata derived from a type library, the runtime creates both the COM object being called and a wrapper for that object. Each RCW maintains a cache of interface pointers on the COM object it wraps and releases its reference on the COM object when the RCW is no longer needed. The runtime performs garbage collection on the RCW. Among other activities, the RCW marshals data between managed and unmanaged code, on behalf of the wrapped object. Specifically, the RCW provides marshaling for method arguments and method return values whenever the client and server have different representations of the data passed between them. The standard wrapper enforces built-in marshaling rules. For example, when a .NET client passes a String type as part of an argument to an unmanaged object, the wrapper converts the string to a BSTR type. Should the COM object return a BSTR to its managed caller, the caller receives a String. Both the client and the server send and receive data that is familiar to them. Other types require no conversion. For instance, a standard wrapper will always pass a 4-byte integer between managed and unmanaged code without converting the type.

Programming Model comparison of .NET-COM interoperability The following table compares the .NET and COM based component programming models. .NET COM Object based communication

Interface based communication

Garbage Collector to manage memory

Reference count will be used to manage memory

Type Standard objects

Binary Standard objects

Objects are created by normal new operator

Objects are created by coCreateInstance

Exceptions will be returned

HRESULT will be returned

Object info resides in assembly files

Object info resides in Type library

Before the application starts to communicate, there are some technical constraints associated with this. When an object is transmitted to a receiver which is in a separate machine/process (managed/unmanaged) space, the object may need to undergo a transformation according to the native type to make it suitable for use by the recipient. That is the object will be converted into a recipient readable form. This process of converting an object between types when sending it across contexts is known as marshaling.

Page 176 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

.NET Marshalling .NET runtime automatically generates code to translate calls between managed code and unmanaged code. While transferring calls between these two codes, .NET handles the data type conversion also. This technique of automatically binding with the server data type to the client data type is known as marshalling. Marshaling occurs between managed heap and unmanaged heap. For example, Fig.4 shows a call from the .NET client to a COM component. This sample call passes a .NET string from the client. The RCW converts this .NET data type into the COM compatible data type. In this case COM compatible data type is BSTR. Thus the RCW converts the .NET string into COM compatible BSTR. This BSTR will be passed to the object and the required calls will be made. The results will be returned to back to the RCW. The RCW converts this COM compatible result to .NET native data type.

Fig.4 Sample diagram for marshalling Logically the marshalling can be classified into 2 types. ‰

Interop marshalling

‰

COM marshalling

If a call occurs between managed code and unmanaged code with in the same apartment, Interop marshaler will play the role. It marshals data between managed code and unmanaged code. In some scenarios COM component may be running in different apartment threads. In those cases that is, calling between managed code and unmanaged code in different apartments or process, both Interop marshaler and COM marshaler are involved.

Interop marshaler When the server object is created in the same apartment of client, all data marshaling is handled by Interop marshaling.

Page 177 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

COM Marshaler COM marshaling involved whenever the calls between managed code and unmanaged code are in different apartments. For example, when a .NET client (with the default apartment settings) communicates with a COM component (whichever developed in VB6.0), the communication occurs through proxy and stub because both the objects will be running in different apartment threads. (The default apartment settings of .NET objects are STA and the components which are developed by VB6.0 are STA). Between these two different apartments COM marshaling will occurs and within the apartment Interop marshaling will occurs. Fig.6 shows this kind of marshaling. This kind of different apartment communication will impact the performance. The apartment settings of the managed client can be changed by changing the STAThreadAttribute / MTAThreadAttribute / Thread.ApartmentState property. Both the codes can run in a same apartment, by making the managed code’s thread to STA. (If the COM component is set as MTA, then cross marshaling will occurs.)

In the earlier scenario, the call with in different apartments will occur by COM marshaling and the call between managed and unmanaged code will occur by Interop marshaling.

Summary ‰

Com interoperability: COM interop provides the means to seamlessly export metadata in an assembly to a type library and registers the managed component as a traditional COM component.

‰

Interoperability through Runtime wrappers: The common language runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW). Although the RCW appears to be an ordinary object to .NET clients, its primary function is to marshal calls between a .NET client and a COM object.

‰

.NET Marshalling: Automatically binding with the server data type to the client data type is known as marshalling. Marshaling occurs between managed heap and unmanaged heap.

‰

Marshalling can be classified into 2 types: o o

Interop marshalling COM marshalling

‰

When the server object is created in the same apartment of client, all data marshaling is handled by Interop marshaling.

‰

COM marshaling involved whenever the calls between managed code and unmanaged code are in different apartments

Page 178 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Test your Understanding 1. 2. 3. 4. 5. 6. 7.

What is interoperability? What is unmanaged code with examples? Differentiate between managed code and unmanaged code? What is RCW? Differentiate between RCW and CCW? What is marshalling? What are the types of marshalling?

Page 179 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Session 47: Remoting Learning Objectives After completing this session, you will be able to: ‰

Explain the .NET Remoting Basics and Concepts

‰

Describe the .NET Remoting Architecture

.NET Remoting basics .NET remoting enables you to build widely distributed applications easily, whether the application components are all on one computer or spread out across the entire world. You can build client applications that use objects in other processes on the same computer or on any other computer that is reachable over its network. You can also use .NET remoting to communicate with other application domains in the same process. .NET remoting provides an abstract approach to interprocess communication that separates the remotable object from a specific client or server application domain and from a specific mechanism of communication. As a result, it is flexible and easily customizable. You can replace one communication protocol with another or one serialization format with another without recompiling the client or the server. In addition, the remoting system assumes no particular application model. You can communicate from a Web application, a console application, a Windows Service – from almost anything you want to use. Remoting servers can also be any type of application domain. Any application can host remoting objects and provide its services to any client on its computer or network. To use .NET remoting to build an application in which two components communicate directly across an application domain boundary, you need to build only the following: ‰

A remotable object.

‰

A host application domain to listen for requests for that object.

‰

A client application domain that makes requests for that object.

.NET Remoting concepts Building an application that uses .NET Framework remoting to communicate across application domain boundaries is very straightforward. You must have an implementation of a remotable type, a listening or host application domain, a client or calling application domain, and you must configure the remoting system in each application domain to use remote activation for the remotable type. This process applies no matter how complex your remoting scenario becomes.

Page 180 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Building a Remotable Type: To enable objects in other application domains to use an instance of your class, your class must inherit from MarshalByRefObject. The following procedure describes how to create a simple object that can be created and invoked from objects executing in another application domain. 1. Define a class that derives from the MarshalByRefObject class public class CustomRemotableException : RemotingException, ISerializable { ……….} 2. Implement the methods and properties for that class as you would for a non-remotable type. private string StringValue = "This is the RemotableType."; public string StringMethod(){ return StringVale; } 3. Save the class as Filename.language-extension (or use another file name of your choice, where the language extension is the language you want to compile), and at the command prompt in the directory in which you saved the file, type the following command: csc /noconfig /t:library RemotableType.cs

Building a Host Application: Using a configuration file enables you to change the remoting configuration without recompiling your executable, among other things. For details on the configuration of the .NET remoting infrastructure: 1. Create a configuration file for the remote class. The host application must be able to find the configuration file to load the configuration for the remote class, and therefore, the configuration file should be saved in the same directory as the host application, or it will not be found and an exception will be thrown. The following code shows the Listener.exe.config configuration file for a host application domain.

Page 181 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

2. Import the System.Runtime.Remoting namespace using System; using System.Runtime.Remoting; Load the configuration file that configures the remote class. public class Listener{ public static void Main(){ RemotingConfiguration.Configure("Listener.exe.config"); } } 3. Compile this class into a host or listener executable using the command-line tools that ship with the .NET Framework SDK, save it as Listener.language-extension (or use another file name of your choice, where the language extension is the language you want to compile). Save the file in the same directory in which you saved the RemotableType. At the command prompt in that directory, type the following command: csc /noconfig /r:RemotableType.dll Listener.cs

Build a Client Application: Application must register itself as a client for that remote object, and then invoke it as though it were within the client's application domain. The .NET remoting system will intercept your client calls, forward them to the remote object, and return the results to your client. The following code procedure describes how to build a simple remoting client. 1. Import the System.Runtime.Remoting namespace 2. Create a client configuration file so that the client application can locate the remote object, and save the file in the same folder as the client application. For example the following configuration file tells the remoting system that the type information for the RemotableType remote object can be found in the RemotableType assembly, and that the client should attempt to create and use a RemotableType object located at http://localhost:8989/RemotableType.rem.

Page 182 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

3. Save the client application as Client.language-extension. Save the file in the same directory in which you saved a copy of the RemotableType. 4. Compile client application or calling executable using the command-line tools that ship with the .NET Framework SDK. For example, to compile the client application Client.language-extension, at the command prompt change directory to the folder where the client application has been saved and type the following command: csc /noconfig /r:RemotableType.dll Client.cs

.NET Remoting Architecture Using object references to communicate between server objects and clients is the heart of remoting. The remoting architecture, however, provides the programmer with an even simpler procedure. If we configure the client properly, we need only create a new instance of the remote object using new (or the instance creation function from your managed programming language). Your client receives a reference to the server object, and you can then call its methods as though the object were in your process rather than running on a separate computer. The remoting system uses proxy objects to create the impression that the server object is in the client's process. Proxies are stand-in objects that present themselves as some other object. When your client creates an instance of the remote type, the remoting infrastructure creates a proxy object that looks exactly like the remote type to your client. Client calls a method on that proxy, and the remoting system receives the call, routes it to the server process, invokes the server object, and returns the return value to the client proxy, which returns the result to the client. Remote calls must be conveyed in some way between the client and the server process. If you were building a remoting system yourself, you might start by learning network programming and a wide array of protocols and serialization format specifications. In the .NET remoting system, the combination of underlying technologies required to open a network connection and use a particular protocol to send the bytes to the receiving application are represented as a transport channel. A channel is a type that takes a stream of data, creates a package according to a particular network protocol, and sends the package to another computer. Some channels can only receive information, others can only send information, and still others, such as the default TcpChannel and HttpChannel classes, can be used in either direction.

Page 183 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Suppose you have an application running on one computer, and you want to use the functionality exposed by a type that is stored on another computer. The following illustration shows the general remoting process.

If both sides of the relationship are configured properly, a client merely creates a new instance of the server class. The remoting system creates a proxy object that represents the class and returns to the client object a reference to the proxy. When a client calls a method, the remoting infrastructure handles the call, checks the type information, and sends the call over the channel to the server process. A listening channel picks up the request and forwards it to the server remoting system, which locates (or creates, if necessary) and calls the requested object. The process is then reversed, as the server remoting system bundles the response into a message that the server channel sends to the client channel. Finally, the client remoting system returns the result of the call to the client object through the proxy. Very little actual code is required to make this work, but some thought should be given to the design and the configuration of the relationship. The code can be absolutely correct and yet fail because a URL or port number is incorrect.

Summary ‰

.NET remoting is an enabler for application communication.

‰

In .NET when an application is loaded in memory a process is created and within process an application domain is created.

‰

The Channels connects the server application domain and the client application domain.

‰

The proxy looks and feels like the real object, however it merely holds a reference to the remotable object.

Page 184 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Test your Understanding 1. 2. 3. 4. 5. 6.

What is Remoting? What is the advantage of using remoting? What is Application Domain? Describe channels and proxy? What are the basic rules which are applicable for Remoting? What are the object modes for server activation?

Page 185 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Session 48: Remoting Learning Objectives After completing this session, you will be able to: ‰

Develop .NET Remoting service

‰

Develop and configure Remoting Server and Client

Remoting Application: .NET remoting enables you to build widely distributed applications easily, whether the application components are all on one computer or spread out across the entire world. You can build client applications that use objects in other processes on the same computer or on any other computer that is reachable over its network. You can also use .NET remoting to communicate with other application domains in the same process. .NET remoting provides an abstract approach to interprocess communication that separates the remotable object from a specific client or server application domain and from a specific mechanism of communication. As a result, it is flexible and easily customizable. You can replace one communication protocol with another or one serialization format with another without recompiling the client or the server. In addition, the remoting system assumes no particular application model. You can communicate from a Web application, a console application, a Windows Service – from almost anything you want to use. Remoting servers can also be any type of application domain. Any application can host remoting objects and provide its services to any client on its computer or network. To use .NET remoting to build an application in which two components communicate directly across an application domain boundary, you need to build only the following: ‰

A remotable object.

‰

A host application domain to listen for requests for that object.

‰

A client application domain that makes requests for that object.

Build a Remotable Type To enable objects in other application domains to use an instance of your class, your class must inherit from MarshalByRefObject. using System; public class RemotableType : MarshalByRefObject { private string StringValue = "This is the RemotableType."; public string StringMethod() { return StringValue; } }

Page 186 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Host Application By itself, the RemotableType class defined in the How To: Build a Remotable Type topic is not special. To enable objects in other application domains to create instances of this object remotely, you must build a host or listener application to do two things: ‰

Choose and register a channel, which is an object that handles the networking protocols and serialization formats on your behalf.

‰

Register your type with the .NET remoting system so that it can use your channel to listen for requests for your type.

The .NET Framework includes two default channels, HttpChannel (which uses SOAP formatting) and TcpChannel (which uses binary formatting). HttpChannel is a good channel to start with because in some scenarios, it can be used through firewalls without opening a port, and it supports standard security and authentication protocols. For more information about choosing channels that suit your scenario. Refer Channels. You can build listener applications using any type of application domain — a Windows Forms application, an ASP.NET Web application, a console application, a Windows Service (also known as a Windows NT Service), or any other managed application domain. Because remote configuration is done on a per-application-domain basis, the application domain must be running to listen for requests. Configuration can be done programmatically or by using an application or machine configuration file. The remoting system uses the information in this file to listen for and route remote requests to an instance of a remotable type.

Build a Hosting Application Create a configuration file for the remote class. The host application must be able to find the configuration file to load the configuration for the remote class, and therefore, the configuration file should be saved in the same directory as the host application, or it will not be found and an exception will be thrown. The following code shows the Listener.exe.config configuration file for a host application domain.

Page 187 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Load the configuration file that configures the remote class: // Listener.cs using System; using System.Runtime.Remoting; public class Listener{ public static void Main(){ RemotingConfiguration.Configure("Listener.exe.config"); Console.WriteLine("Listening for requests. Press Enter to exit..."); Console.ReadLine(); } }

Build a Client Application To build a client of the remote type, your application must register itself as a client for that remote object, and then invoke it as though it were within the client's application domain. The .NET remoting system will intercept your client calls, forward them to the remote object, and return the results to your client. The following code procedure describes how to build a simple remoting client. Create a client configuration file so that the client application can locate the remote object, and save the file in the same folder as the client application. For example the following configuration file tells the remoting system that the type information for the RemotableType remote object can be found in the RemotableType assembly, and that the client should attempt to create and use a RemotableType object located at http://localhost:8989/RemotableType.rem. // Client.cs using System; using System.Runtime.Remoting; public class Client { public static void Main()

Page 188 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

{ RemotingConfiguration.Configure("Client.exe.config"); RemotableType remoteObject = new RemotableType(); Console.WriteLine(remoteObject.StringMethod()); } }

Remoting Task List .NET remoting is one of several ways to establish communication between application domains using the .NET Framework. You must decide which features your application requires and consider the resources you have at your disposal before choosing a particular development model for your distributed application. For guidance, see Choosing Communication Options in .NET . The following task lists describe the fundamental steps required to build a basic .NET remoting application.

Host Tasks The following steps are required to publish any service for use from outside your application domain: 1. Design your service. a. Choose a host application domain. b. Choose an activation model. c. Choose a channel and port. d. Decide how the client will obtain your service's metadata. 2. Implement your host application domain. Remoting hosts might be Windows Services, console applications, Windows Forms applications, Internet Information Services (IIS) processes, or ASP.NET applications. Requirements for each type of application vary, so you should read the documentation describing how to build the type of application you want to use. For more information, see Windows-based Applications or ASP.NET Web Applications. In the host, configure the remoting system for activation mode and other information, such as application name and endpoint. If you want to programmatically configure the system, you do not need to use a configuration file. If you use a configuration file, you must load that file into the system by calling RemotingConfiguration.Configure. 3. In the host, create the appropriate channel and register it with the system by calling ChannelServices.RegisterChannel. If you use a configuration file, then you must load that file into the system by calling RemotingConfiguration.Configure. 4. The host cannot run without the published class, but the way you build your host environment with your service's implementation depends on how you want to share the public interface of your service. a) If you are implementing an XML Web service (using an HttpChannel with the default SOAP serialization), your client can obtain the information in three ways: i. Using the Soapsuds tool (Soapsuds.exe) to extract the information from the endpoint. ii. Downloading an assembly that contains the metadata. iii. Downloading the source code for an interface.

Page 189 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

b) If you are implementing another type of service (for example, using a TcpChannelobject) your client can obtain the information in two ways: iv. Downloading an assembly that contains the metadata. v. Downloading the source code for an interface. In either case, the way you package your service in your own hosting application domain will depend on how you want to publish the metadata necessary for others to consume the service.

Client Tasks The following basic steps are required to consume any service for use from outside your application domain: 1. Design your client. a) Choose a client application domain. b) Determine the activation mode and either the client activation URL or the wellknown object URL of the remote type. c) Consider whether you need to register a channel and port. d) Obtain the remote type's metadata. 2. Implement your client application domain. Remoting hosts might be Windows Services, console applications, Windows Forms applications, Internet Information Services (IIS) processes, or ASP.NET applications. Requirements for each type of application vary, so you should read the documentation describing how to build the type of application you want to use. For more information, refer Windows Applicationsor ASP.NET Web Applications. 3. Configure the client remoting system with the activation mode and other type information, such as application name and object Uniform Resource Identifier (URI). If you want to programmatically configure the system, you do not need to use a configuration file. If you use a configuration file, you must load that file into the system by calling RemotingConfiguration.Configure. 4. Create the appropriate channel and register it with the system by calling ChannelServices.RegisterChannel. If you use a configuration file, you must load that file into the system by calling RemotingConfiguration.Configure.

Summary ‰

Server activation is used when remote objects are not required to maintain any state between method calls.

‰

Single Call objects service one and only one request coming in.

‰

These objects service multiple clients and hence share data by storing state information between client invocations.

‰

Client activation objects are server-side objects that are activated upon request from the client.

Test your Understanding 1. 2. 3. 4.

How do you make an object remotable? What is the formatting type used by HTTP channel? What is the formatting type used by TCP channel? What is the namespace used for Remoting?

Page 190 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Session 50: Garbage Collection and Memory Management Learning Objectives After completing this session, you will be able to: ‰

Explain Memory Management

‰

Define Disposing and Destructor

‰

Explain Garbage Collection

Memory Management Automatic memory management is one of the services that the common language runtime provides during Managed Execution. The common language runtime's garbage collector manages the allocation and release of memory for an application. For developers, this means that you do not have to write code to perform memory management tasks when you develop managed applications. Automatic memory management can eliminate common problems, such as forgetting to free an object and causing a memory leak, or attempting to access memory for an object that has already been freed.

Allocating Memory When you initialize a new process, the runtime reserves a contiguous region of address space for the process. This reserved address space is called the managed heap. The managed heap maintains a pointer to the address where the next object in the heap will be allocated. Initially, this pointer is set to the managed heap's base address. All reference types are allocated on the managed heap. When an application creates the first reference type, memory is allocated for the type at the base address of the managed heap. When the application creates the next object, the garbage collector allocates memory for it in the address space immediately following the first object. As long as address space is available, the garbage collector continues to allocate space for new objects in this manner. Allocating memory from the managed heap is faster than unmanaged memory allocation. Because the runtime allocates memory for an object by adding a value to a pointer, it is almost as fast as allocating memory from the stack. In addition, because new objects that are allocated consecutively are stored contiguously in the managed heap, an application can access the objects very quickly.

Releasing Memory The garbage collector's optimizing engine determines the best time to perform a collection based on the allocations being made. When the garbage collector performs a collection, it releases the memory for objects that are no longer being used by the application. It determines which objects are no longer being used by examining the application's roots. Every application has a set of roots. Each root either refers to an object on the managed heap or is set to null. An application's roots include global and static object pointers, local variables and reference object parameters on a thread's stack, and CPU registers. The garbage collector has access to the list of active roots that the just-in-time (JIT) compiler and the runtime maintain. Using this list, it examines an application's

Page 191 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

roots, and in the process creates a graph that contains all the objects that are reachable from the roots. Objects that are not in the graph are unreachable from the application's roots. The garbage collector considers unreachable objects garbage and will release the memory allocated for them. During a collection, the garbage collector examines the managed heap, looking for the blocks of address space occupied by unreachable objects. As it discovers each unreachable object, it uses a memory-copying function to compact the reachable objects in memory, freeing up the blocks of address spaces allocated to unreachable objects. Once the memory for the reachable objects has been compacted, the garbage collector makes the necessary pointer corrections so that the application's roots point to the objects in their new locations. It also positions the managed heap's pointer after the last reachable object. Note that memory is compacted only if a collection discovers a significant number of unreachable objects. If all the objects in the managed heap survive a collection, then there is no need for memory compaction. To improve performance, the runtime allocates memory for large objects in a separate heap. The garbage collector automatically releases the memory for large objects. However, to avoid moving large objects in memory, this memory is not compacted.

Generations and Performance To optimize the performance of the garbage collector, the managed heap is divided into three generations: 0, 1, and 2. The runtime's garbage collection algorithm is based on several generalizations that the computer software industry has discovered to be true by experimenting with garbage collection schemes. First, it is faster to compact the memory for a portion of the managed heap than for the entire managed heap. Secondly, newer objects will have shorter lifetimes and older objects will have longer lifetimes. Lastly, newer objects tend to be related to each other and accessed by the application around the same time. The runtime's garbage collector stores new objects in generation 0. Objects created early in the application's lifetime that survive collections are promoted and stored in generations 1 and 2. The process of object promotion is described later in this topic. Because it is faster to compact a portion of the managed heap than the entire heap, this scheme allows the garbage collector to release the memory in a specific generation rather than release the memory for the entire managed heap each time it performs a collection. In reality, the garbage collector performs a collection when generation 0 is full. If an application attempts to create a new object when generation 0 is full, the garbage collector discovers that there is no address space remaining in generation 0 to allocate for the object. The garbage collector performs a collection in an attempt to free address space in generation 0 for the object. The garbage collector starts by examining the objects in generation 0 rather than all objects in the managed heap. This is the most efficient approach, because new objects tend to have short lifetimes, and it is expected that many of the objects in generation 0 will no longer be in use by the application when a collection is performed. In addition, a collection of generation 0 alone often reclaims enough memory to allow the application to continue creating new objects.

Page 192 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

After the garbage collector performs a collection of generation 0, it compacts the memory for the reachable objects as explained in Releasing Memory earlier in this topic. The garbage collector then promotes these objects and considers this portion of the managed heap generation 1. Because objects that survive collections tend to have longer lifetimes, it makes sense to promote them to a higher generation. As a result, the garbage collector does not have to reexamine the objects in generations 1 and 2 each time it performs a collection of generation 0. After the garbage collector performs its first collection of generation 0 and promotes the reachable objects to generation 1, it considers the remainder of the managed heap generation 0. It continues to allocate memory for new objects in generation 0 until generation 0 is full and it is necessary to perform another collection. At this point, the garbage collector's optimizing engine determines whether it is necessary to examine the objects in older generations. For example, if a collection of generation 0 does not reclaim enough memory for the application to successfully complete its attempt to create a new object, the garbage collector can perform a collection of generation 1, then generation 0. If this does not reclaim enough memory, the garbage collector can perform a collection of generations 2, 1, and 0. After each collection, the garbage collector compacts the reachable objects in generation 0 and promotes them to generation 1. Objects in generation 1 that survive collections are promoted to generation 2. Because the garbage collector supports only three generations, objects in generation 2 that survive a collection remain in generation 2 until they are determined to be unreachable in a future collection.

Releasing Memory for Unmanaged Resources For the majority of the objects that your application creates, you can rely on the garbage collector to automatically perform the necessary memory management tasks. However, unmanaged resources require explicit cleanup. The most common type of unmanaged resource is an object that wraps an operating system resource, such as a file handle, window handle, or network connection. Although the garbage collector is able to track the lifetime of a managed object that encapsulates an unmanaged resource, it does not have specific knowledge about how to clean up the resource. When you create an object that encapsulates an unmanaged resource, it is recommended that you provide the necessary code to clean up the unmanaged resource in a public Dispose method. By providing a Dispose method, you enable users of your object to explicitly free its memory when they are finished with the object. When you use an object that encapsulates an unmanaged resource, you should be aware of Dispose and call it as necessary.

Garbage Collection: The .NET Framework's garbage collector manages the allocation and release of memory for your application. Each time you use the new operator to create an object, the runtime allocates memory for the object from the managed heap. As long as address space is available in the managed heap, the runtime continues to allocate space for new objects. However, memory is not infinite. Eventually the garbage collector must perform a collection in order to free some memory. The garbage collector's optimizing engine determines the best time to perform a collection, based upon the allocations being made. When the garbage collector performs a collection, it checks for objects in the managed heap that are no longer being used by the application and performs the necessary operations to reclaim their memory. For the majority of the objects that your application creates, you can rely on the .NET Framework's garbage collector to implicitly perform all the necessary memory management tasks. However, when you create objects that encapsulate unmanaged resources, you must explicitly release the unmanaged resources when you are finished using them in your application. The most common

Page 193 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

type of unmanaged resource is an object that wraps an operating system resource, such as a file, window, or network connection. Although the garbage collector is able to track the lifetime of an object that encapsulates an unmanaged resource, it does not have specific knowledge about how to clean up the resource. For these types of objects, the .NET Framework provides the Object.Finalize method, which allows an object to clean up its unmanaged resources properly when the garbage collector reclaims the memory used by the object. By default, the Finalize method does nothing. If you want the garbage collector to perform cleanup operations on your object before it reclaims the object's memory, you must override the Finalize method in your class. The garbage collector keeps track of objects that have Finalize methods, using an internal structure called the finalization queue. Each time your application creates an object that has a Finalize method, the garbage collector places an entry in the finalization queue that points to that object. The finalization queue contains entries for all the objects in the managed heap that need to have their finalization code called before the garbage collector can reclaim their memory. Implementing Finalize methods or destructors can have a negative impact on performance and you should avoid using them unnecessarily. Reclaiming the memory used by objects with Finalize methods requires at least two garbage collections. When the garbage collector performs a collection, it reclaims the memory for inaccessible objects without finalizers. At this time, it cannot collect the inaccessible objects that do have finalizers. Instead, it removes the entries for these objects from the finalization queue and places them in a list of objects marked as ready for finalization. Entries in this list point to the objects in the managed heap that are ready to have their finalization code called. The garbage collector calls the Finalize methods for the objects in this list and then removes the entries from the list. A future garbage collection will determine that the finalized objects are truly garbage because they are no longer pointed to by entries in the list of objects marked as ready for finalization. In this future garbage collection, the objects' memory is actually reclaimed.

Cleaning up Unmanaged Resources The users should be prevented from calling an object's Finalize method directly by limiting its scope to protected. In addition, you are strongly discouraged from calling a Finalize method for a class other than your base class directly from your application's code. To properly dispose of unmanaged resources, it is recommended that you implement a public Dispose or Close method that executes the necessary cleanup code for the object. The IDisposable interface provides the Dispose method for resource classes that implement the interface. Because it is public, users of your application can call the Dispose method directly to free memory used by unmanaged resources. When you properly implement a Dispose method, the Finalize method becomes a safeguard to clean up resources in the event that the Dispose method is not called.

Implementing a Dispose method A type's Dispose method should release all the resources that it owns. It should also release all resources owned by its base types by calling its parent type's Dispose method. The parent type's Dispose method should release all resources that it owns and in turn call its parent type's Dispose method, propagating this pattern through the hierarchy of base types. To help ensure that resources are always cleaned up appropriately, a Dispose method should be callable multiple times without throwing an exception.

Page 194 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

A Dispose method should call the GC.SuppressFinalize method for the object it is disposing. If the object is currently on the finalization queue, GC.SuppressFinalize prevents its Finalize method from being called. Remember that executing a Finalize method is costly to performance. If your Dispose method has already done the work to clean up the object, then it is not necessary for the garbage collector to call the object's Finalize method. The purpose of the following code example is to illustrate the recommended design pattern for implementing a Dispose method for classes that encapsulate unmanaged resources. This pattern is implemented throughout the .NET Framework. // Design pattern for the base class. // By implementing IDisposable, you are announcing that instances of this type allocate scarce resources. public class BaseResource: IDisposable { private IntPtr handle; private Component Components; // Track whether Dispose has been called. private bool disposed = false; // Implement IDisposable. // Do not make this method virtual. A derived class should not be able to override this method. public void Dispose() { Dispose(true); // Take yourself off the Finalization queue to prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } // Dispose(bool disposing) executes in two distinct scenarios. If disposing equals true, the method has been called directly or indirectly by a user's code. Managed and unmanaged resources can be disposed. If disposing equals false, the method has been called by the runtime from inside the finalizer and you should not reference other objects. Only unmanaged resources can be disposed. protected virtual void Dispose(bool disposing) { // Check to see if Dispose has already been called. if(!this.disposed) { // If disposing equals true, dispose all managed and unmanaged resources. if(disposing)

Page 195 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

{ // Dispose managed resources. Components.Dispose(); } // Release unmanaged resources. If disposing is false, only the following code is executed. CloseHandle(handle); handle = IntPtr.Zero; } disposed = true; } // Use C# destructor syntax for finalization code. This destructor will run only if the Dispose method does not get called. It gives your base class the opportunity to finalize. Do not provide destructors in types derived from this class. ~BaseResource() { // Do not re-create Dispose clean-up code here. Calling Dispose(false) is optimal in terms of readability and maintainability. Dispose(false); } // Allow your Dispose method to be called multiple times, but throw an exception if the object has been disposed. Whenever you do something with this class, check to see if it has been disposed. public void DoSomething() { if(this.disposed) { throw new ObjectDisposedException(); } } } // Design pattern for a derived class. public class MyResourceWrapper: BaseResource { private ManagedResource addedManaged; private NativeResource addedNative; private bool disposed = false; protected override void Dispose(bool disposing) { if(!this.disposed)

Page 196 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

{ try { if(disposing) { // Release the managed resources you added in this derived class here. addedManaged.Dispose(); } // Release the native unmanaged resources you added in this derived class here. CloseHandle(addedNative); this.disposed = true; } finally { // Call Dispose on your base class. base.Dispose(disposing); } } } }

Using Objects that Encapsulate Resources When you write code that uses an object that encapsulates a resource, you should make sure that the object's Dispose method gets called when you are finished using the object. You can do this with the C# using statement or by implementing a try/finally block in other languages that target the common language runtime.

C# Using Statement The C# programming language's using statement makes a call to the Dispose method more automatic, by simplifying the code that you must write to create and clean up an object. The using statement obtains one or more resources, executes the statements that you specify, and then disposes of the object. Note that the using statement is only useful for objects with a lifetime that does not extend beyond the method in which the objects are constructed. The following code example creates and cleans up an instance of the ResourceWrapper class, as illustrated in the C# example of implementing a Dispose method. class myApp { public static void Main() { using (ResourceWrapper r1 = new ResourceWrapper()) { // Do something with the object. r1.DoSomething(); }

Page 197 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

} } The preceding code, incorporating the using statement, is equivalent to the following. class myApp { public static void Main() { ResourceWrapper r1 = new ResourceWrapper(); try { // Do something with the object. r1.DoSomething(); } finally { // Check for a null resource. if (r1 != null) // Call the object's Dispose method. r1.Dispose(); } } }

Forcing a Garbage Collection The garbage collection GC class provides the GC.Collect method, which you can use to give your application some direct control over the garbage collector. In general, you should avoid calling any of the collect methods and allow the garbage collector to run independently. In most cases, the garbage collector is better at determining the best time to perform a collection. In certain rare situations, however, forcing a collection might improve your application's performance. It might be appropriate to use the GC.Collect method in a situation where there is a significant reduction in the amount of memory being used at a defined point in your application's code. For example, an application might use a document that references a significant number of unmanaged resources. When your application closes the document, you know definitively that the resources the document has been using are no longer needed. For performance reasons, it makes sense to release them all at once. For more information, see the GC.Collect Method. Before the garbage collector performs a collection, it suspends all currently executing threads. This can become a performance issue if you call GC.Collect more often than is necessary. You should also be careful not to place code that calls GC.Collect at a point in your program where users could call it frequently. This would defeat the optimizing engine in the garbage collector, which determines the best time to run a garbage collection.

Page 198 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

The following tables list the members exposed by the GC type. Public Properties: Name

Description

MaxGeneration Gets the maximum number of generations the system currently supports.

Public Methods: Name AddMemoryPressure

Collect

Description Informs the runtime of a large allocation of unmanaged memory that should be taken into account when scheduling garbage collection. Overloaded. Forces garbage collection.

CollectionCount

Returns the number of times garbage collection has occurred for the specified generation of objects.

Equals

Overloaded. Determines whether two Object instances are equal. (Inherited from Object.)

GetGeneration

Overloaded. Returns the current generation number of an object.

GetHashCode

Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)

GetTotalMemory

GetType KeepAlive

Retrieves the number of bytes currently thought to be allocated. A parameter indicates whether this method can wait a short interval before returning, to allow the system to collect garbage and finalize objects. Gets the Type of the current instance. (Inherited from Object.) References the specified object, making it ineligible for garbage collection from the start of the current routine to the point where this method is called.

ReferenceEquals

Determines whether the specified Object instances are the same instance. (Inherited from Object.)

RemoveMemoryPressure

Informs the runtime that unmanaged memory has been released and no longer needs to be taken into account when scheduling garbage collection.

ReRegisterForFinalize Requests that the system call the finalizer for the specified object, for which SuppressFinalize has previously been called.

Page 199 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Name SuppressFinalize

ToString

Description Requests that the system not call the finalizer for the specified object. Returns a String that represents the current Object. (Inherited from Object.)

WaitForPendingFinaliz Suspends the current thread until the thread processing the queue ers of finalizers has emptied that queue.

Summary ‰

Memory Management: Keeping track of memory used by the program and reclaim the memory space when they are no longer used.

‰

Disposing: It is the tasks associated with freeing, releasing or resetting unmanaged resources.

‰

Destructors: It is a member that implements the actions required to destruct an instance of a class.

‰

Garbage Collection: It is a process by which you can dynamically allocated storage is reclaimed during the execution of a program.

Test your Understanding 1. 2. 3. 4.

Which object implements Garbage Collection in .Net? Which method forces Garbage collection? How many generations are available in .Net? Where are objects created in the memory? a) Stack b) Heap 5. Which statement implements Dispose functionality automatically in C#?

Page 200 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Glossary Access modifiers: Language keywords used to specify the visibility of the methods and member variables declared within a class. The five access modifiers in the C# language are public, private, protected, internal, and protected internal. Application domain: The logical and physical boundary created around every .NET application by the CLR. The CLR can allow multiple .NET applications to be run in a single process by loading them into separate application domains. The CLR isolates each application domain from all other application domains and prevents the configuration, security, or stability of running .NET applications from affecting other applications. Objects can only be moved between application domains by the use of remoting. Application Manifest: The part of an application that provides information to describe the components that the application uses. Array: A collection of objects of the same type, all of which are referenced by a single identifier and an indexer. In the .NET Framework, all arrays inherits from the Array class that is located in the System namespace. Assembly: All of the files that comprise a .NET application, including the resource, security management, versioning, sharing, deployment information, and the actual MSIL code executed by the CLR. An assembly may appear as a single DLL or EXE file, or as multiple files, and is roughly the equivalent of a COM module. See assembly manifest, private assembly, shared assembly. Assembly cache: A reserved area of memory used to store the assemblies of a .NET applications running on a specific machine. See Global Assembly Cache. Assembly manifest: A detailed description of the contents of an assembly. A manifest contains metadata describing the name, version, types, and resources in the assembly, and the dependencies upon other assemblies. The manifest allows an assembly to be self-describing, easily deployed, and not bound to a particular system by storing information in the Windows registry. Assembly Registration Tool: A .NET programming tool (RegAsm.exe) used to register an assembly in the Windows registry. Registration is required if COM clients need to call managed methods residing in a .NET assembly. This tool can also be used to generate a registry (.reg) file containing the necessary registration information. Registration typically only occurs once when the assembly is installed. Base class: The parent class of a derived class. Classes may be used to create other classes. A class that is used to create (or derive) another class is called the base class or super class. See Derived Class, Inheritance.

Page 201 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Boxing; Conversion of a value type to a reference type object (that is, System.Object). Value types are stored in stack memory and must be converted (that is, boxed) to a new object in heap memory before they can be manipulated as objects. The methods, functions, and events of the new object are invoked to perform operations on the value (for example, converting an integer to a string). Boxing is implicitly performed by the CLR at runtime. Refer Unboxing. Callback Method: A method used to return the results of an asynchronous processing call. Typically, methods are called in a synchronous fashion, where the call does not return until the results (that is, the output or return value) of the call are available. An asynchronous method call returns prior to the results, and then sometime later a callback method is called to return the actual results. The callback method itself contains program statements that are executed in response to the reception of the results. It is also referred to as a callback function under the Win32 API. Refer Event. Casting: Conversion of a value from one type to another. Implicit casting is performed silently by the compiler when the casting would not cause any information to be lost (For example, converting a 16-bit integer to a 32-bit integer value). Explicit casting is coded by the programmer using the particular language's cast operator. This is necessary when the use of a value would cause a possible loss of data (For example, converting a 32-bit integer to a 16-bit integer value). Catching: To trap a program exception. See try/catch block. COM (Component Object Model): A software architecture developed by Microsoft to build component-based applications. COM objects are discrete components, each with a unique identity, which expose interfaces that allow applications and other components to access their features. COM objects are more versatile that Win32 DLLs because they are completely language independent, have built-in interprocess communications capability, and easily fit into an ObjectOriented program design. COM was first released in 1993 with OLE2, largely to replace the interprocess communication mechanism Dynamic Data Exchanged (DDE) used by the initial release of OLE. Refer COM+. COM+: The "next generation" of the COM and DCOM software architectures. COM+ (pronounced "COM plus") makes it easier to design and construct distributed, transactional, and componentbased applications using a multi-tiered architecture. COM+ also supports the use of many new services, such as Just-in-Time Activation, object pooling, and Microsoft Transaction Server (MTS) 2.0. The use of COM, DCOM, and COM+ in application design will eventually be entirely replaced by the Microsoft .NET Framework. COM Callable Wrapper (CCW): A metadata wrapper that allows COM components to access managed .NET objects. The CCW is generated at runtime when a COM client loads a .NET object. The .NET assembly must first be registered using the Assembly Registration Tool. Refer Runtime Callable Wrapper (RCW). Class: In .NET languages, classes are templates used for defining new types. Classes describe both the properties and behaviors of objects. Properties contain the data that are exposed by the class. Behaviors are the functionality of the object, and are defined by the public methods (also called member functions) and events of the class. Collectively, the public properties and methods of a class are known as the object interface. Classes themselves are not objects, but instead they are used to instantiate (that is, create) objects in memory. Refer structure.

Page 202 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Common Intermediate Language (CIL): The system-independent code generated by a .NET language compiler. CIL defines a file format for storing managed code as both program instructions and metadata in a single file. Either the ILASM assembler or JIT compiler is then used to convert CIL to native machine code. CIL is also referred to as Microsoft Intermediate Language (MSIL). Common Language Infrastructure (CLI): The .NET infrastructure that allows applications written in multiple programming languages to operate many different environments without the need to modify the program code. The CLI consists of a file format (PE), a common type system (CTS), an extensible metadata system, an intermediate language (CIL), a factored base class library (FCL), and access to the underlying operating system (Win32). The CLI is defined by the standard ECMA-335. Common Language Runtime (CLR): A runtime environment that manages the execution of .NET program code, and provides services such as memory and exception management, debugging and profiling, and security. The CLR is a major component of the .NET Framework, and provides much of its functionality by following the rules defined in the Common Type System. Also known as the Virtual Execution System (VES). Common Language Specification (CLS): A set of common conventions used to promote interoperability between programming languages and the .NET Framework. The CLS specifies a subset of the Common Type System and set of conventions that are adhered to by both programming language designers and framework class library authors. Common Type System (CTS): The .NET Framework specification which defines the rules of how the Common Language Runtime defines, declares, and manages types, regardless of the programming language. All .NET components must comply with the CTS specification. Constructor: A method that is automatically called when an object is created. The constructor is used to initialize the object and place it in a valid state (For example, setting the values of member variables). The constructor method always has the same identifier as the class in which it is defined. Refer Destructor. DCOM (Distributed Component Object Model): An extension of the Microsoft Component Object Model (COM) that allows COM components to communicate across network boundaries. Traditional COM components can only perform interprocess communication across process boundaries on the same machine. DCOM uses the Remote Procedure Call (RPC) mechanism to transparently send and receive information between COM components (that is, clients and servers) on the same network. DCOM was first made available in 1995 with the initial release of Windows NT 4. Delegate: A mechanism used to implement event handling in .NET Framework code. A class that needs to raise events must define one delegate per event. Types that use the class must implement one event handler method per event that must be processed. Delegates are often described as a managed version of a C++ function pointer. However, delegates can reference both instance and static (also called shared) methods, while function pointers can only reference static methods.

Page 203 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Derived class: A class that was created based on a previously existing class (that is, base class). A derived class inherits all of the member variables and methods of the base class it is derived from. It is also called a derived type. Destructor: In traditional Object Oriented Programming, a destructor is a class method that is called when an object goes out of scope. In .NET languages, the destructor method is instead called when the object is garbage collected by the CLR - which happens at some indeterminate time after an object goes out of scope. In C#, the destructor is actually a syntactic mapping to a Finalize method. Refer Constructor, Dispose. Dispose: A class-only method used to implement an explicit way to release the resources allocated by an object. The dispose method is actually in implementation of the IDisposable interface, and is typically called by the destructor or Finialize method of a class. Event: A notification by a program or operating system that "something has happened." An event may be fired (or raised) in response to the occurrence of a pre-defined action (for example, a window getting focus, a user clicking a button, a timer indicating a specific interval of time has passed, or a program starting up or shutting down). In response to an event, an event handler is called. Event Handler: A function or method containing program statements that are executed in response to an event. Refer Callback method. Exception: A signal that is generated when an unplanned or unexpected event occurs. Exceptions are typically caught by an exception handler and dealt with in an appropriate way. A fatal exception (also called a critical or catastrophic error) is an event that cannot be properly handled to allow the application - or the operating system - to continue running. Exception Handling: The process of trapping an exception and performing some sort of corrective procedure in response. Refer try/catch block. Finalize: A class-only method that is automatically called when an object is destroyed by the garbage collector. The Finalize method is primarily used to free up unmanaged resources allocated by the object before the object itself is removed from memory. A Finalize method is not needed when only managed resources are used by the object, which are automatically freed by the garbage collector. In C#, when a destructor is defined in a class it is mapped to a Finalize method. It is also called a finalizer. Refer Dispose. Finally block: A block of program statements that will be executed regardless if an exception is thrown or not. A finally block is typically associated with a try/catch block (although a catch block need not be present to use a finally block). This is useful for operations that must be performed regardless if an exception was thrown or not (For example, closing a file, writing to a database, deallocating unmanaged memory, and so on). Framework Class Library (FCL): The collective name for the thousands of classes that compose the .NET Framework. The services provided by the FCL include runtime core functionality (basic types and collections, file and network I/O, accessing system services, and so on.), interaction with

Page 204 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

databases, consuming and producing XML, and support for building Web-based (Web Form) and desktop-based (Windows Form) client applications, and SOAP-based XML Web services. Garbage Collection (GC): The process of implicitly reclaiming unused memory by the CLR. Stack values are collected when the stack frame they are declared within ends (For example, when a method returns). Heap objects are collected sometime after the final reference to them is destroyed. Global Assembly Cache (GAC): A reserved area of memory used to store the assemblies of all of the .NET applications running on a specific machine. The GAC is necessary for side-by-side execution and for the sharing of assemblies among multiple applications. To reside in the GAC, an assembly must be public (that is, a shared assembly) and have a strong name. Assemblies are added and removed from the GAC using the Global Assembly Cache Tool. Heap: An area of memory reserved for use by the CLR for a running programming. In .NET languages, reference types are allocated on the heap. Refer Stack Indexer: A CLR language feature that allows array-like access to the properties of an object using getter and setter methods and an index value. This construct is identical to operator[] in C++. Refer Property. Inheritance: The ability of a class to be created from another class. The new class, called a derived class or subclass, is an exact copy of the base class or superclass and may extend the functionality of the base class by both adding additional types and methods and overriding existing ones. Just In Time (JIT): The concept of only compiling units of code just as they are needed at runtime. The JIT compiler in the CLR compiles MSIL instructions to native machine code as a .NET application is executed. The compilation occurs as each method is called; the JIT-compiled code is cached in memory and is never recompiled more than once during the program's execution. Managed code: It is the code that is executed by the CLR. Managed code provides information (that is, metadata) to allow the CLR to locate methods encoded in assembly modules, store and retrieve security information, handle exceptions, and walk the program stack. Managed code can access both managed data and unmanaged data. MSIL (Microsoft Intermediate Language): The machine-independent language into which .NET applications are compiled using a high-level .NET language compiler (For example, C# and VB.NET). The MSIL output is then used as the input of the Just-In-Time (JIT) compiler, which compiles the MSIL instructions to machine language just prior to its execution. MSIL can also be converted to native machine object code using the Native Image Generator utility. Namespace: A logical grouping of the names (that is, identifiers) used within a program. A programmer defines multiple namespaces as a way to logically group identifiers based on their use. For example, System.Drawing and System.Windows are two namespaces containing each containing types used for different purposes. The name used for any identifier may only appear once in any namespace. A namespace only contains the name of a type and not the type itself. Also called name scope.

Page 205 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Native code: Machine-readable instructions that are created for a specific CPU architecture. Native code for a specific family of CPUs is not usable by a computer using different CPU architectures (c.f., Intel x86 and Sun UltraSPARC). It is also called object code and machine code. Native Image Generator: A .NET programming tool (Ngen.exe) used to compile a managed assembly to native machine code and install it in the local assembly cache. During execution the native image will be used each time the assembly is accessed rather than the MSIL assembly itself. If the native image is removed, the CLR reverts to using the original MSIL assembly by default. Native images are faster to load and execute than MSIL assemblies, which must be JustIn-Time (JIT) compiled by the CLR. Using Ngen to create a native image file is often referred to as pre-JITting, because it makes JIT-compiling the assembly unnecessary. Object: The instance of a class that is unique and self-describing. A class defines an object, and an object is the functional, realization of the class. Analogously, if a class is a cookie cutter then the cookies are the objects the cutter was used to create. Private assembly: An assembly that is used only by a single application. A private assembly will run only with the application with which it was built and deployed. References to the private assembly will only be resolved locally to the application directory it is installed in. Refer Shared assembly. Pointer: A variable that contains the address of a location in memory. The location is the starting point of an allocated object, such as an object or value type, or the element of an array. Reference types: A variable that stores a reference to data located elsewhere in memory rather than to the actual data itself. Reference types include array, class, delegate, and interface. Refer Value types, Pointer types. Reflection: A feature that allows an application to query its own metadata. Reflection (System.Reflection) allows an application to discover information about itself so that it may display this information to the user, modify its own behavior by using late-binding and dynamic invocation (that is, binding to and calling methods at runtime), or create new types at runtime (Reflection Emit). Remoting: A .NET technology that allows objects residing in different application domains to communicate. Objects in different application domains are said to be separated by a remoting boundary. Objects using remoting may be on the same computer, or on different computers connected by a network. Remoting is the .NET replacement for Distributed COM (DCOM). Runtime Callable Wrapper (RCW)L: A metadata wrapper that allows COM components to be called from .NET applications. For OLE automation interfaces, an RCW is a managed .NET assembly that is generated from the COM component's type library using the Type Library Importer tool. For non-OLE automation interfaces, a custom RCW must be written that manually maps the types exposed by the COM interface to .NET Framework-compatible types. Refer COM Callable Wrapper (CCW). Stack: An area of program memory used to store local program variables, method parameters, and return values. In .NET languages, value types are allocated on the stack. Refer Heap.

Page 206 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

Strong name: An assembly name that is globally unique among all .NET assemblies. A public key encryption scheme is used to create a digital signature to insure that the strong name is truly different than all other names created at anytime and anywhere in the known universe. The digital signature also makes it easy to encrypt the assembly, authenticate who created the assembly, and to validate that the assembly has not been corrupted or tampered with. Strong names are created using the Shared name utility. Try/Catch block: An exception handling mechanism in program code. A try block contains a set of program statements that may possibly throw an exception when executed. The associated catch block contains program statements that handle any exception that is thrown in the try block. Multiple catch blocks may be defined to catch specific exceptions (For example, divide by zero, overflow, and so on.). Refer Finally block. Unmanaged: An adjective generally applied to any code or data that is outside of the control of a runtime host environment. In .NET, any objects or resources not allocated and controlled by the CLR are considered unmanaged (For example, Windows handles and calls to the Win32 API). Unmanaged code: Any code that executes outside of the control of the .NET Common Language Runtime. Unmanaged code may perform unsafe operations, such as declare and operate on pointers, take the address of a variable, and perform conversions between pointers and integral types. Uses of unmanaged code include calling operating system APIs, interfacing to COM components, accessing unmanaged areas of memory, and writing performance-critical routines that are not encumbered by the overhead of the CLR. It is also called as unsafe code. Value types: A variable that stores actual data rather than a reference to data, which is stored elsewhere in memory. Simple value types include the integer, floating point number, decimal, character, and Boolean types. Value types have the minimal memory overhead and are the fastest to access. Refer Reference types, Pointer types. XML Schema: A description of the structure of an XML document. Schemas are written in XSD and support namespaces and data types. XPath (XML Path Language): A language that uses path expressions to specify the locations of structures and data within an XML document. XPath information is processed using XSLT or XPointer. See the document XML Path Language (XPath) Version 1.0.

Page 207 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

References

Websites ‰

Visual C# Developer Center: o

‰

http://msdn.microsoft.com/vcsharp/

.NET Framework Developer Center o

http://msdn.microsoft.com/netframework/

‰

MSDN Columns o http://msdn.microsoft.com/columns/

‰

MSDN Academic Alliance: o

http://www.msdnaa.net/

Books ‰

ECMA C# Language Specification.

‰

Professional C#, 2nd Edition. Simon Robinson. Wrox.

‰

Learning C#. Jesse Liberty. O'Reilly.

‰

Inside C#. Tom Archer. Microsoft Press.

‰

C# Essentials. Ben Albahari, Peter Drayton & Brad Merrill. O'Reilly.

Page 208 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - C#

STUDENT NOTES:

Page 209 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF