Introduction

Welcome to .NET and COM: The Complete Interoperability Guide. First, to avoid any unsatisfied customers, let me make clear that this is not a book about domain names for Web sites! This is a book about two technologies that enable software developers to leverage existing software while taking advantage of the Microsoft .NET platform: COM Interoperability (often abbreviated as COM Interop), and Platform Invocation Services (often shortened to Platform Invoke, or simply PInvoke). Without them, widespread adoption of the Microsoft .NET platform would not be growing as quickly as it has been, because developers of .NET software projects would essentially be forced to start from scratch.

In observing the history of the .NET platform, from its initial announcement at the Microsoft Professional Developers Conference in the summer of 2000, to its two subsequent beta releases, to its 1.0 release at the beginning of 2002, I’ve seen many software developers ask a lot of questions about COM Interoperability and PInvoke! These are complex technologies, and they are especially important to understand as software developers evaluate what to do with large bodies of existing software. Interoperating with existing software is one of the first .NET topics a developer should master, because a pure .NET world can’t begin overnight (if at all). Even if you’re starting a new .NET software project from scratch, chances are that you’ll need to take advantage of interoperability somewhere—whether you need to use APIs exposed by the operating system or by third-party components.

I’ve seen other .NET books dedicate a chapter or two to COM Interoperability and/or PInvoke. These chapters sometimes provide a nice introduction to the technologies, but real-world applications almost never behave as nicely as canonical examples. Instead, they often require techniques that just can’t be covered in one or two chapters. Since I started working on the COM Interoperability team over two and a half years ago, I’ve always believed that an entire book on .NET’s interoperability services would be a must-have for the development community. Nobody else has stepped up to the challenge, so I went ahead and wrote it!

It was very hard for me to come up with a concise title for this book and still convey the broad array of topics covered. Let me explain the motivation behind the final title (chosen with the help of Shelley Kronzek). The “.NET and COM” part should be obvious, but the subtitle is chosen for the following reasons:

Complete—COM Interoperability and Platform Invocation Services are large topics, and this is a large book. I’ve made every effort to make this book as comprehensive as possible. It ended up being twice as long as I originally anticipated (and took me twice as long to write it), but I wanted to ensure that this book deserved to be described as “complete.” So I kept writing until the entire story was told.

Interoperability—Although the title doesn’t mention Platform Invocation Services, this book is about general interoperability with existing software. The focus of the book is with COM Interoperability, but I believe that this book also serves as a complete reference for Platform Invocation Services, a technology that doesn’t necessarily involve COM.

Guide—I wanted this book to be more than just a reference, but one that guides you step-by-step through the nuances, and one with an abundance of code examples. This includes some fun examples toward the end of the book, including a .NET arcade game! In addition, I wanted to capture and explain why these technologies are designed the way they are, something a plain reference book might not bother covering.

Who Should Read This Book?

This book is for anyone wanting to leverage existing pre-.NET software with .NET applications or components. I don’t expect you to know anything about .NET in advance, but the more background in .NET you have (and experience with one .NET language), the better off you’ll be. Most of the book assumes familiarity with either “raw COM” or COM through Visual Basic 6, but its concepts are explained in enough detail such that you should still get a lot out of the book without in-depth prior knowledge. Even if you (gasp!) don’t care about COM, you should still be able to get a lot out of Part VI and Appendix E, because they are targeted for reusing any existing software in .NET, even if it has nothing to do with COM.

To summarize, by reading this book, you learn how to:

• Leverage existing software (COM-based or not) in new .NET applications.

• Plug new .NET components into an existing COM architecture, taking advantage of .NET’s many features rather than continuing to program the COM way.

• Design your software to work well in both .NET and COM-based surroundings.

• Call any unmanaged APIs (such as Win32 functions) in any .NET language.

• Interoperate with COM+ and DCOM objects, as well as ActiveX controls.

If there’s one thing abundant in this book, it’s source code examples! .NET examples are provided in C#, Visual Basic .NET, and Visual C++ .NET, and should be easy to reproduce in any .NET language. Although most examples are printed in one language, every one is available for download from this book’s Web site in both C# and Visual Basic .NET, where applicable. COM Interoperability and PInvoke are language-independent at the core, but this book highlights features in all three languages that add value to interoperability in their own unique ways (and may guide your decision of which .NET language to use when interoperability is needed).

COM examples are provided in Visual C++ (version 6 or 7), IDL, and Visual Basic 6, to help the readers whose only exposure to COM is through Visual Basic. Throughout the book, special considerations for Visual Basic COM components are given. Many source code examples in these COM-based languages are also available for download.

Software Requirements

This book targets the final release of version 1.0 of the Microsoft .NET Framework and its Software Development Kit (SDK), and version 7.0 of Microsoft Visual Studio .NET.

The only software required—besides Microsoft Windows—is the freely downloadable .NET Framework SDK, available at msdn.microsoft.com. This book explains not only how to accomplish every task using nothing other than the free SDK, but also how to accomplish the tasks using Visual Studio .NET. If you already have Visual Studio .NET—the ultimate development tool providing the rapid application development (RAD) experience for developing .NET applications—you’ll appreciate the extra content covering some of its features as they relate to the examples.

Some of the examples in this book use Microsoft COM-based technologies to demonstrate concepts in a realistic setting. Most of these are freely downloadable, such as the Microsoft Speech SDK, the Windows Media Player SDK, and the Microsoft DirectX SDK. Downloading instructions appear with the examples. A few examples use Microsoft Office, but having this software is not required to understand the concepts.

How This Book is Organized

This book is organized in nine parts. The heart of the book is Parts II through V, which cover all angles of the COM Interoperability picture. With COM Interoperability, there are two basic directions of interaction: a .NET component calling a COM component and a COM component calling a .NET component. Parts II and III cover the client side of both directions for the application developer, and parts IV and V cover the server side of both directions for the component developer. This organization is summarized in the following diagram:

Figure IN.1. A conceptual overview of Parts II-V.

Image

This picture is a simplification, because it does not mean that the topics covered only apply to simple client/server interaction; the “clients” pictured could actually be components themselves in a long chain of a multi-tiered application. Regardless of an application’s structure or what pieces of an application are made up of .NET and COM components, the themes remain the same unless called out otherwise in these chapters.

Material specific to COM+ components can be found in the following places:

• Using COM+ components in .NET applications—Chapter 6

• Custom attributes for writing .NET serviced components—Chapter 12

• Programmatically installing .NET components in the COM+ Component Services Explorer—Chapter 22

• Manually installing .NET components in the COM+ Component Services Explorer—Appendix B

Here’s a summary of all nine parts of the book:

Part I. Background

Besides containing the obligatory overviews of the .NET Framework and COM, this part of the book covers a handful of concepts that are especially important for the remainder of the book.

Chapter 1, “Introduction to the .NET Framework,” explains the .NET Framework’s and Common Language Runtime’s position in the broad .NET initiative, and pays special attention to two .NET features: reflection and custom attributes. The chapter ends with an overview of C#, Visual Basic .NET, and Visual C++ .NET, the three .NET languages given focus in this book.

Chapter 2, “Bridging the Two Worlds—Managed and Unmanaged Code,” is an overview of .NET interoperability services, introducing the four main mechanisms for leveraging existing code in .NET applications: Platform Invocation Services, Mixed-Mode Programming in Visual C++ .NET, Java User Migration Path to .NET (JUMP to .NET), and last but not least, COM Interoperability.

Part II. Using COM Components in .NET Applications

This is the largest part of the book, and it covers the topics that most .NET developers need to know first.

Chapter 3, “The Essentials for Using COM in Managed Code,” covers the information necessary to use most COM components and ActiveX controls and most of their APIs in .NET applications.

Chapter 4, “An In-Depth Look at Imported Assemblies,” explains exactly how COM type information gets translated into .NET type information. This chapter arms you with the knowledge to handle the fact that the source code required to use COM components in a .NET language sometimes doesn’t resemble the source code using them in COM-based languages (and perhaps the examples in COM components’ .NET-unaware documentation).

Chapter 5, “Responding to COM Events,” discusses the .NET and COM event models, how the Common Language Runtime integrates these two disparate mechanisms, and how to respond to events raised by COM components and ActiveX controls.

Chapter 6, “Advanced Topics for Using COM Components,” covers a handful of advanced topics, including debugging, troubleshooting common problems, DCOM, security, threading models, do-it-yourself marshaling, and more.

Chapter 7, “Modifying Interop Assemblies,” discusses how to use .NET Framework SDK tools to disassemble, modify, and reassemble components containing the .NET view of COM APIs. This is sometimes necessary to make COM components usable in .NET, and other times it’s a big help in improving their ease of use.

Part III. Using .NET Components in COM Applications

This part of the book covers tasks that are the opposite of the tasks covered in Part II. Using .NET components in a COM-based language is not as common as using COM components in a .NET language, but is still a topic of great importance.

Chapter 8, “The Essentials for Using .NET Components from COM,” is the opposite of Chapter 3. This chapter explains the information necessary to use most .NET components in COM applications. It also demonstrates how to host .NET components and Windows Forms controls inside Internet Explorer and write script that uses them.

Chapter 9, “An In-Depth Look at Exported Type Libraries,” is the opposite of Chapter 4 and explains exactly how .NET type information gets translated into COM type information. Using .NET APIs in COM often differs significantly from using them in .NET languages. Since it’s unlikely that most .NET components will be documented from COM’s perspective, this chapter fills in the gaps and removes the need for such documentation.

Chapter 10, “Advanced Topics for Using .NET Components,” the opposite of Chapter 6, covers the advanced topics of using .NET components in COM applications. This includes tricks for using .NET APIs that are supposed to be invisible to COM, using .NET components without registration, using reflection to invoke static members, and some advanced shutdown-related APIs exposed by the Common Language Runtime.

Part IV. Designing Great .NET Components for COM Clients

This part of the book complements Part II, focusing on the .NET components that might be used by COM clients.

Chapter 11, “.NET Design Guidelines for Components Used by COM Clients,” explains how to design your .NET components while keeping the ease-of-use for potential COM clients in mind, so your clients won’t have to buy a copy of this book to figure out how to use the components from COM!

Chapter 12, “Customizing COM’s View of .NET Components,” covers the long list of custom attributes provided by COM Interoperability, so you can customize the way your .NET components are exposed to COM. It also introduces custom attributes provided by .NET Enterprise Services that enable you to take advantage of component services available for COM+ objects.

Chapter 13, “Exposing .NET Events to COM Clients,” discusses how to take extra steps to ensure that any events you raise can be handled naturally from COM. Unless you follow the procedures explained in this chapter, .NET events are essentially unusable from COM’s perspective.

Chapter 14, “Implementing COM Interfaces for Binary Compatibility,” discusses binary compatibility, and the subtleties that can arise when .NET classes implement COM interfaces. It also discusses the interfaces automatically implemented when .NET components are exposed to COM, and how to customize their behavior.

Part V. Designing Great COM Components for .NET Clients

This part of the book complements Part III, focusing on the COM components that might be used by .NET clients.

Chapter 15, “Creating and Deploying Useful Primary Interop Assemblies,” discusses ways of creating and distributing type information for existing COM components that maximize their use in .NET. It also discusses cosmetic changes that greatly improve a COM component’s .NET usability with minimal impact.

Chapter 16, “COM Design Guidelines for Components Used by .NET Clients,” is analogous to Chapter 11, and explains how to design new COM components (or redesign old ones) so they can be used seamlessly as if they were “pure” .NET components.

Chapter 17, “Implementing .NET Interfaces for Type Compatibility,” is analogous to Chapter 14, and discusses the subtleties and limitations (especially for Visual Basic 6 users) in writing COM classes that implement .NET interfaces.

Part VI. Platform Invocation Services (PInvoke)

This part of the book serves as a complete reference for Platform Invocation Services.

Chapter 18, “The Essentials of PInvoke,” covers the basic use of PInvoke in C# and Visual Basic .NET. It instructs how to create correct PInvoke signatures and how to customize them, as well as the data type transformations that must be understood in order to be successful.

Chapter 19, “Deeper Into PInvoke and Useful Examples,” covers a handful of important topics such as callbacks, structure marshaling, interaction with garbage collection, and C# unsafe code. It also includes several examples using Win32 APIs to accomplish common tasks that are not possible with .NET Framework APIs alone.

Part VII. Advanced Topics

These chapters cover advanced topics in COM Interoperability used in both directions of COM and .NET interaction.

Chapter 20, “Custom Marshaling,” describes how to write a custom marshaler that controls how COM types are exposed to .NET, and vice-versa.

Chapter 21, “Manually Defining COM Types in Source Code,” shows how to create the same type definitions emitted by the type library importer in any high-level .NET language. It also covers ways to customize and improve upon these definitions.

Chapter 22, “Using APIs Instead of SDK Tools,” covers a handful of APIs that enable you to programmatically do the same tasks done by several of the .NET Framework SDK tools, and ends with source code for a large graphical application that takes advantage of all these APIs.

Part VIII. Comprehensive Examples

This is the fun part of the book, containing the full source code for two large examples that use COM Interoperability and Platform Invocation Services. Although the examples are meant to be entertaining, the same concepts can be applied to more serious business applications.

Chapter 23, “Writing a .NET Arcade Game Using DirectX,” is a large example of using COM in a .NET application to create a video game. This example demonstrates the concepts of Part II, Part VI, and Chapter 21.

Chapter 24, “Writing .NET Visualizations for Windows Media Player,” is an example of writing .NET components to be used by a COM client that knows nothing about .NET, all to the beat of some music in Windows Media Player. This example demonstrates the concepts of Part IV and Chapter 21.

Part IX. Appendices

Appendix A, “System.Runtime.InteropServices Reference,” covers every type and member in the System.Runtime.InteropServices namespace in depth and in alphabetical order.

Appendix B, “SDK Tools Reference,” describes the COM Interoperability-related command-line utilities that ship with the .NET Framework SDK, and all of their options.

Appendix C, “HRESULT to .NET Exception Transformations,” contains a list that completely defines how HRESULT values (COM error codes) are transformed into .NET exception types. For convenience, the list appears twice—sorted by HRESULT values and sorted by exception name.

Appendix D, “.NET Exception to HRESULT Transformations,” is the opposite of Appendix C and contains a list that displays how exception types defined in the .NET Framework are exposed to COM as HRESULT values. For convenience, the list appears twice—sorted by HRESULT values and sorted by exception name.

Appendix E, “PInvoke Definitions for Win32 Functions,” contains a list of PInvoke method signatures that, once you define any necessary parameter types, enables a .NET program to call just about any Win32 API appearing in one of five core Windows DLLs—KERNEL32.DLL, GDI32.DLL, OLE32.DLL, SHELL32.DLL, and USER32.DLL.

Appendix F, “Glossary,” defines common terms used throughout this book.

Conventions Used in This Book

To bring special attention to certain material in a chapter, or to make some material easier to follow, the following special elements appear in this book:

• FAQ sidebars

• Digging Deeper sidebars

• Tips

• Cautions

Tip

Tips are bits of information that can help you in real-world situations. They often offer shortcuts or alternative approaches to make a task easier, quicker, or safer.

Caution

Cautions alert you to an action or condition that can lead to an unexpected or unpredictable result—such as a loss of data—and tell you how to avoid or fix the results.

This book also uses various typesetting styles to distinguish between explanatory and instructional text and text you enter:

• Onscreen messages, program code, commands, filenames, and URLs appear in a special monospaced font.

Placeholders—words that you replace with actual code—are indicated with monospace italic.

• Some lines of code may appear in monospace bold, for emphasis.

For more information, please visit the book’s Web site at http://www.samspublishing.com. Type 067232170x in the Search box and click Search.

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

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