Contents

Introduction

Part I. Background

1. Introduction to the .NET Framework

What Is .NET?

The .NET Framework

Features of the .NET Framework

Version Resiliency (The End of DLL Hell)

Trivial Deployment

Fine-Grained Security

Platform Neutrality

Concepts Important for This Book

Assemblies

Metadata

Reflection

Custom Attributes

Languages and Tools

C#

Visual Basic .NET

C++

IL Assembler (ILASM)

IL Disassembler (ILDASM)

Conclusion

2. Bridging the Two Worlds—Managed and Unmanaged Code

Managed Code Versus Unmanaged Code

Goals of Unmanaged Code Interaction

How Can Using Unmanaged Code Be Secure?

How Unmanaged Code Interacts with Managed Code

Platform Invocation Services (PInvoke)

Mixed-Mode Programming Using Managed Extensions to C++

Java User Migration Path to .NET (JUMP to .NET)

COM Interoperability

Unmanaged Code Isn’t Always the Answer

Conclusion

Part II. Using COM Components in .NET Applications

3. The Essentials for Using COM in Managed Code

Referencing a COM Component in Visual Studio .NET

Referencing a COM Component Using Only the .NET Framework SDK

Example: A Spoken Hello, World Using the Microsoft Speech API

The Type Library Importer

Interop Assemblies

Primary Interop Assemblies

Using COM Objects in ASP.NET Pages

Example: Using ADO in ASP.NET

Using COM+ Components

An Introduction to Interop Marshaling

Common Interactions with COM Objects

Creating an Instance

Calling Methods and Properties on a COM Object

Releasing a COM Object

Casting to an Interface (QueryInterface)

Error Handling

Enumerating Over a Collection

Passing the Right Type of Object

Late Binding and By-Reference Parameters

Using ActiveX Controls in .NET Applications

Referencing an ActiveX Control in Visual Studio .NET

Referencing an ActiveX Control Using Only the .NET Framework SDK

Example: A Simple Web Browser

Deploying a .NET Application That Uses COM

Example: Using Microsoft Word to Check Spelling

Conclusion

4. An In-Depth Look at Imported Assemblies

Converting the Library

Converting COM Data Types

Combining Several Types in One

Complex Types

Converting Methods and Properties

Methods

Properties

Special DISPIDs

Converting Interfaces

Converting Classes

Coclass Interfaces and Parameter/Field Replacement

The RCW Class

Converting Modules

Converting Structures

Converting Unions

Converting Enumerations

Converting Typedefs

Converting ActiveX Controls

Conclusion

5. Responding to COM Events

Callbacks in .NET

Callback Interfaces

Delegates

Events

Callbacks in COM

Handling COM Events in Managed Code

The Raw Approach

Type Library Importer Transformations

Using the Event Abstraction

Lazy Connection Point Initialization

Connectable Objects You Don’t Instantiate

Handling ActiveX Control Events in Managed Code

ActiveX Importer Transformations

Using ActiveX Events

Conclusion

6. Advanced Topics for Using COM Components

Do-It-Yourself Marshaling

C# Unsafe Code Versus System.Runtime.InteropServices APIs

Examples of Manipulating IntPtr Types

Threading and Apartments

Threading in COM Versus Threading in .NET

Choosing Your Apartment State in a .NET Application

Callbacks from a COM Object to a .NET Object

Troubleshooting an InvalidCastException

QueryInterface Failure

Casting to an RCW Class

Garbage Collection

Securing Unmanaged Calls

Using COM+ and DCOM Objects

Inheriting from COM Classes

Debugging into COM Components

Monitoring Performance

Conclusion

7. Modifying Interop Assemblies

How to Change an Assembly’s Contents

IL Assembler Syntax

Data Types

Passing Parameters

MarshalAsAttribute Syntax

Changing Data Types

Exposing Success HRESULTs

Arrays

Exposing SAFEARRAYs Differently

Adding Size Information to C-Style Arrays

Custom Attributes

Changing Attribute Contents

Marking Classes as Visual Basic Modules

Adding Back helpstring Information

Adding Custom Marshalers

Adding DISPIDs

Adding Back IDL Custom Attributes

Adding Methods to Modules

Conclusion

Part III. Using .NET Components in COM Applications

8. The Essentials for Using .NET Components from COM

A Sample .NET Component

Using a .NET Component in Visual Basic 6

Using a .NET Component in Unmanaged Visual C++

Using a .NET Component in Unmanaged JScript

Assembly Registration

The Type Library Exporter

.NET Class Interfaces

Interacting with a .NET Object

Creating a .NET Object

Calling Members on a .NET Object

Getting Rich Error Information

Enumerating Over a Collection

Deploying a COM Application That Uses .NET

Hosting Windows Forms Controls in Internet Explorer

Conclusion

9. An In-Depth Look at Exported Type Libraries

Converting the Assembly

Converting .NET Data Types

Converting Members

Methods

Properties

Fields

Events

Converting Interfaces

Converting Classes

Converting Value Types

Converting Enumerations

Conclusion

10. Advanced Topics for Using .NET Components

Avoiding Registration

Hosting the Common Language Runtime

Using the ClrCreateManagedInstance API

Hosting Windows Forms Controls in Any ActiveX Container

Working Around COM-Invisibility

Using Reflection to Invoke Static Members

Handling .NET Events

Unexpected Casing in Type Libraries

Advanced Shutdown Topics

Conclusion

Part IV. Designing Great .NET Components for COM Clients

11. .NET Design Guidelines for Components Used by COM Clients

Naming Guidelines

Names to Avoid

Namespaces and Assembly Names

Case Insensitivity

Usage Guidelines

Interfaces Versus Classes

Interfaces Versus Custom Attributes

Properties Versus Fields

Using Overloaded Methods

Using Constructors

Using Enumerations

Choosing the Right Data Types

Reporting Errors

Defining New Exception Types

General Guidelines

Exposing Enumerators to COM

Versioning

Library Identifiers (LIBIDs)

Class Identifiers (CLSIDs)

Interface Identifiers (IIDs)

Deployment

Testing Your Component from COM

Conclusion

12. Customizing COM’s View of .NET Components

Customizing Data Types

MarshalAsAttribute Basics

Customizing Arrays

Detecting Incorrect Use of MarshalAsAttribute

Customizing Data Flow

Customizing Structure Layout

Exposing Class Interfaces

Using Visual Basic .NET’s ComClassAttribute

Making APIs Invisible to COM

Customizing Registration

Choosing Your Own ProgID

Adding Arbitrary Registration Code

Providing Your Own GUIDs

Providing Your Own DISPIDs

Controlling Interface Derivation

Returning a Specific HRESULT

Disabling Type Library Marshaling of .NET Interfaces

Creating Multi-Cultured Methods

Using Optional Parameters in Any Language

Exposing .NET Objects As COM+ Objects

Conclusion

13. Exposing .NET Events to COM Clients

Exposing Events Without Using Extra CLR Support

Exposing Events Using Extra CLR Support

Using ComSourceInterfacesAttribute

Defining a Source Interface

The Phone Example Revisited

Visual Basic .NET’s ComClassAttribute

Design Guidelines

Example: Handling a .NET Windows Form’s Events from COM

The .NET Event Source

The COM Event Sink

Conclusion

14. Implementing COM Interfaces for Binary Compatibility

Getting Interface Definitions

Binary Compatibility with Visual Basic 6 Classes

Example: Implementing Office XP Smart Tag Interfaces

Running the Example Using Visual Studio .NET

Running the Example Using Only the .NET Framework SDK

Interface Implementation Shortcuts in Visual Studio .NET

Common Problems When Implementing COM Interfaces

Parameterized Properties

Interface Inheritance

Returning Specific HRESULTs

COM Interfaces with Default CCW Implementations

IUnknown

IDispatch

IMarshal

IProvideClassInfo

ISupportErrorInfo

IConnectionPointContainer

IObjectSafety

COM Interfaces Bridged to Different .NET Types

Conclusion

Part V. Designing Great COM Components for .NET Clients

15. Creating and Deploying Useful Primary Interop Assemblies

Primary Interop Assembly or Brand New Assembly?

Creating a Primary Interop Assembly

Generating a Strong Name

Handling References to Other Type Libraries

Naming the Output Assembly

Customizing the Metadata

Deploying and Registering a Primary Interop Assembly

Writing IDL That Produces Good Type Libraries

Referencing External Types

Defining Classes

Defining Structures, Enums, and Unions

Using Constants Appropriately

Avoiding Ignored Constructs

Registering the Type Library

What About ActiveX Controls?

Conclusion

16. COM Design Guidelines for Components Used by .NET Clients

General Guidelines

Using Array Parameters

Use SAFEARRAYs

Use Zero Lower Bounds

Use Single-Dimensional Arrays

Issues with VARIANT Parameters

Reporting Errors

Reserve Failure HRESULTs for Exceptional Circumstances

Don’t Return Success HRESULTs Other than S_OK

Set Additional Error Information

Adjusting Certain COM-Specific Idioms

Passing a Pointer to Anything

Passing Type Information

Passing Error Information

Managing Limited Resources

Threading and Apartment Guidelines

Providing Self-Describing Type Information

Naming Guidelines

Performance Considerations

Conclusion

17. Implementing .NET Interfaces for Type Compatibility

Class Interfaces

Interface Inheritance

Considerations for Visual C++ Programmers

Example: Implementing IDisposable to Clean Up Resources

Considerations for Visual Basic 6 Programmers

Example: Implementing IFormattable to Customize ToString

Example: Implementing IHashCodeProvider and IComparer to Use a COM Object as a Hashtable Key

Conclusion

Part VI. Platform Invocation Services (PInvoke)

18. The Essentials of PInvoke

Using PInvoke in Visual Basic .NET

Using PInvoke in Other .NET Languages

Choosing the Right Parameter Types

Strings

Arrays

Customizing Declare and DllImportAttribute

Choosing a Different Function Name

Customizing the Behavior of Strings

Changing the “Exact Spelling” Setting

Choosing a Calling Convention

Customizing Error Handling

Conclusion

19. Deeper Into PInvoke and Useful Examples

Callbacks

Using Delegates as Function Pointers

Invoking Unmanaged Function Pointers in Managed Code

Passing Structures

Customizing Structures with Custom Attributes

Using Formatted Classes

The Structure Inspector

Handling Variable-Length Structures and Signatures

Using C# Unsafe Code

Guarding Against Premature Garbage Collection

The System.GC.KeepAlive Method

The System.Runtime.InteropServices.HandleRef Value Type

Choosing the DLL Location or Name Dynamically

Example: Responding Immediately to Console Input

Example: Clearing the Console Screen

Example: Using CoCreateInstanceEx to Activate Remote COM Objects

Conclusion

Part VII. Advanced Topics

20. Custom Marshaling

Transforming Types Without Custom Marshaling

Custom Marshaling Architecture

The Custom Marshaler

The Consumers

The Adapter Objects

Marshalers, Marshalers, Marshalers!

Example: Marshaling Between .NET and COM Fonts

Example: Marshaling Between System.IO.Stream and IStream

Example: Marshaling With Arrays

Example: Providing Deterministic Release of Resources

Limitations

Conclusion

21. Manually Defining COM Types in Source Code

Using SDK Tools for Support

Manually Defining COM Interfaces

Important Custom Attributes

IUnknown-Only Interfaces

Dual Interfaces

Dispinterfaces

Interface Inheritance

Working With Language Limitations

Handy Customizations

Manually Defining Coclass Interfaces and Event Types

Manually Defining COM Structures

Manually Defining COM Enums

Manually Defining COM Classes

Defining Classes the Simple Way

Defining Classes the Hard Way

Avoiding the Balloon Effect

Conclusion

22. Using APIs Instead of SDK Tools

Generating an Assembly from a Type Library

Creating a Dynamic Assembly

Getting a Primary Interop Assembly

Saving the Dynamic Assembly

Generating a Type Library from an Assembly

Creating a Dynamic Type Library

Saving the Dynamic Type Library

Registering and Unregistering Assemblies

Installing and Uninstalling Serviced Components

Example: Using the APIs in an Interactive Application

The Importer

The Exporter

The Registrar

The COM+ Installer

The Windows Forms Client

Conclusion

Part VIII. Comprehensive Examples

23. Writing a .NET Arcade Game Using DirectX

The User’s Perspective

The Programmer’s Perspective

DirectX Interaction

The Game Class

Sounds and Pictures

Layers

Screens

The Actors

Using the Game Class

E-mail Attack—The Advanced Version

Conclusion

24. Writing .NET Visualizations For Windows Media Player

The COM Visualization API

Part IX. Appendices

A. System.Runtime.InteropServices Reference

The System.Runtime.InteropServices Namespace

The ArrayWithOffset Value Type

The AssemblyRegistrationFlags Enumeration

The AutomationProxyAttribute Custom Attribute

The BIND_OPTS Value Type

The BINDPTR Value Type

The CALLCONV Enumeration

The CallingConvention Enumeration

The CharSet Enumeration

The ClassInterfaceAttribute Custom Attribute

The ClassInterfaceType Enumeration

The CoClassAttribute Custom Attribute

The ComAliasNameAttribute Custom Attribute

The ComConversionLossAttribute Custom Attribute

The ComEventInterfaceAttribute Custom Attribute

The COMException Exception

The ComImportAttribute Pseudo-Custom Attribute

The ComInterfaceType Enumeration

The ComMemberType Enumeration

The ComRegisterFunctionAttribute Custom Attribute

The ComSourceInterfacesAttribute Custom Attribute

The ComUnregisterFunctionAttribute Custom Attribute

The ComVisibleAttribute Custom Attribute

The CONNECTDATA Value Type

The CurrencyWrapper Class

The DESCKIND Enumeration

The DESCUNION Value Type

The DispatchWrapper Class

The DispIdAttribute Custom Attribute

The DISPPARAMS Value Type

The DllImportAttribute Pseudo-Custom Attribute

The ELEMDESC Value Type

The ErrorWrapper Class

The EXCEPINFO Value Type

The ExporterEventKind Enumeration

The ExtensibleClassFactory Class

The ExternalException Exception

The FieldOffsetAttribute Pseudo-Custom Attribute

The FILETIME Value Type

The FUNCDESC Value Type

The FUNCFLAGS Enumeration

The FUNCKIND Enumeration

The GCHandle Value Type

The GCHandleType Enumeration

Caution.

The GuidAttribute Custom Attribute

The HandleRef Value Type

The ICustomAdapter Interface

The ICustomFactory Interface

The ICustomMarshaler Interface

The IDispatchImplAttribute Custom Attribute

The IDispatchImplType Enumeration

The IDLDESC Value Type

The IDLFLAG Enumeration

The IMPLTYPEFLAGS Enumeration

The ImportedFromTypeLibAttribute Custom Attribute

The ImporterEventKind Enumeration

The InAttribute Pseudo-Custom Attribute

The InterfaceTypeAttribute Custom Attribute

The InvalidComObjectException Exception

The InvalidOleVariantTypeException Exception

The INVOKEKIND Enumeration

The IRegistrationServices Interface

The ITypeLibConverter Interface

The ITypeLibExporterNameProvider Interface

The ITypeLibExporterNotifySink Interface

The ITypeLibImporterNotifySink Interface

The LayoutKind Enumeration

The LCIDConversionAttribute Custom Attribute

The LIBFLAGS Enumeration

The Marshal Class

The MarshalAsAttribute Pseudo-Custom Attribute

The MarshalDirectiveException Exception

The ObjectCreationDelegate Delegate

The OptionalAttribute Pseudo-Custom Attribute

The OutAttribute Pseudo-Custom Attribute

The PARAMDESC Value Type

The PARAMFLAG Enumeration

The PreserveSigAttribute Pseudo-Custom Attribute

The PrimaryInteropAssemblyAttribute Custom Attribute

The ProgIdAttribute Custom Attribute

The RegistrationServices Class

The RuntimeEnvironment Class

The SafeArrayRankMismatchException Exception

The SafeArrayTypeMismatchException Exception

The SEHException Exception

The STATSTG Value Type

The StructLayoutAttribute Pseudo-Custom Attribute

The SYSKIND Enumeration

The TYPEATTR Value Type

The TYPEDESC Value Type

The TYPEFLAGS Enumeration

The TYPEKIND Enumeration

The TYPELIBATTR Value Type

The TypeLibConverter Class

The TypeLibExporterFlags Enumeration

The TypeLibFuncAttribute Custom Attribute

The TypeLibFuncFlags Enumeration

The TypeLibImporterFlags Enumeration

The TypeLibTypeAttribute Custom Attribute

The TypeLibTypeFlags Enumeration

The TypeLibVarAttribute Custom Attribute

The TypeLibVarFlags Enumeration

The UCOMIBindCtx Interface

The UCOMIConnectionPoint Interface

The UCOMIConnectionPointContainer Interface

The UCOMIEnumConnectionPoints Interface

The UCOMIEnumConnections Interface

The UCOMIEnumMoniker Interface

The UCOMIEnumString Interface

The UCOMIEnumVARIANT Interface

The UCOMIMoniker Interface

The UCOMIPersistFile Interface

The UCOMIRunningObjectTable Interface

The UCOMIStream Interface

The UCOMITypeComp Interface

The UCOMITypeInfo Interface

The UCOMITypeLib Interface

The UnknownWrapper Class

The UnmanagedType Enumeration

The VARDESC Value Type

The VarEnum Enumeration

The VARFLAGS Enumeration

The System.Runtime.InteropServices.CustomMarshalers Namespace

The EnumerableToDispatchMarshaler Class

The EnumeratorToEnumVariantMarshaler Class

The ExpandoToDispatchExMarshaler Class

The TypeToTypeInfoMarshaler Class

The System.Runtime.InteropServices.Expando Namespace

B. SDK Tools Reference

TLBIMP.EXE

/asmversion

/delaysign

/keycontainer

/keyfile

/out

/namespace

/primary

/publickey

/reference

/strictref

/sysarray

/unsafe

/nologo

/silent

/verbose

/help and /?

TLBEXP.EXE

/names

/out

/nologo

/silent

/verbose

/help and /?

REGASM.EXE

/codebase

/regfile

/registered

/tlb

/unregister

/nologo

/silent

/verbose

/help and /?

AXIMP.EXE

/delaysign

/keycontainer

/keyfile

/out

/publickey

/source

/nologo

/silent

/verbose

/help and /?

REGSVCS.EXE

Warning

/appname

/c

/componly

/exapp

/extlb

/fc

/noreconfig

/parname

/reconfig

/tlb

/u

/nologo

/quiet

/help and /?

C. HRESULT to .NET Exception Transformations

D. .NET Exception to HRESULT Transformations

E. PInvoke Definitions for Win32 Functions

GDI32.DLL

KERNEL32.DLL

OLE32.DLL

SHELL32.DLL

USER32.DLL

F. Glossary

Index

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.135.63