75
Ray Konopka Introduction to the Microsoft .NET Framework for Delphi Developers

Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

Embed Size (px)

Citation preview

Page 1: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

Ray KonopkaRay Konopka

Introduction to theMicrosoft .NET Framework

for Delphi Developers

Introduction to theMicrosoft .NET Framework

for Delphi Developers

Page 2: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

2

AgendaAgenda

Delphi and .NET

What is the .NET Framework?

.NET Framework Core Features

Writing .NET Managed Code

Programming in Delphi for .NET

Delphi and .NET

What is the .NET Framework?

.NET Framework Core Features

Writing .NET Managed Code

Programming in Delphi for .NET

Page 3: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

3

Origins of .NETOrigins of .NET

The .NET Framework was influenced by many languages and frameworks

But there is no question that it looks a lot like Delphi and the VCL

The .NET Framework was influenced by many languages and frameworks

But there is no question that it looks a lot like Delphi and the VCL

Page 4: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

4

Delphi or .NET?Delphi or .NET?

Single-inheritance Object Hierarchy

Strongly Typed

Formal concept of properties and events

Consistent use of exceptions

Reusable and extensible component model

Formal notion of class interfaces

Special DLLs containing metadata (RTTI) and code

WinForms (VCL).

Single-inheritance Object Hierarchy

Strongly Typed

Formal concept of properties and events

Consistent use of exceptions

Reusable and extensible component model

Formal notion of class interfaces

Special DLLs containing metadata (RTTI) and code

WinForms (VCL).

Page 5: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

5

Migrating to .NETMigrating to .NET

Shorter learning curve for Delphi developers Already familiar with object-oriented

programming Well versed in component-oriented programming Comfortable consuming and creating events Already know the benefits of exceptions and how

to use them

Do not have to throw away existing Delphi development knowledge

Delphi 8 provides a clear migration path to .NET.

Shorter learning curve for Delphi developers Already familiar with object-oriented

programming Well versed in component-oriented programming Comfortable consuming and creating events Already know the benefits of exceptions and how

to use them

Do not have to throw away existing Delphi development knowledge

Delphi 8 provides a clear migration path to .NET.

Page 6: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

6

What is the .NET Framework?

What is the .NET Framework?

CILCIL

CLRCLR

CLSCLS

GCGC

GACGAC

BDPBDP

ADO.NETADO.NET

TLATLA

JITJIT

VESVES

FCLFCL

VCL.NETVCL.NET

RTL.NETRTL.NET

ASP.NETASP.NET

CUBSCUBS

Page 7: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

7

What is the .NET Framework?

What is the .NET Framework?

Virtual Machine Execution System The Common Language Runtime (CLR)

Language-Neutral Class Library The Framework Class Library (FCL)

Successor to Win32 Application Programming Model

Competitor to Java Platform

Virtual Machine Execution System The Common Language Runtime (CLR)

Language-Neutral Class Library The Framework Class Library (FCL)

Successor to Win32 Application Programming Model

Competitor to Java Platform

Page 8: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

8

Common Language RuntimeCommon Language Runtime

Serves as the execution engine for managed applications Activates objects Performs security checks Manages memory allocations and recovery Executes code etc.

Serves as the execution engine for managed applications Activates objects Performs security checks Manages memory allocations and recovery Executes code etc.

Page 9: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

9

Framework Class LibraryFramework Class Library

Object-oriented API for writing managed applications

Defines more than 7,000 types classes interfaces enumerations delegates

Object-oriented API for writing managed applications

Defines more than 7,000 types classes interfaces enumerations delegates

Page 10: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

10

.NET Framework Core Features

.NET Framework Core Features

Simplified & Consistent Programming ModelSide-by-Side Execution and VersioningSimplified DeploymentMulti-platform SupportProgramming Language IntegrationGarbage CollectionCode VerificationConsistent Error HandlingCode Access SecurityInteroperability

Simplified & Consistent Programming ModelSide-by-Side Execution and VersioningSimplified DeploymentMulti-platform SupportProgramming Language IntegrationGarbage CollectionCode VerificationConsistent Error HandlingCode Access SecurityInteroperability

Page 11: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

11

Simplified Programming Model

Simplified Programming Model

All operating system services accessed through common object-oriented programming model File Access Data Access Threading Graphics etc.

The CLR removes many cumbersome concepts Registry, GUIDs, IUnknown, HRESULTS, etc.

All operating system services accessed through common object-oriented programming model File Access Data Access Threading Graphics etc.

The CLR removes many cumbersome concepts Registry, GUIDs, IUnknown, HRESULTS, etc.

Page 12: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

12

Side-by-Side Execution/Versions

Side-by-Side Execution/Versions

The CLR allows application components to be isolated

The CLR will always load the components that were used to be build and test the application.

If an application runs after installation, it should always run

Multiple versions of an application component may be installed on the same system

DLL versioning issues (DLL Hell) are eliminated

The CLR allows application components to be isolated

The CLR will always load the components that were used to be build and test the application.

If an application runs after installation, it should always run

Multiple versions of an application component may be installed on the same system

DLL versioning issues (DLL Hell) are eliminated

Page 13: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

13

Simplified DeploymentSimplified Deployment

Installing most .NET applications involves Copying files to a directory Adding a shortcut to Start menu, desktop, or

Quick Launch bar

Registry access no longer needed No more GUIDs, ProgIDs, ClassIDs, etc.

To uninstall, just delete the files

Installing most .NET applications involves Copying files to a directory Adding a shortcut to Start menu, desktop, or

Quick Launch bar

Registry access no longer needed No more GUIDs, ProgIDs, ClassIDs, etc.

To uninstall, just delete the files

Page 14: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

14

Multi-Platform SupportMulti-Platform Support

.NET source code compiled to Common Intermediate Language (CIL) instead of traditional CPU instructions High-level CPU independent assembly language ~100 different instructions Direct support for object types, exceptions, etc.

DCCIL compiles Delphi source code into CIL

.NET source code compiled to Common Intermediate Language (CIL) instead of traditional CPU instructions High-level CPU independent assembly language ~100 different instructions Direct support for object types, exceptions, etc.

DCCIL compiles Delphi source code into CIL

Page 15: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

15

Multi-Platform SupportMulti-Platform Support

At runtime, the CLR translates the CIL into native CPU instructions Resulting CPU instructions are optimized for the

host processor

A .NET application can be deployed to any machine that has an ECMA-compliant version of the CLR and FCL e.g. x86, IA64, Pocket PC, Linux (via Mono), etc.

At runtime, the CLR translates the CIL into native CPU instructions Resulting CPU instructions are optimized for the

host processor

A .NET application can be deployed to any machine that has an ECMA-compliant version of the CLR and FCL e.g. x86, IA64, Pocket PC, Linux (via Mono), etc.

Page 16: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

16

Language InteroperabilityLanguage Interoperability

The CLR allows different programming languages to share types

The CLR provides a Common Type System (CTS) Describes how types are defined and how they

behave Specifies the rules for type visibility and members

access Single inheritance - System.Object

Common Language Specification (CLS) Defines the minimum set of features that all .NET

languages that target the CLR must support

The CLR allows different programming languages to share types

The CLR provides a Common Type System (CTS) Describes how types are defined and how they

behave Specifies the rules for type visibility and members

access Single inheritance - System.Object

Common Language Specification (CLS) Defines the minimum set of features that all .NET

languages that target the CLR must support

Page 17: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

17

CLR/CTS & CLS RelationshipCLR/CTS & CLS Relationship

CLR/CTS

CLS

C#

Others

Delphi

Each language supports A subset of the CLR/CTS A superset of the CLS

Each language supports A subset of the CLR/CTS A superset of the CLS

Page 18: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

18

Garbage CollectionGarbage Collection

The CLR automatically tracks all references to memory

When a block of memory no longer has any “live” references to it, it can be released and reused (collected)

Impact – No deterministic destruction of objects

IDisposable for releasing resources

GC in the CLR covered in detail in February 2004 issue of The Delphi Magazine by Julian Bucknall.

The CLR automatically tracks all references to memory

When a block of memory no longer has any “live” references to it, it can be released and reused (collected)

Impact – No deterministic destruction of objects

IDisposable for releasing resources

GC in the CLR covered in detail in February 2004 issue of The Delphi Magazine by Julian Bucknall.

Page 19: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

19

Garbage Collection and Delphi

Garbage Collection and Delphi

Destructors in Delphi source code are translated into IDisposable pattern

Free is still available in Delphi 8

Programming pattern for reference types same as before—use Free when finished.

Destructors in Delphi source code are translated into IDisposable pattern

Free is still available in Delphi 8

Programming pattern for reference types same as before—use Free when finished.

begin List := TStringList.Create; try . . . finally List.Free; // Calls Dispose if implementedend;

begin List := TStringList.Create; try . . . finally List.Free; // Calls Dispose if implementedend;

Page 20: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

20

Code VerificationCode Verification

The CLR can verify that all your code is type-safe

The CLR ensures that allocated objects are always accessed appropriately Correct number of parameters Correct types of parameters No inappropriate memory access etc.

The CLR also ensures that execution flow will only transfer to well-known locations Method entry points

The CLR can verify that all your code is type-safe

The CLR ensures that allocated objects are always accessed appropriately Correct number of parameters Correct types of parameters No inappropriate memory access etc.

The CLR also ensures that execution flow will only transfer to well-known locations Method entry points

Page 21: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

21

Consistent Error HandlingConsistent Error Handling

Traditional Win32 programming incorporates many different error handling mechanisms Status Codes GetLastError HRESULTS Structured Exceptions

In the CLR, all failures are reported via Exceptions

Exceptions work across module and programming language boundaries An exception raised in a Delphi class can be

handled in a VB.NET exception handler

Traditional Win32 programming incorporates many different error handling mechanisms Status Codes GetLastError HRESULTS Structured Exceptions

In the CLR, all failures are reported via Exceptions

Exceptions work across module and programming language boundaries An exception raised in a Delphi class can be

handled in a VB.NET exception handler

Page 22: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

22

SecuritySecurity

The CLR supports protecting access to specific parts of application code

Code Access Security based around an assembly’s identity rather than the user’s identity

The CLR supports protecting access to specific parts of application code

Code Access Security based around an assembly’s identity rather than the user’s identity

Page 23: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

23

InteroperabilityInteroperability

The .NET Framework supports interoperability with existing code and components

Managed code can call an unmanaged function in a DLL P/Invoke – Platform Invoke

Managed code can use an existing COM component (server) Managed assembly created from type library

Unmanaged code can use a managed type (server) TlbExp.exe – Assembly to Type Library Converter RegAsm.exe – Assembly Registration Utility

The .NET Framework supports interoperability with existing code and components

Managed code can call an unmanaged function in a DLL P/Invoke – Platform Invoke

Managed code can use an existing COM component (server) Managed assembly created from type library

Unmanaged code can use a managed type (server) TlbExp.exe – Assembly to Type Library Converter RegAsm.exe – Assembly Registration Utility

Page 24: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

24

Writing .NET Managed CodeWriting .NET Managed Code

Managed Modules

Assemblies

Namespaces

Manifests

AppDomains

Safe Code vs. Unsafe Code

Managed Modules

Assemblies

Namespaces

Manifests

AppDomains

Safe Code vs. Unsafe Code

Page 25: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

25

Managed ModulesManaged Modules

An executable designed to be run by the CLRTypically has EXE, DLL, or NETMODULE

extensionContains

Windows Portable Executable (PE) File Header A CLR header Metadata describing contents and external

dependencies CIL instructions generated from source code

However, the CLR cannot execute a managed module directly Must be part of an assembly

An executable designed to be run by the CLRTypically has EXE, DLL, or NETMODULE

extensionContains

Windows Portable Executable (PE) File Header A CLR header Metadata describing contents and external

dependencies CIL instructions generated from source code

However, the CLR cannot execute a managed module directly Must be part of an assembly

Page 26: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

26

AssembliesAssemblies

Logical grouping of one or more modules or files

Smallest unit of reuse, security, and versioning

Assemblies can be created Directly by compiler (e.g. DCCIL.exe, CSC.exe, VBC.exe) By combining existing modules using AL.exe (assembly

linker)

Satellite Assemblies Contain resource data (strings, icons, etc.) Loaded at runtime based on user locale

Note: The CLR loader considers a .NET executable is an assembly

Logical grouping of one or more modules or files

Smallest unit of reuse, security, and versioning

Assemblies can be created Directly by compiler (e.g. DCCIL.exe, CSC.exe, VBC.exe) By combining existing modules using AL.exe (assembly

linker)

Satellite Assemblies Contain resource data (strings, icons, etc.) Loaded at runtime based on user locale

Note: The CLR loader considers a .NET executable is an assembly

Page 27: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

27

Assemblies and DelphiAssemblies and Delphi

Very similar to Packages in Delphi

In fact, you create assemblies using the Delphi package syntax

requires clause lists dependent assemblies (including .NET Framework assemblies)

contains clause lists units to be included

Example RayKonopka.BorCon2004.Samples.dpk

Very similar to Packages in Delphi

In fact, you create assemblies using the Delphi package syntax

requires clause lists dependent assemblies (including .NET Framework assemblies)

contains clause lists units to be included

Example RayKonopka.BorCon2004.Samples.dpk

Page 28: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

28

NamespacesNamespaces

A namespace is a logical container for types

Designed to eliminate name collisions

Namespaces do not have any physical manifestation Unlike Java, they do not map onto a directory

structure

An assembly can contribute to multiple namespaces

Multiple assemblies can contributed to a namespace

Examples System.Drawing System.Windows.Forms

A namespace is a logical container for types

Designed to eliminate name collisions

Namespaces do not have any physical manifestation Unlike Java, they do not map onto a directory

structure

An assembly can contribute to multiple namespaces

Multiple assemblies can contributed to a namespace

Examples System.Drawing System.Windows.Forms

Page 29: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

29

Namespaces in DelphiNamespaces in Delphi

A Delphi project (program, library, or package) implicitly introduces its own namespace called the project default namespace.

A unit may explicitly declare itself to be part of a namespace in the unit header unit RayKonopka.Common.StringUtils; Namespace = RayKonopka.Common.StringUtils

A generic unit automatically becomes part of the project default namespace unit RkStringUtils; Namespace =

RayKonopka.BorCon2004.RkStringUtils

A Delphi project (program, library, or package) implicitly introduces its own namespace called the project default namespace.

A unit may explicitly declare itself to be part of a namespace in the unit header unit RayKonopka.Common.StringUtils; Namespace = RayKonopka.Common.StringUtils

A generic unit automatically becomes part of the project default namespace unit RkStringUtils; Namespace =

RayKonopka.BorCon2004.RkStringUtils

Page 30: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

30

Multi-unit NamespacesMulti-unit Namespaces

One of the criticisms of Delphi 8’s support of namespaces is that multiple units cannot belong to the same namespace

This is no longer an issue with Diamondback—the next version of Delphi.

One of the criticisms of Delphi 8’s support of namespaces is that multiple units cannot belong to the same namespace

This is no longer an issue with Diamondback—the next version of Delphi.

Page 31: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

31

ManifestsManifests

An XML description of the contents and external dependencies of a managed module

A manifest specifies the exact version of a module that should be loaded to satisfy an external reference

Internal - Manifest can be embedded as resource

External - Manifest file can be placed in same directory as executable. Must have same base filename as module. RayKonopka.Controls.dll.manifest

An XML description of the contents and external dependencies of a managed module

A manifest specifies the exact version of a module that should be loaded to satisfy an external reference

Internal - Manifest can be embedded as resource

External - Manifest file can be placed in same directory as executable. Must have same base filename as module. RayKonopka.Controls.dll.manifest

Page 32: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

32

AppDomainsAppDomains

An Application Domain is a context in which one or more assemblies may be loaded

An AppDomain is the smallest granularity of code disposal You cannot unload an assembly You can unload an AppDomain, which will dispose

of all the assemblies loaded into it

By default, every managed executable will run in its own, separate process that has just one AppDomain

However, the CLR supports loading multiple AppDomains into a single process

An Application Domain is a context in which one or more assemblies may be loaded

An AppDomain is the smallest granularity of code disposal You cannot unload an assembly You can unload an AppDomain, which will dispose

of all the assemblies loaded into it

By default, every managed executable will run in its own, separate process that has just one AppDomain

However, the CLR supports loading multiple AppDomains into a single process

Page 33: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

33

AppDomain BoundariesAppDomain Boundaries

Objects in one domain cannot be accessed by code in another domain

Data passed between domains must be marshaled across the domain boundary

Objects in one domain cannot be accessed by code in another domain

Data passed between domains must be marshaled across the domain boundary

Page 34: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

34

Safe vs. Unsafe CodeSafe vs. Unsafe Code

Managed code DOES NOT mean safe code

Safe code is code that is verifiably safe PEVerify.exe

Safe code does not improperly access memory does not call methods with inappropriate parameters cannot adversely affect another application’s code etc.

Code that cannot be verified is considered unsafe Call external APIs (external to .NET) Using pointers and other unsafe types

Managed code DOES NOT mean safe code

Safe code is code that is verifiably safe PEVerify.exe

Safe code does not improperly access memory does not call methods with inappropriate parameters cannot adversely affect another application’s code etc.

Code that cannot be verified is considered unsafe Call external APIs (external to .NET) Using pointers and other unsafe types

Page 35: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

35

Unsafe Types in DelphiUnsafe Types in Delphi

Data types that work with pointers in some way are considered unsafe PChar Untyped Pointers file of <type> Variant Records Untyped out and ref parameters Real48 (i.e. 6 byte floating point numbers)

Data types that work with pointers in some way are considered unsafe PChar Untyped Pointers file of <type> Variant Records Untyped out and ref parameters Real48 (i.e. 6 byte floating point numbers)

Page 36: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

36

Unsafe Code in DelphiUnsafe Code in Delphi

Unsafe code accesses or works directly with memory and cannot be verified to be safe BlockRead BlockWrite Addr Ptr Absolute

Unsafe code accesses or works directly with memory and cannot be verified to be safe BlockRead BlockWrite Addr Ptr Absolute

Page 37: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

37

Unsafe Typecasts in DelphiUnsafe Typecasts in Delphi

An unsafe typecast occurs when you cast an object to a type that is not an ancestor or descendant of the object instance

An unsafe typecast occurs when you cast an object to a type that is not an ancestor or descendant of the object instance

var NumList: TStringList;

procedure AddNumber(Caption: string; Value: Integer);begin NumList.AddObject( Caption, TObject( Value ) );end;

var NumList: TStringList;

procedure AddNumber(Caption: string; Value: Integer);begin NumList.AddObject( Caption, TObject( Value ) );end;

Page 38: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

38

BreakBreak

Page 39: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

39

Programming in Delphi for .NET

Programming in Delphi for .NET

FCL Overview

Types and Attributes

Exceptions, Debugging, and Tracing

Math, Strings, and Regular Expressions

File I/O

Collections

WinForms and Graphics

Reflection

FCL Overview

Types and Attributes

Exceptions, Debugging, and Tracing

Math, Strings, and Regular Expressions

File I/O

Collections

WinForms and Graphics

Reflection

Page 40: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

40

FCL OverviewFCL Overview

The Framework Class Library (FCL) is the object-oriented API for writing managed applications

The FCL defines more than 7,000 types Classes Records (Called structs in .NET documentation) Interfaces Enumerations Delegates

The types defined in the FCL allow developers to build all kinds of applications…

The Framework Class Library (FCL) is the object-oriented API for writing managed applications

The FCL defines more than 7,000 types Classes Records (Called structs in .NET documentation) Interfaces Enumerations Delegates

The types defined in the FCL allow developers to build all kinds of applications…

Page 41: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

41

ApplicationsApplications

Web Services Methods that can be accessed over the Internet

using SOAP and XML

Web Forms HTML-based web applications ASP.NET

Windows Forms (i.e. WinForms) MS Windows-based GUI applications Controls, menus, mouse and keyboard events,

etc.

Web Services Methods that can be accessed over the Internet

using SOAP and XML

Web Forms HTML-based web applications ASP.NET

Windows Forms (i.e. WinForms) MS Windows-based GUI applications Controls, menus, mouse and keyboard events,

etc.

Page 42: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

42

Applications (cont.)Applications (cont.)

Console Applications MS Windows-based command line tools and

utilities

Windows Services Controllable via the Windows Service Control

Manager

Component Libraries The FCL supports extension through inheritance

Console Applications MS Windows-based command line tools and

utilities

Windows Services Controllable via the Windows Service Control

Manager

Component Libraries The FCL supports extension through inheritance

Page 43: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

43

FCL NamespacesFCL Namespaces

The types in the FCL are organized into ~100 namespaces

System Basic types used by every application

System.Collections Types for managing collections of objects

System.ComponentModel Types used to implement runtime and design

features of components and controls

System.Data ADO.NET data access classes

The types in the FCL are organized into ~100 namespaces

System Basic types used by every application

System.Collections Types for managing collections of objects

System.ComponentModel Types used to implement runtime and design

features of components and controls

System.Data ADO.NET data access classes

Page 44: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

44

FCL Namespaces (cont.)FCL Namespaces (cont.)

System.Diagnostic Types to help instrument and debug

applications Debug and Trace static classes

System.Drawing Type for generating graphical output (GDI+)

System.Globalization Types for National Language Support (NLS)

System.IO Type for performing file and stream I/O

System.Diagnostic Types to help instrument and debug

applications Debug and Trace static classes

System.Drawing Type for generating graphical output (GDI+)

System.Globalization Types for National Language Support (NLS)

System.IO Type for performing file and stream I/O

Page 45: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

45

FCL Namespaces (cont.)FCL Namespaces (cont.)

System.Net Types that allow network communiciations

System.Reflection Types that allow inspection of metadata

System.Runtime.InteropServices Types that allow managed code to access

unmanaged OS platform facilities

System.Runtime.Remoting Type that allow for types to be access remotely

System.Net Types that allow network communiciations

System.Reflection Types that allow inspection of metadata

System.Runtime.InteropServices Types that allow managed code to access

unmanaged OS platform facilities

System.Runtime.Remoting Type that allow for types to be access remotely

Page 46: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

46

FCL Namespaces (cont.)FCL Namespaces (cont.)

System.Runtime.Serialization Types that allow instances of objects to be

persisted and regenerated from a stream

System.Text Type to work with text in different encodings

(e.g. ASCII or Unicode)

System.Threading Types used for asynchronous-operations and

synchronizing access to resources

System.Web.Services Types for writing Web services

System.Runtime.Serialization Types that allow instances of objects to be

persisted and regenerated from a stream

System.Text Type to work with text in different encodings

(e.g. ASCII or Unicode)

System.Threading Types used for asynchronous-operations and

synchronizing access to resources

System.Web.Services Types for writing Web services

Page 47: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

47

FCL Namespaces (cont.)FCL Namespaces (cont.)

System.Web.UI Core types used by ASP.NET

System.Web.UI.WebControls ASP.NET Server Controls

System.Windows.Forms Type for writing WinForms applications

System.XML Types used for processing XML schemas and

data.

System.Web.UI Core types used by ASP.NET

System.Web.UI.WebControls ASP.NET Server Controls

System.Windows.Forms Type for writing WinForms applications

System.XML Types used for processing XML schemas and

data.

Page 48: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

48

.NET Types.NET Types

ALL types in .NET are classes that descend from System.Object TObject = System.Object

For performance reasons, not all types are implemented the same way

Two kinds of types in .NET Reference Types Value Types

ALL types in .NET are classes that descend from System.Object TObject = System.Object

For performance reasons, not all types are implemented the same way

Two kinds of types in .NET Reference Types Value Types

Page 49: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

49

Reference & Value TypesReference & Value Types

Reference Types Allocated on the managed heap Classes are reference types

Value Types Descend from System.ValueType Allocated on the stack Not garbage collected Primitive types, records and enumerations are

value types

Reference Types Allocated on the managed heap Classes are reference types

Value Types Descend from System.ValueType Allocated on the stack Not garbage collected Primitive types, records and enumerations are

value types

Page 50: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

50

Types ExampleTypes Example

DotNETTypes.dpr

Lutz Roeder’s Reflector

DotNETTypes.dpr

Lutz Roeder’s Reflector

Page 51: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

51

BoxingBoxing

Boxing is the process of creating a copy of a value type on the managed heap so it can be treated as a reference type

A boxed value type can be unboxed as well, but requires a type cast

Boxing and unboxing does affect performance

Boxing is the process of creating a copy of a value type on the managed heap so it can be treated as a reference type

A boxed value type can be unboxed as well, but requires a type cast

Boxing and unboxing does affect performance

procedure AddCustomer(List: ArrayList; C: TCustomer);begin // Box the value type and add the reference to List List.Add( C );end;

procedure AddCustomer(List: ArrayList; C: TCustomer);begin // Box the value type and add the reference to List List.Add( C );end;

Page 52: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

52

AttributesAttributes

Attributes provide a way to add information to metadata

Can be applied to assemblies, classes, methods, properties, parameters, etc.

All attributes descend from System.Attribute TCustomAttribute = System.Attribute

Attributes provide a way to add information to metadata

Can be applied to assemblies, classes, methods, properties, parameters, etc.

All attributes descend from System.Attribute TCustomAttribute = System.Attribute

[ Conditional( "DEBUG" ) ]procedure DoValidityCheck;begin . . .end;

[ Conditional( "DEBUG" ) ]procedure DoValidityCheck;begin . . .end;

Page 53: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

53

ExceptionsExceptions

Error conditions in .NET are reported via exceptions

Common FCL exception classes ArgumentNullException ArgumentOutOfRangeException IndexOutOfRangeException InvalidCastException NullReferenceException

Recommended that custom exception classes be derived from System.ApplicationException Not consistently followed in the FCL

Error conditions in .NET are reported via exceptions

Common FCL exception classes ArgumentNullException ArgumentOutOfRangeException IndexOutOfRangeException InvalidCastException NullReferenceException

Recommended that custom exception classes be derived from System.ApplicationException Not consistently followed in the FCL

Page 54: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

54

Debugging/TracingDebugging/Tracing

System.Diagnostics defines the Debug and Trace static classes

Both do similar things (i.e. allow developer to record information about their program’s execution)

Debug Only available when debugging When “release” mode used to build application,

Debug statements are removed from the CIL generation

Trace Available both in debug mode and release mode

System.Diagnostics defines the Debug and Trace static classes

Both do similar things (i.e. allow developer to record information about their program’s execution)

Debug Only available when debugging When “release” mode used to build application,

Debug statements are removed from the CIL generation

Trace Available both in debug mode and release mode

Page 55: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

55

MathMath

The System namespace defines the static Math class

The Math class defines many mathematical functions Round Floor Log Sin/Cos/Tan Sqrt etc.

The Math class also defines constants E and PI

The System namespace defines the static Math class

The Math class defines many mathematical functions Round Floor Log Sin/Cos/Tan Sqrt etc.

The Math class also defines constants E and PI

Page 56: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

56

Math ExampleMath Example

Math Tab in FCLSamples

Demonstrates several functions defined in the Math class

Also illustrates exception handling FormatException

Math Tab in FCLSamples

Demonstrates several functions defined in the Math class

Also illustrates exception handling FormatException

Page 57: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

57

StringsStrings

Strings receive quite a bit of attention in .NET

All classes implement a ToString method

The String class supports many useful methods Format, ToUpper, StartsWidth, Replace,

etc.

However, Delphi string functions still available and quite useful Copy, Delete, Pos

Strings receive quite a bit of attention in .NET

All classes implement a ToString method

The String class supports many useful methods Format, ToUpper, StartsWidth, Replace,

etc.

However, Delphi string functions still available and quite useful Copy, Delete, Pos

Page 58: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

58

StringBuilderStringBuilder

System.String instances are immutable-once defined, they cannot be changed

When having to perform lots of concatenations, there is a performance hit Each concatenation results in a new memory

allocation and a memory copy

The StringBuilder class should be used when needing to make many changes to a string at one time e.g. concatenating many sub-strings to create a

new string

System.String instances are immutable-once defined, they cannot be changed

When having to perform lots of concatenations, there is a performance hit Each concatenation results in a new memory

allocation and a memory copy

The StringBuilder class should be used when needing to make many changes to a string at one time e.g. concatenating many sub-strings to create a

new string

Page 59: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

59

Strings ExampleStrings Example

Strings Tab in FCLSamples

Illustrates several built-in operations available in String class

Also shows DateTime formatting and StringBuilder class

Strings Tab in FCLSamples

Illustrates several built-in operations available in String class

Also shows DateTime formatting and StringBuilder class

Page 60: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

60

Regular ExpressionsRegular Expressions

The System namespace defines the RegEx class

RegEx can be used to find sub-string matches

RegEx can be used to split strings into tokens

The System namespace defines the RegEx class

RegEx can be used to find sub-string matches

RegEx can be used to split strings into tokens

Page 61: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

61

Regular Expressions Example

Regular Expressions Example

RegEx Tab in FCLSamples

Splits up a path into its separate folders

RegEx Tab in FCLSamples

Splits up a path into its separate folders

Page 62: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

62

File I/OFile I/O

System.IO defines types for file access FileStream StreamReader and StreamWriter for text

files BinaryReader and BinaryWriter for binary

files

System.IO also defines types for manipulating files and directories FileInfo DirectoryInfo

System.IO defines types for file access FileStream StreamReader and StreamWriter for text

files BinaryReader and BinaryWriter for binary

files

System.IO also defines types for manipulating files and directories FileInfo DirectoryInfo

Page 63: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

63

File I/O ExampleFile I/O Example

File I/O Tab in FCLSamples

Displays contents of selected file

File I/O Tab in FCLSamples

Displays contents of selected file

Page 64: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

64

CollectionsCollections

System.Collections defines the following classes

ArrayList – Resizable Arrays

BitArray – Bit Arrays

Hasttable – Tables of key/value pairs structured for fast lookups

Queue – First-in, First-out (FIFO) buffers

SortedList – Tables of sorted key/value pairs accessible by key or index

Stack – Last-in, First-out (LIFO) buffers

System.Collections defines the following classes

ArrayList – Resizable Arrays

BitArray – Bit Arrays

Hasttable – Tables of key/value pairs structured for fast lookups

Queue – First-in, First-out (FIFO) buffers

SortedList – Tables of sorted key/value pairs accessible by key or index

Stack – Last-in, First-out (LIFO) buffers

Page 65: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

65

Collections ExampleCollections Example

Collections Tab in FCLSamples

Counts the number of occurrences of words in a file

Collections Tab in FCLSamples

Counts the number of occurrences of words in a file

Page 66: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

66

WinFormsWinForms

System.Windows.Forms namespace

Basic Form class

Standard WinForm Control hierarchy Button ListBox CheckBox TabControl etc.

Application class

System.Windows.Forms namespace

Basic Form class

Standard WinForm Control hierarchy Button ListBox CheckBox TabControl etc.

Application class

Page 67: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

67

GraphicsGraphics

System.Drawing contains classes that wrap the Graphics Device Interface+ (GDI+)

All drawing is performed with the Graphics class

Graphics is the WinForms equivalent to a device context

GDI+ Features Alpha Blending & Anti-Aliased 2D Drawing Gradient Brushes Universal Transformations & Floating Point

coordinates Support for more Image formats

BMP, GIF, JPEG, PNG, TIFF, ICON, WMF, EMF.

System.Drawing contains classes that wrap the Graphics Device Interface+ (GDI+)

All drawing is performed with the Graphics class

Graphics is the WinForms equivalent to a device context

GDI+ Features Alpha Blending & Anti-Aliased 2D Drawing Gradient Brushes Universal Transformations & Floating Point

coordinates Support for more Image formats

BMP, GIF, JPEG, PNG, TIFF, ICON, WMF, EMF.

Page 68: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

68

GDI+ Programming ModelGDI+ Programming Model

No more device contexts (DC) – Graphics Object

GDI+ is Stateless No more selecting pens and brushes into a DC Pens, Brushes, etc. are passed to each GDI+

drawing method

Graphic elements are no longer drawn with both Pen and Brush Draw methods use a Pen (eg. DrawRectangle) Fill methods use a Brush (eg. FillEllipse).

No more device contexts (DC) – Graphics Object

GDI+ is Stateless No more selecting pens and brushes into a DC Pens, Brushes, etc. are passed to each GDI+

drawing method

Graphic elements are no longer drawn with both Pen and Brush Draw methods use a Pen (eg. DrawRectangle) Fill methods use a Brush (eg. FillEllipse).

Page 69: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

69

GDI+ Programming ModelGDI+ Programming Model

Colors support Alpha Channels ARGB format

0x880000FF semi-transparent blue

A = 0x00 fully transparent A = 0xFF fully opaque

Rectangles, Points, etc. are classes r.Inflate( 5, 5 ); // Instead of InflateRect( r, 5,

5 );

Rectangles are defined differently! Left, Top, Width, Height.

Colors support Alpha Channels ARGB format

0x880000FF semi-transparent blue

A = 0x00 fully transparent A = 0xFF fully opaque

Rectangles, Points, etc. are classes r.Inflate( 5, 5 ); // Instead of InflateRect( r, 5,

5 );

Rectangles are defined differently! Left, Top, Width, Height.

Page 70: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

70

GDI+ Programming ModelGDI+ Programming Model

Obtaining a Graphics Object Passed to OnPaint methods in

PaintEventArgs Request one using

Graphics.FromHwnd( Handle ) If utilizing double-buffering, do not use

FromHwnd

Cleaning Up Dispose all GDI+ objects Dispose Graphics object if requested via

FromHwnd

Obtaining a Graphics Object Passed to OnPaint methods in

PaintEventArgs Request one using

Graphics.FromHwnd( Handle ) If utilizing double-buffering, do not use

FromHwnd

Cleaning Up Dispose all GDI+ objects Dispose Graphics object if requested via

FromHwnd

Page 71: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

71

Graphics ExampleGraphics Example

Graphics Tab in FCLSamples

Displays several graphics primitives SolidBrush, HatchBrush,

LinearGradientBrush, Pen, Bitmap

Also illustrates the FileInfo class

Graphics Tab in FCLSamples

Displays several graphics primitives SolidBrush, HatchBrush,

LinearGradientBrush, Pen, Bitmap

Also illustrates the FileInfo class

Page 72: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

72

ReflectionReflection

.NET equivalent to RTTI in Delphi (Win32)

System.Reflection namespace

Reflection is the process of inspecting the metadata generated for a module or assembly

Assembly GetModules

GetTypes GetMembers

.NET equivalent to RTTI in Delphi (Win32)

System.Reflection namespace

Reflection is the process of inspecting the metadata generated for a module or assembly

Assembly GetModules

GetTypes GetMembers

Page 73: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

73

Reflection ExampleReflection Example

Reflection Tab in FCLSamples

Displays information about a selected assembly

Reflection Tab in FCLSamples

Displays information about a selected assembly

Page 74: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

74

ReferencesReferences

Delphi for .NET Developers Guide Xavier Pacheco

Microsoft Development Network (MSDN)

Applied .NET Framework Development Jeffrey Richter

Programming Microsoft .NET Jeff Prosise

.NET Reflector by Lutz Roeder http://www.aisto.com/roeder/dotnet

Delphi for .NET Developers Guide Xavier Pacheco

Microsoft Development Network (MSDN)

Applied .NET Framework Development Jeffrey Richter

Programming Microsoft .NET Jeff Prosise

.NET Reflector by Lutz Roeder http://www.aisto.com/roeder/dotnet

Page 75: Ray Konopka Introduction to the Microsoft.NET Framework for Delphi Developers

75

The Finish LineThe Finish Line

Contact Information

Evaluation Forms

Questions & Answers

Contact Information

Evaluation Forms

Questions & Answers

Ray [email protected]://www.raize.com

Ray [email protected]://www.raize.com