middle ware technologies

52
MIDDLE WARE TECHNOLOGIES B.TECH III YR II SEMESTER UNIT 3 PPT SLIDES TEXT BOOKS: 1.Client/Server programming with Java and CORBA Robert Orfali and Dan Harkey, John Wiley & Sons,SPD 2nd Edition 2. Java programming with CORBA 3rd Edition, G.Brose, A Vogel and K.Duddy, Wiley-dreamtech, India John wiley and sons

Upload: toki

Post on 07-Jan-2016

28 views

Category:

Documents


0 download

DESCRIPTION

MIDDLE WARE TECHNOLOGIES. B.TECH III YR II SEMESTER UNIT 3 PPT SLIDES TEXT BOOKS: 1. Client/Server programming with Java and CORBA Robert Orfali and Dan Harkey, John Wiley & Sons,SPD 2nd Edition - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: MIDDLE WARE TECHNOLOGIES

MIDDLE WARE TECHNOLOGIES

B.TECH III YR II SEMESTER

UNIT 3 PPT SLIDES

TEXT BOOKS:

1.Client/Server programming with Java and CORBA Robert Orfali and Dan Harkey, John Wiley & Sons,SPD 2nd Edition

2. Java programming with CORBA 3rd Edition, G.Brose, A Vogel and K.Duddy, Wiley-dreamtech, India John wiley and sons

Page 2: MIDDLE WARE TECHNOLOGIES

INDEX UNIT 3 PPT SLIDESS.NO. TOPIC LECTURE NO. PPTSLIDES

1. INTRODUCING C# AND .NET L14 L1. 1 TO L1.4 L15 L2.1 To L2.4

2. UNDERSTANDIG . NET L16 L3. 1 TO L3.4

L17 L4. 1 TO L4.4

3. OOP WITH C# L18 L5. 1 TO L5.4 L19 L6. 1 TO L6.6 4. CALL BACK INTERFACES L20 L7. 1 TO L7.65. DELEGATES, L21 L8. 1 TO L8.66.EVENTS L22 L9. 1 TO L9.67. REVISION L23 L10. 1 TO L10.6

Page 3: MIDDLE WARE TECHNOLOGIES

Lecture 1 slide 2

UNIT3 SYLLABUS

• Introduction C# and the NET Platform: Understanding. Net Assemblies; Object-Oriented Programming with C#; Callback Interfaces, Delegated, and Events

Page 4: MIDDLE WARE TECHNOLOGIES

Lecture 1 slide 1

Introducing c# and the .net platform

1. C/Win 32 API Programmer: • C is a very terse language – manual memory

management, ugly pointer arithmetic and ugly syntactical constructs; C is a structured language and lacks the benefits of O-O approach.

• Combined with the thousands of global functions and data types defined by the raw Win 32 API to an already formidable language, many buggy apps. float around today.

Page 5: MIDDLE WARE TECHNOLOGIES

Lecture 1 slide 2

Introducing c# and the .net platform

2. C++ / MFC Programmer:

• C++ is an O-O language built in top of C and at the mercy of the painful aspects – manual memory management, ugly operator arithmetic and ugly syntactical constructs.

• Microsoft Foundation Classes (MFC) wraps a “sane subset” of the raw Win32 API behind a no. of classes, magic macros and numerous code wizards (App Wizard, Class Wizard etc). C++ Programming remains a difficult and error-prone experience.

Page 6: MIDDLE WARE TECHNOLOGIES

Lecture 1 slide 3

Introducing c# and the .net platform

3. VB 6.0 Programmer:

• Ability to build complex user interfaces, code libraries (ex. COM servers) and data access logic with minimum fuss and bother. Also hides the complexities of the raw Win32 API from view, using a no. of integrated code wizards, intrinsic data types, classes and VB-centric functions.

• Downfall of VB – not a fully O-O language; but rather “Object-aware”. No “is-a” relationship between types (i.e. no inheritance ); no support for parameterized class construction; no support for multi-threaded apps.

Page 7: MIDDLE WARE TECHNOLOGIES

Lecture 1 slide 4

Introducing c# and the .net platform

4. Java/J2EE Programmer: • Completely O-O; Syntactic roots in C++; large no. of

predefined “Packages” containing various class and interface definitions. “100% pure Java” apps can be built complete with database connectivity, messaging support, Web-enabled front ends, and a rich user interface.

• Potential problem – little hope of language independence – Java used front-to-back during the development cycle. Also not appropriate for graphical or numerically intensive apps. (ex. 3D-Video game).

Page 8: MIDDLE WARE TECHNOLOGIES

Lecture 1 slide 5

Introducing c# and the .net platform

5. COM Programmer:

• Microsoft’s Component Object Model (COM) – architecture that enables reuse of binary code. COM server – language-independent. C++ Programs can build COM classes that can be used by VB; Delphi programmers can use COM classes built using C, etc. However, there is no support for inheritance.

• Another benefit of COM is location transparency . Using constructs such as app identifiers (APP IDs) stubs, proxies and the COM runtime environment, programmers can avoid the need to work with raw sockets, RPC calls, and other low-level details.

Page 9: MIDDLE WARE TECHNOLOGIES

Lecture 2lide 1

Introducing c# and the .net platform

5. COM Programmer:• COM is a dominant object model, but is

extremely complex under the hood. Active Template Library (ATL) eases the complexity somewhat.

• Fragile registration entries, numerous deployment related issues have to be contended with.

Page 10: MIDDLE WARE TECHNOLOGIES

Lecture 2 slide 2

Introducing c# and the .net platform6. Windows DNA Programmer: Building a

complete web app using classic Windows DNA (Distributed internet Architecture) is also very complex. Complexity is due to the fact that DNA requires the use of numerous technologies and languages such as ASP, HTML, XML, JavaScript, VBScript, COM+, ADO etc. Syntactically different, for ex., JavaScript has a syntax much like C, VBScript is a subset of VB. Each language and/or technology has its own type system – for ex., “int” in JavaScript is not the same as “int” in C, which is different from an “Integer” in VB.

Page 11: MIDDLE WARE TECHNOLOGIES

Lecture 2 slide 3

Introducing c# and the .net platformThe .NET Solution – Core features:1. Full interoperability with existing Win32 Code –

Existing COM binaries can inter-op with newer .NET binaries and vice versa. PInvoke (PlatfromInvocation) allows you to invoke raw C-based functions (such as the Win32 API) from managed code.

2. Complete and total language integration – Unlike classic COM, .NET supports cross-language inheritance, cross-language exception handling, and cross-language debugging.

3. A common runtime engine shared by all .NET-aware languages – A well-defined set of types that each .NET-aware language “understands”.

4. A base class library – that provides shelter from the complexities of raw API calls, and offers a consistent object model used by all .NET-aware languages.

Page 12: MIDDLE WARE TECHNOLOGIES

Lecture 2 slide 4

Introducing c# and the .net platform5. No more COM plumbing – IClassFactory,

Iunknown, Idispatch, IDLCode, and the evil VARIANT – Compliant data types (BSTR, SAFEARRAY etc.) have been dropped in .NET binary.

6. A truly simplified deployment model – No need to register a binary unit into the System registry. Also the .NET runtime allows multiple versions of the same *.dll to exist in harmony on a single machine (“side-by-side execution”).

Page 13: MIDDLE WARE TECHNOLOGIES

Lecture 2 slide 5

Introducing c# and the .net platformThe building blocks of the .NET platform:

1. CLR - .NET is a new runtime environment and a common base class library. The runtime layer is referred to as Common Language Runtime (CLR). CLR’s primary role is to locate, load and manage .NET types on your behalf.

2. It also takes care of a number of low-level details such as automatic memory management, language integration and ensuring type safety.

Page 14: MIDDLE WARE TECHNOLOGIES

Lecture 3 slide 1

Introducing c# and the .net platform2. CTS (Common Type System) – fully

describes all possible data types and programming constructs supported by the runtime, specifies how these entities can interact with each other and details how they are represented in the .NET metadata format.

3. CLS (Common Language Specification) – is a set of rules that define a subset of a common types and programming constructs that all .NET programming languages can agree on.

Page 15: MIDDLE WARE TECHNOLOGIES

Lecture 3 slide 2

Understanding .NET AssembliesA .NET assembly consists of five

major elements:

1. A standard Windows file header

2. A CLR header that marks the file as a managed module

3. CIL Code

4. Type metadata

5. The assembly manifest

Page 16: MIDDLE WARE TECHNOLOGIES

Lecture 3 slide 3

Understanding .NET AssembliesCore Benefits

1. Assemblies promote code reuse.

2. Assemblies establish a type boundary.

3. Assemblies are versionable and self-describing entities.

4. Assemblies define a security context.

5. Assemblies enable side-by-side execution.

Page 17: MIDDLE WARE TECHNOLOGIES

Lecture 3 slide 4

Understanding .NET Assemblies• Single File Assemblies – contain all the

necessary CIL, metadata and associated manifest in an autonomous, single, well-defined package.

• Multi-file assemblies – are composed of numerous .NET binaries, each of which is termed a module. When building a multi-file assembly, one of these modules (termed the primary module) must contain the assembly manifest and possibly CIL instructions and metadata for various types. The other related modules contain a module level manifest, CIL and type metadata. The primary module documents the set of required secondary modules within the assembly manifest.

Page 18: MIDDLE WARE TECHNOLOGIES

Lecture 4 slide 1

Understanding .NET AssembliesNote:1. Partitioning an assembly into discrete modules

provides a more flexible deployment option. Ex: if a user is referencing a remote assembly

that needs to be downloaded into his machine, the runtime will only download the required modules.

2. Thus, an assembly is a logical grouping of one or more related modules that are intended to be deployed and versioned as a single unit.

Page 19: MIDDLE WARE TECHNOLOGIES

Lecture 4 slide 2

Understanding .NET AssembliesRole of CIL:• CIL is a language that sits above

any particular platform-specific instruction set.

• Regardless of which .NET – aware language you choose, (C#, VB .NET, Eiffel .NET, and so forth); the associated compiler emits CIL instructions.

Page 20: MIDDLE WARE TECHNOLOGIES

Lecture 4 slide 3

Understanding .NET AssembliesBenefits of CIL:1. Language integration – Each .NET-

aware language produces the same underlying CIL. Therefore, all languages are able to interact within a well-defined binary arena.

2. Platform agnostic – the .NET runtime is poised to become a platform-independent architecture, providing the same benefits as Java.

Page 21: MIDDLE WARE TECHNOLOGIES

Lecture 4 slide 4

Understanding .NET AssembliesThe role of .NET Type Metadata:• Describes each and every type – class,

structure, enumeration, and so forth defined in the binary, as well as the members of each type – properties, methods, events, and so on.

The role of the Assembly Manifest:• A valid .NET assembly contains metadata

that describes the code library itself (technically termed a manifest). Like type metadata, it is always the job of the compiler to generate assembly’s manifest.

Page 22: MIDDLE WARE TECHNOLOGIES

Lecture 4 slide 5

Understanding .NET AssembliesCompiling CIL to Platform-specific Instructions:• Since the assemblies contain CIL and metadata, the CIL

must be compiled on the fly before use.• The entity that does this is JIT (Just-In-Time compiler)

or popularly known as “Jitter”. The .NET runtime environment leverages a JIT compiler for each CPU targeting the CLR, each of which is optimized for the platform it is targeting.

Note:– JIT – applications deployed on Hand-held devices – have low-

memory and automatically adjust to that environment.– JIT – Back end Server – have high-memory and again

automatically adjust to that environment.– Caching of results – CIL instructions into corresponding

machine code. On first invocation, the CIL instructions are compiled into platform-specific instructions of the machine and later reused on subsequent invocations.

Page 23: MIDDLE WARE TECHNOLOGIES

Lecture 5 slide 1

Understanding .NET AssembliesCTS (Common Type System):• In .NET, a type is a generic term used to collectively

refer to any entity from the set{class, structure, interface, enumeration, delegate).

CTS Class Types:1. Is the class “sealed” or not? Sealed Classes – cannot

function as a base class to other types.2. Does the class implement any interfaces? Zero or more.3. Is the class abstract or concrete? Abstract classes cannot

be directly created.4. What is the “visibility” of this class? Visibility attribute.

Page 24: MIDDLE WARE TECHNOLOGIES

Lecture 5 slide 2

Understanding .NET AssembliesCLS• is a set of guidelines that describe in

detail, the minimal and complete set of features a given .NET-aware compiler must support to produce code that can be hosted by the CLR, while at the same time be accessed in a uniform manner by all languages that target the .NET platform.

• CLS can be viewed as a physical subset of the full functionality defined by the CTS.

Page 25: MIDDLE WARE TECHNOLOGIES

Lecture 5 slide 3

Understanding .NET AssembliesCLR

• The workflow that takes place between your source code (which is making use of base class library types), a given .NET Compiler, and the .NET execution engine is shown in the following diagram.

Page 26: MIDDLE WARE TECHNOLOGIES

Lecture 5 slide 4

Object-Oriented Programming with C#Pillars of OOP:1. Encapsulation – hide object’s internal implementation.2. Inheritance – code reuse – “is-a” and “has-a”

relationships. Exs: Object Shape Hexagon(“is a”) and Car radio (“has a”)

3. Polymorphism – treat related objects in a similar way.a) Classical – Object Shape Hexagon Circle b) Ad hoc – late binding is used; no common base

class.4. Encapsulation in C#: “public” fields may get

corrupted; so “private” data fields have to be used, which can be manipulated as follows:

a) Define a pair of accessor and mutator fields.b) Define a named property.c) Special key word “read-only” delivers an additional form of data

protection.

Page 27: MIDDLE WARE TECHNOLOGIES

Lecture 6 slide 1

Object-Oriented Programming with C#Ex: for accessors and mutators:public class Employee{ private string fullName;

…//accessorpubic string getfullName(){return fullName;}//mutatorpublic void setfullName(string n) { fullName=n;}

Class Property:.NET Classes (as well as structures and interfaces) can also define

properties.Ex: public static int Main(string[] args)

{ Employee p = new Employee();p.EmpID = 81;Console.WriteLine(“Person ID is: {0}”,

p.EmpID);return 0;

}

Page 28: MIDDLE WARE TECHNOLOGIES

Lecture 6 slide 2

Object-Oriented Programming with C#//custom property for the EmpID data point.public class Employee{ …

private int EmpID;public int EmpID{

get { return EmpID;}set { EmpID = value;}

}Note:1. Properties make your types easier to manipulate.

Ex: accessors & mutators:Employee joe = new Employee();joe.setAge(joe.getAge() + 1);propertiesEmployee joe = new Employee();joe.Age++;

A C# property maps to a get_/set_ pair. So care must be taken to see that get_/set_ property methods are not redefined.

Page 29: MIDDLE WARE TECHNOLOGIES

Lecture 6 slide 3

Object-Oriented Programming with C#Read-only and Write-only properties:Build a property without a corresponding set block for read-only and

without a get block for write-only properties.Static properties: are supported in C#.Properties are bound to a given class; but not an instance (object) of

that class.Static constructors are also supported in C# - useful for assigning

initial values to static data.Read-only fields, static Read-only fields – are also supported.• Inheritance:

Employee SalesPerson Manager

public class Manager : Employee{ … }public class SalesPerson : Employee{ … }

Note: A child class cannot directly access private members of its parent class.

Page 30: MIDDLE WARE TECHNOLOGIES

Lecture 6 slide 4

Object-Oriented Programming with C#Protected: data and methods can be accessed directly by

any descendant.Sealed classes: prevent inheritance.Ex: public sealed class PTSalesPerson : SalesPerson

{ … }Useful for creating stand-alone utility classes like

System.String.Containment/Delegation (“has-a” relationship):public class Radio{ … }public class Car{ …

private Radio theMusicBox;}Nested classes – are permitted.

Page 31: MIDDLE WARE TECHNOLOGIES

Lecture 7 slide 1

Object-Oriented Programming with C#3. Polymorphism: Base class – “virtual” method. Sub

class – “override” base class’s virtual method.Abstract classes:Ex: abstract public class Employee

{ … }Abstract methods: can be used, when a concrete

definition is not supplied.Versioning class members: method hiding – opposite of

method overriding. Key word: newEx: public class oval : Circle

{ public oval {base.petName = “Joe”; }public new void Draw(){ … }

Casting: between “types” permitted.“Type-of” – key word “is”

Page 32: MIDDLE WARE TECHNOLOGIES

Lecture 7 slide 2

Callback Interfaces, Delegates and Events1. Objects can talk back to the entity that created them.2. “Two-way” conversation is common for objects in a

system through the use of events, callback interfaces and other programming constructs.

3. C# Key word “delegate”.4. Interfaces – used to define common behaviors.5. Callback interfaces:

ex: //The callback interfacepublic interface IEngineEvents{ void AboutToBlow(string

msg);void Exploded(string msg);

}

Page 33: MIDDLE WARE TECHNOLOGIES

Lecture 7 slide 3

Callback Interfaces, Delegates and Events6. Event interfaces are not implemented directly by the client

executable, but rather by a helper sink object; upon which the sender of the events (the Car type in our ex.) will make calls.

7. Assume the client-side sink class is called CarEventSink.8. When the Car type sends the event notification to the sink, it will

print the messages to the console.9. //CarEventSink

public class CarEventSink : IEngineEvents{ private string name;//Diagnostic member to identify sink.

public CarEventSink() { }public CarEventSink(string sinkName){ name = sinkName; }public void AboutToBlow(string msg){Console.WriteLine(“{0}reporting:

{1}”,name,msg); }public void Exploded(string msg){Console.WriteLine(“{0}reporting:

{1}”,name,msg); }}

Page 34: MIDDLE WARE TECHNOLOGIES

Lecture 7 slide 4

Callback Interfaces, Delegates and Events10. Now, a reference to this sink has to be passed to the

Car type.11. The Car holds onto the reference and makes calls

back on the sink, when appropriate.12. To obtain a reference to the sink, Advise() method

can be used – similar to COM paradigm.13. Similarly, to detach from the event source, another

custom method Unadvise() can be used – again similar to COM paradigm.

Page 35: MIDDLE WARE TECHNOLOGIES

Lecture 8 slide 1

Callback Interfaces, Delegates and Events14. To register multiple event sinks, let us assume that the

Car maintains an ArrayList to represent each outstanding connection.

//This car does not make any use of the //C# delegate or event key word, but can//still send events to the caller.public class Car{ //The set of connected sinks

ArrayList itfConnections = new ArrayList();//Attach or disconnect from the source of events.public void Advise(IEngineEvents itfClientImpl){ itfConnections.Add(itfClientImpl); }public void Unadvise(IEngineEvents itfClientImpl){ itfConnections.Remove(itfClientImpl);

}}

Page 36: MIDDLE WARE TECHNOLOGIES

Lecture 8 slide 2

Callback Interfaces, Delegates and Events15. Car.SpeedUp() method is used to send the events. The method iterates

over the list of connections and fires the correct notification when appropriate.

//Interface-based event protocol!Class Car{…public void SpeedUp(int delta){ //If the car is dead, send exploded event to each sink.

if(carIsDead){ foreach(IEngineEvents e in itfConnections)

e.Exploded(“Sorry, this car is dead …”);}else {currSpeed += delta; if(10 == maxSpeed – currSpeed) { foreach(IEngineEvents e in itfConnections)

e.AboutToBlow(“Careful! Going to blow!”);}

if(currSpeed >= maxSpeed)CarIsDead = true;

else Console.WriteLine(“\tcurrSpeed={0}”,currSpeed);

}}

Page 37: MIDDLE WARE TECHNOLOGIES

Lecture 8 slide 3

Callback Interfaces, Delegates and Events16. Client-side code://Make a car and listen to the events.public class CarApp{ public static int Main(string[] args)

{ Car c1 = new Car(“SlugBug”, 100, 10);//Make sink objectCarEventSink sink = new CarEventSink();//Pass the Car a ref. to the sink.c1.Advise(sink);//Speed up (this will generate the events)for(int i = 0; i < 6; i++)

c1.Speedup(20);//Detach from events.c1.Unadvise(sink);

}return 0;

}

Page 38: MIDDLE WARE TECHNOLOGIES

Lecture 8 slide 4

Callback Interfaces, Delegates and EventsNote: Unadvise() method is very helpful in allowing the caller to

selectively detach from events at will.Ex: The following app registers two sinks, dynamically removes a

particular sink during the flow of execution, and continues to process the program.

public static int Main(string[] args){Car c1 = new Car(“SlugBug”, 100, 10); //Make sink objects Console.WriteLine(“***Creating sinks***”); CarEventSink sink = new CarEventSink(“First sink”); CarEventSink myOtherSink = new CarEventSink(“Other

sink”); //Hand sinks to car Console.WriteLine(“Sending 2 sinks into Car”); c1.Advise(sink); c1.Advise(myOtherSink);

Page 39: MIDDLE WARE TECHNOLOGIES

Lecture 8 slide 5

Callback Interfaces, Delegates and Events//Speed up (this will generate the events) Console.WriteLine(“\n***Speeding up***”); for(int i=0; i < 6; i++)

c1.SpeedUp(20); //Detach first sink from events Console.WriteLine(“\nRemoving first sink”); c1.Unadvise(sink); //speed up again (only “other sink” will be called.) Console.WriteLine(“\n***Speeding up again***”); for(int I=0; I < 6; I++)

c1.SpeedUp(20); //Detach other sink from events. Console.WriteLine(“\n***Removing second sink***”); c1.Unadvise(myOtherSink); return 0; }

Page 40: MIDDLE WARE TECHNOLOGIES

Lecture 8 slide 6

Callback Interfaces, Delegates and Events.NET Delegate Type:1. Windows API – C-Style function ptrs – callback

functions (or callbacks). The approach is not safe, as no. & type of args. infn. is not stored; only address is stored.

2. .NET provides a safer, more Obj. Oriented manner, using delegates.

3. A delegate maintains name, arguments and return value of the method.

4. .NET supports both synchronous, and asynchronous delegates.

5. Defining a delegate in C#:ex: 1. Public delegate void PlayAcidHouse (Person theDJ, int volume);

The C# compiler dynamically produces a new sealed class named PlayAcidHouse deriving from System.MultiCastDelegate.

Page 41: MIDDLE WARE TECHNOLOGIES

Lecture 9 slide 1

Callback Interfaces, Delegates and EventsThe dynamically generated sealed class:Sealed class PlayAcidHouse : System.MultiCastDelegate{public PlayAcidHouse(object target, uint

functionAddress); public void Invoke(Person theDJ, int volume); public IAsyncResult BeginInvoke(Person theDJ, int

volume, AsyncCallback cb, object state); public void EndInvoke(IAsyncResult result);}Invoke() – core method, may be called to inform the

delegate it is time to call the method it is currently pointing to. It is a synchronous method.

BeginInvoke() & EndInvoke() – provide ability to call the current method asynchronously.

Ex 2: public delegate string TakeSomeBools(bool a, bool b, bool c);

Page 42: MIDDLE WARE TECHNOLOGIES

Lecture 9 slide 2

Callback Interfaces, Delegates and EventsEx 3: public delegate string

TakeSomeBoolsByRefAndAsOut (out bool a, out bool b, ref bool c);

In this case the EndInvoke() method will have these three (out & ref) parameters also in its args list.

System MultiCastDelegate: derives from System.Delegate and implements two standard interfaces.

public abstract class MultiCastDelegate : Delegate, ICloneable, ISerializable

{public MethodInfo Method {get;}…

}

Page 43: MIDDLE WARE TECHNOLOGIES

Lecture 9 slide 3

Callback Interfaces, Delegates and EventsA simple delegate example:namespace SimpleDelegate{class DelegateApp

{//This is the method that will be called by the delegate public static void PlainPrint(string msg) {Console.WriteLine(“Msg is:{0}”, msg);} //Define a delegate type public delegate void AnyMethodTakingAString(string s); public static void Main() {//Make the delegate AnyMethodTakingAString del; del = new AnyMethodTakingAString(PlainPrint); //AnyMethodTakingAString.Invoke() called here! del(“Hello there …”); //Dump info about the delegate Console.WriteLine(“I just called:{0}”,del.Method); } }}

Page 44: MIDDLE WARE TECHNOLOGIES

Lecture 9 slide 4

Callback Interfaces, Delegates and EventsOutput: Msg is: Hello there …

I just called: voidPlainPrint(System.string)

Note:1. The target method can be changed dynamically.2. Multicasting with .NET delegates is also

possible.A more elaborate delegate ex:• Two new boolean variables for the Car class –

isDirty(due for a wash) and shouldRotate (tire rotation).

• Additional properties and an updated constructor are included.

Page 45: MIDDLE WARE TECHNOLOGIES

Lecture 9 slide 5

Callback interfaces, delegates and eventspublic class Car{ … private bool isDirty; private bool shouldRotate; public Car(string name, int max, int curr, bool dirty, bool rotate) { …

isDirty = dirty;shouldRotate = rotate;

} public bool Dirty { get{return isDirty;}

set (isDirty = value;} } public bool Rotate { get{return shouldRotate;}

set (shouldRotate = value;} }}

Page 46: MIDDLE WARE TECHNOLOGIES

Lecture 9 slide 6

Callback interfaces, delegates and eventsDelegate://This delegate is actually a class encapsulating a//function pointer to ‘some method’, taking a Car//as a parameter, and returning void.public delegate void CarDelegate(Car c);

Note: A more enlightened alternative is to define CarDelegate directly within the Car class (Delegate as nested type)

public class Car{//This is represented in CIL as //Car$CarDelegate (i.e. a nested type) public delegate void CarDelegate(Car c); …}

Page 47: MIDDLE WARE TECHNOLOGIES

Lecture 10 slide 1

Callback interfaces, delegates and eventsUsing the CarDelegate:

1. New class Garage maintains a collection of Car types contained in an ArrayList (on creation, filled with some initial car types).

2. ProcessCars() method – takes a single arg of type Car.CarDelegate. In the implementation of ProcessCars(), you pass each car in your collection as a parameter to the “function pointed to” by the delegate.

Page 48: MIDDLE WARE TECHNOLOGIES

Lecture 10 slide 2

Callback interfaces, delegates and events//The Garage class has a method that makes use //of the CarDelegate.Using System.Collections;…Public class Garage{ //A list of all cars in the Garage.

ArrayList theCars = new ArrayList();//creates the cars in the Garage.public Garage(){theCars.Add(new Car(“Viper”,100,0,true,false)); theCars.Add(new Car(“Fred”,100,0,false,false));

theCars.Add(new Car(“BillyBob”,100,0,false,true)); theCars.Add(new Car(“Bart”,100,0,true,true)); theCars.Add(new Car(“Stan”,100,0,false,true));

}

Page 49: MIDDLE WARE TECHNOLOGIES

Lecture 10 slide 3

Callback interfaces, delegates and events//This method takes a Car.CarDelegate as a parameter.//Therefore, ‘proc’ is nothing more than a function//pointer!public void ProcessCars(Car.CarDelegate proc){ //Diagnostics: Where are we forwarding the call?

C.W.(“Calling: {0}”, d.Method.ToString());//Diagnostics: Are we calling an instance method or a//static method?if(proc.Target!=null)

C.W.(“->Target:{0}”,proc.Target.ToString());else C.W.(“->Target is a static method”);//Real work: Now call the method, passing in each carforeach(Car c in theCars)

proc(c);}}

Page 50: MIDDLE WARE TECHNOLOGIES

Lecture 10 slide 4

Callback interfaces, delegates and events• When the object user calls ProcessCars(), it will send in the

name of the method that should handle this request. Let us assume, these are static members named WashCar() and RotateTires().

Usage://The garage delegates all work orders to these static functionspublic class CarApp{ //A Target for the delegate.

public static void WashCar(Car c){ if(c.Dirty) C.W.(“Cleaning a Car”);

else C.W.(“The Car is already clean …”);}public static void RotateTires(Car c){ if(c.Rotate) C.W.(“Tires have been rotated”);

else C.W.(“Don’t need to be rotated …”);}

Page 51: MIDDLE WARE TECHNOLOGIES

Lecture 10 slide 5

Callback interfaces, delegates and eventspublic int Main(string[] args){ Garage g = new Garage();

//Wash all dirty carsg.ProcessCars(new Car.CarDelegate(WashCar));//Rotate the tires.g.ProcessCars(new Car.CarDelegate(RotateTires));return 0;

}}

Page 52: MIDDLE WARE TECHNOLOGIES

Lecture 10 slide 6

Callback interfaces, delegates and eventsAsynchronous Delegates:Threading concepts – word doc printing 1000 pages;

basic user input requests to be serviced.BeginInvoke() and EndInvoke() methods.Events:event key word.GUI – Button, Text Box etc.Non-GUI – apps also handle eventspublic static event EngineHandler Exploded;public static event EngineHandler AboutToBlow;Where EngineHandler is declared as a delegate.Each event internally represented as the following

members – a private class; an add_XXX() method and a remove_XXX() method.