Introduction to the Microsoft .NET Framework for Delphi

Download Report

Transcript Introduction to the Microsoft .NET Framework for Delphi

Introduction to the
Microsoft .NET Framework for
Delphi Developers
Ray Konopka
Agenda
 Delphi and .NET
 What is the .NET Framework?
 .NET Framework Core Features
 Writing .NET Managed Code
 Programming in Delphi for .NET
2
Origins 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
3
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).
4
Migrating 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.
5
What is the .NET Framework?
CIL
CLS
ASP.NET
JIT
CUBS
GAC
CLR
BDP
VES
RTL.NET
GC
FCL
ADO.NET
VCL.NET
TLA
6
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
7
Common Language Runtime
 Serves as the execution engine for managed
applications

Activates objects

Performs security checks

Manages memory allocations and recovery

Executes code

etc.
8
Framework Class Library
 Object-oriented API for writing managed applications
 Defines more than 7,000 types

classes

interfaces

enumerations

delegates
9
.NET Framework Core Features
 Simplified & Consistent Programming Model
 Side-by-Side Execution and Versioning
 Simplified Deployment
 Multi-platform Support
 Programming Language Integration
 Garbage Collection
 Code Verification
 Consistent Error Handling
 Code Access Security
 Interoperability
10
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.
11
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
12
Simplified 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
13
Multi-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
14
Multi-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.
15
Language 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
16
CLR/CTS & CLS Relationship
 Each language supports

A subset of the CLR/CTS

A superset of the CLS
CLR/CTS
C#
Delphi
CLS
Others
17
Garbage 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.
18
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.
begin
List := TStringList.Create;
try
. . .
finally
List.Free; // Calls Dispose if implemented
end;
19
Code 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
20
Consistent 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
21
Security
 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
22
Interoperability
 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
23
Writing .NET Managed Code
 Managed Modules
 Assemblies
 Namespaces
 Manifests
 AppDomains
 Safe Code vs. Unsafe Code
24
Managed Modules
 An executable designed to be run by the CLR
 Typically has EXE, DLL, or NETMODULE extension
 Contains




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
25
Assemblies
 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
26
Assemblies 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
27
Namespaces
 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
28
Namespaces 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
29
Multi-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.
30
Manifests
 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
31
AppDomains
 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
32
AppDomain Boundaries
 Objects in one domain cannot be accessed by code in
another domain
 Data passed between domains must be marshaled
across the domain boundary
33
Safe 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
34
Unsafe 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)
35
Unsafe Code in Delphi
 Unsafe code accesses or works directly with memory
and cannot be verified to be safe

BlockRead

BlockWrite

Addr

Ptr

Absolute
36
Unsafe 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
var
NumList: TStringList;
procedure AddNumber(Caption: string; Value: Integer);
begin
NumList.AddObject( Caption, TObject( Value ) );
end;
37
Break
38
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
39
FCL Overview
 The Framework Class Library (FCL) is the objectoriented 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…
40
Applications
 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.
41
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
42
FCL 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
43
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
44
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
45
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
46
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.
47
.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
48
Reference & 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
49
Types Example
 DotNETTypes.dpr
 Lutz Roeder’s Reflector
50
Boxing
 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
procedure AddCustomer(List: ArrayList; C: TCustomer);
begin
// Box the value type and add the reference to List
List.Add( C );
end;
 A boxed value type can be unboxed as well, but
requires a type cast
 Boxing and unboxing does affect performance
51
Attributes
 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;
52
Exceptions
 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
53
Debugging/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
54
Math
 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
55
Math Example
 Math Tab in FCLSamples
 Demonstrates several functions defined in the Math
class
 Also illustrates exception handling

FormatException
56
Strings
 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
57
StringBuilder
 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
58
Strings Example
 Strings Tab in FCLSamples
 Illustrates several built-in operations available in
String class
 Also shows DateTime formatting and
StringBuilder class
59
Regular 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
60
Regular Expressions Example
 RegEx Tab in FCLSamples
 Splits up a path into its separate folders
61
File 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
62
File I/O Example
 File I/O Tab in FCLSamples
 Displays contents of selected file
63
Collections
 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
64
Collections Example
 Collections Tab in FCLSamples
 Counts the number of occurrences of words in a file
65
WinForms
 System.Windows.Forms namespace
 Basic Form class
 Standard WinForm Control hierarchy

Button

ListBox

CheckBox

TabControl

etc.
 Application class
66
Graphics
 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.
67
GDI+ 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).
68
GDI+ 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.
69
GDI+ 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
70
Graphics Example
 Graphics Tab in FCLSamples
 Displays several graphics primitives

SolidBrush, HatchBrush, LinearGradientBrush,
Pen, Bitmap
 Also illustrates the FileInfo class
71
Reflection
 .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
72
Reflection Example
 Reflection Tab in FCLSamples
 Displays information about a selected assembly
73
References
 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
74
The Finish Line
 Contact Information
Ray Konopka
[email protected]
http://www.raize.com
 Evaluation Forms
 Questions & Answers
75