Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Pro CSharp 2008 And The .NET 3.5 Platform [eng]

.pdf
Скачиваний:
78
Добавлен:
16.08.2013
Размер:
22.5 Mб
Скачать

1312 APPENDIX A COM AND .NET INTEROPERABILITY

[out, retval] long* pRetVal); [id(0x60020005)]

HRESULT Subtract( [in] long x, [in] long y, [out, retval] long* pRetVal);

};

Notice that the _DotNetCalc interface not only describes the Add() and Subtract() methods, but also exposes the members inherited by System.Object. As a rule, when you expose a .NET class type to COM, all public methods defined up the chain of inheritance are also exposed through the autogenerated class interface.

Building a Visual Basic 6.0 Test Client

Now that the .NET assembly has been properly configured to interact with the COM runtime, you can build some COM clients. You can create a simple VB6 Standard *.exe project type (named VB6DotNetClient) and set a reference to the new generated type library (see Figure A-18).

Figure A-18. Referencing your .NET server from VB6

As for the GUI front end, keep things really simple. A single Button object will be used to manipulate the DotNetCalc .NET type. Here is the code (notice that you are also invoking ToString(), defined by the _Object interface):

Private Sub btnUseDotNetObject_Click()

'Create the .NET object.

Dim c As New DotNetCalc

MsgBox c.Add(10, 10), , "Adding with .NET"

'Invoke some members of System.Object.

MsgBox c.ToString, , "ToString value"

End Sub

Source Code The VB6DotNetClient application is included under the Appendix A subdirectory.

APPENDIX A COM AND .NET INTEROPERABILITY

1313

So, at this point you have seen the process of building .NET applications that talk to COM types and COM applications that talk to .NET types. Again, while there are many additional topics regarding the role of interop services, you should be in a solid position for further exploration.

Summary

.NET is a wonderful thing. Nevertheless, managed and unmanaged code must learn to work together for some time to come. Given this fact, the .NET platform provides various techniques that allow you to blend the best of both worlds.

A major section of this appendix focused on the details of .NET types using legacy COM components. As you have seen, the process begins by generating an assembly proxy for your COM types. The RCW forwards calls to the underlying COM binary and takes care of the details of mapping COM types to their .NET equivalents.

The appendix concluded by examining how COM types can call on the services of newer .NET types. As you have seen, this requires that the creatable types in the .NET assembly are registered for use by COM, and that the .NET types are described via a COM type library.

A P P E N D I X B

Platform-Independent .NET

Development with Mono

This appendix introduces you to the topic of cross-platform C# and .NET development using an open source implementation of .NET named Mono (in case you are wondering about the name, “Mono” is a Spanish word for monkey, as in “code monkey,” a term often used to describe individuals who author code for a living). In this appendix, you will come to understand the role of the Common Language Infrastructure (CLI), the overall scope of Mono, and numerous Mono development tools. Given your work over the course of this text, you will be in a perfect position to dig further into Mono development as you see fit at the conclusion of this appendix.

Note If you require a detailed treatment of cross-platform .NET development, I recommend picking up a copy of

Cross-Platform .NET Development: Using Mono, Portable .NET, and Microsoft .NET by Mark Easton and Jason King (Apress, 2004).

The Platform-Independent Nature of .NET

Historically speaking, when programmers made use of a Microsoft development language or programming framework (VB6, MFC, COM, ATL, etc.), they had to resign themselves to building software that (by and large) only executed on the Windows family of operating systems. Many .NET developers, accustomed to previous Microsoft development options, are quite surprised when they learn that .NET is platform-independent. But it’s true. You can compile and execute .NET assemblies on operating systems other than Microsoft Windows.

Using open source .NET implementations such as Mono, Mac OS X, Solaris, AIX, as well as numerous flavors of Unix/Linux can be happy homes for your .NET binaries. Furthermore, Mono provides an installation package for (surprise, surprise) Microsoft Windows. Thus, it is possible to build and run .NET assemblies on the Windows operating system, without ever installing the Microsoft .NET Framework 3.5 SDK or the Visual Studio 2008 IDE.

Note Be aware, however, that if you are only interested in building .NET software for the Windows operating system, the Microsoft .NET Framework 3.5 SDK and Visual Studio 2008 provide the best options for doing so.

Even after developers are made aware of .NET code’s cross-platform capabilities, they often assume that the scope of platform-independent .NET development is limited to little more than

1315

1316 APPENDIX B PLATFORM-INDEPENDENT .NET DEVELOPMENT WITH MONO

“Hello World” console applications. In reality, however, you can build production-ready assemblies that make use of ADO.NET, Windows Forms (in addition to alternative GUI toolkits such as GTK# and Cocoa#), ASP.NET, and XML web services using many of the core namespaces and language features you have seen used throughout this text.

The way in which .NET’s cross-platform nature is achieved is different from the approach taking by Sun Microsystems with the handling of the Java programming platform. Unlike Java, Microsoft itself does not provide installers of .NET for Mac, Linux, etc. Rather, Microsoft has released a set of formalized specifications that other entities can use as a road map for building

.NET distributions for their platform(s) of choice. Collectively, these specifications are termed the CLI.

The Role of the CLI

As briefly mentioned in Chapter 1, when C# and the .NET platform were released to the world at large, Microsoft Corporation submitted two formal specifications to ECMA (European Computer Manufacturers Association). Once approved, these same specifications were submitted to the International Organization for Standardization (ISO) and ratified shortly thereafter.

So, why on earth should you care? Again, these two specifications provide a road map for other companies, developers, universities, and other such organizations to build their own custom distributions of the C# programming language and the .NET platform. The two specifications in question are

ECMA-334, which defines the syntax and semantics of the C# programming language

ECMA-335, which defines numerous details of the .NET platform, collectively termed the

Common Language Infrastructure

ECMA-334 tackles the lexical grammar of C# in an extremely rigorous and scientific manner (as you might guess, this level of detail is quite important to those implementing their own C# compiler). However, ECMA-335 is the meatier of the two specifications, so much so that it has been broken down into six partitions, as listed in Table B-1.

Table B-1. ECMA-335 Specification Partitions

ECMA-335 Partition

Meaning in Life

Partition I: Architecture

Describes the overall architecture of the CLI, including the rules of

 

the Common Type System, the Common Language Specification,

 

and the mechanics of the .NET runtime engine.

Partition II: Metadata

Describes the details of the .NET metadata format.

Partition III: CIL

Describes the syntax and semantics of the common intermediate

 

language (CIL) programming language.

Partition IV: Libraries

Gives a high-level overview of the minimal and complete class

 

libraries that must be supported by a CLI-compatible .NET

 

distribution.

Partition V: Binary Formats

Provides details of the portable debug interchange format

 

(CILDB). Portable CILDB files provide a standard way to

 

interchange debugging information between CLI producers

 

and consumers.

Partition VI: Annexes

Represents a collection of “odds and ends” examining topics such

 

as class library design guidelines and the implementation details

 

of a CIL compiler.

 

 

APPENDIX B PLATFORM-INDEPENDENT .NET DEVELOPMENT WITH MONO

1317

The point of this appendix is not to dive into the details of the ECMA-334 and ECMA-335 speci- fications—nor are you required to know the ins-and-outs of these documents to understand how to build platform-independent .NET assemblies. However, if you are interested, you can download both of these specifications for free from the ECMA website (http://www.ecma-international.org/ publications/standards).

Note Even if you have no interest in the cross-platform aspects of .NET, I would recommend reading the ECMA-334 and ECMA-335 specifications, as they provide a number of insights regarding the C# language and the .NET platform.

The Mainstream CLI Distributions

To date, there are two mainstream implementations of the CLI, beyond Microsoft’s CLR, Microsoft Silverlight, and the Microsoft NET Compact Framework (see Table B-2).

Table B-2. Mainstream .NET CLI Distributions

CLI Distribution

Supporting Website

Meaning in Life

Mono

http://www.mono-project.com

Mono is an open source and commercially

 

 

supported distribution of .NET sponsored

 

 

by Novell Corporation.

 

 

Mono is targeted to run on many popular

 

 

flavors of Unix/Linux, Mac OS X, Solaris,

 

 

and Windows.

Portable .NET

http://www.dotgnu.org

Portable .NET is distributed under the GNU

 

 

General Public License.

 

 

As the name implies, Portable .NET intends

 

 

to function on as many operation systems

 

 

and architectures as possible, including

 

 

many esoteric platforms such as BeOS,

 

 

Microsoft Xbox, and Sony PlayStation (no,

 

 

I’m not kidding about those last two!).

 

 

 

Each of the CLI implementations shown in Table B-2 provide a fully function C# compiler, numerous command-line development tools, a global assembly cache (GAC) implementation, sample code, useful documentation, and dozens of assemblies that constitute the base class libraries.

Beyond implementing the core libraries defined by Partition IV of ECMA-335, Mono and Portable .NET provide Microsoft-compatible implementations of mscorlib.dll, System.Data.dll,

System.Web.dll, System.Drawing.dll, and System.Windows.Forms.dll (among many others). Furthermore, the Mono and Portable .NET distribution also ship with a handful of assemblies specifically targeted at Unix/Linux and Mac OS X operating systems. For example, Cocoa# is a

.NET wrapper around the Mac OX GUI toolkit, Cocoa. In this appendix, I will not dig into these OSspecific binaries and instead stay focused on making use of the OS-agonistic programming stacks.

Note Portable .NET will not be examined in this appendix. However, it is important to know that Mono is not the only platform-independent distribution of the .NET platform available today. I would recommend you take some time to play around with Portable .NET in addition to the Mono platform.

1318 APPENDIX B PLATFORM-INDEPENDENT .NET DEVELOPMENT WITH MONO

The Scope of Mono

Given that Mono is an API built on existing ECMA specifications that originated from Microsoft Corporation, you would be correct in assuming that Mono is playing a constant game of catch up as newer versions of Microsoft’s .NET platform are released. At the time of this writing, Mono is compatible with C# 2.0/.NET 2.0. Therefore, you are able to build ASP.NET websites, Windows Forms applications, database-centric applications using ADO.NET, and (of course) simple console applications.

Currently, Mono is not completely compatible with C# 2008 or .NET 3.0/3.5. What that means is your Mono applications are currently unable (again, at the time of this writing) to make use of the following APIs:

Windows Presentation Foundation (WPF)

Windows Communication Foundation (WCF)

Windows Workflow Foundation (WF)

The LINQ APIs

C# 2008–specific language features

Rest assured that the Novell-based Mono team is already working on incorporating these APIs and C# 2008 programming features into the Mono project. In fact, many C# 2008 language features are already part of the latest build of Mono (1.2.5), including implicit typing, object initialization syntax, and anonymous types.

Note The C# 2008 support is enabled by passing the -langversion:linq option to the Mono C# compiler.

In addition, the Olive project, which plans to bring WPF, WCF, and WF into the Mono platform, is currently underway. LINQ support, you will be happy to know, is also moving along nicely.

Note The Mono website maintains a page that describes the overall road map of Mono’s functionality and plans for future releases (http://www.mono-project.com/plans).

The final point of interest regarding the Mono feature set is that much like Microsoft’s .NET Framework 3.5 SDK, the Mono SDK supports a number of .NET programming languages. While this appendix will stay focused on C#, Mono does provide support for a Visual Basic .NET–compatible compiler, as well as support for many other .NET-aware programming languages.

Obtaining and Installing Mono

With this basic primer behind us, we can turn our attention to obtaining and installing Mono on your operating system of choice. Navigate to the Mono website (http://www.mono-project.com) and click the Download Now button to navigate to the downloads page. Here you are able to download a variety of installers.

I am assuming that you are installing the Windows distribution of Mono (note that installing Mono will not interfere whatsoever with any existing installation of Microsoft .NET or Visual Studio IDEs). Begin by downloading the current stable Mono installation package for Microsoft Windows and saving the setup program to your local hard drive.

APPENDIX B PLATFORM-INDEPENDENT .NET DEVELOPMENT WITH MONO

1319

Note If you are installing Mono on a Linux-based OS, I’d suggest doing so using the Linux Installer for x86 package, which will allow you to install Mono using a friendly setup wizard (rather than forcing you to install Mono from source; be sure to read the supplied installation notes on the Mono website). If you make use of the Mac OS X Mono installer, the installation process will be identical to installing other Mac-based software.

When you run the setup program, you will be given a chance to install a variety of Mono development tools beyond the expected base class libraries and the C# programming tools. Specifically, the installer will ask you whether you wish to include GTK# (an open source .NET GUI API based on the Linux-centric GTK toolkit) and XSP (a stand-alone web server, similar to Microsoft’s webdev. webserver.exe). In this appendix, I will assume you have opted for a full installation, so be sure you have checked each option in the setup script (see Figure B-1).

Figure B-1. Select all options for your Mono installation.

All of the remaining options of the Mono installer can be left using the suggested default values.

Examining Mono’s Directory Structure

By default, Mono installs under C:\Program Files\Mono-<version> (at the time of this writing, the latest and greatest version of Mono is 1.2.5). Beneath that root you will find a number of subdirectories (see Figure B-2).

For this appendix, you need only concern yourself with the following subdirectories:

bin: Contains a majority of the Mono development tools including the C# command-line compilers

lib\mono\gac: The location of Mono’s global assembly cache

1320 APPENDIX B PLATFORM-INDEPENDENT .NET DEVELOPMENT WITH MONO

Figure B-2. The Mono directory structure

Given that you run the vast majority of the Mono development tools from the command line, you will want to make use of the Mono command prompt, which automatically recognizes each of the command-line development tools. The command prompt (which is functionally equivalent to the Visual Studio 2008 command prompt) can be activated by selecting Start All Programs Mono <version> For Windows menu option. To test your installation, enter the following command and press the Enter key:

mono --version

If all is well, you should see various details regarding the Mono runtime environment (see Figure B-3).

Figure B-3. The Mono runtime environment

APPENDIX B PLATFORM-INDEPENDENT .NET DEVELOPMENT WITH MONO

1321

The Mono Development Tools

Similar to the Microsoft’s CLR distribution, Mono ships with a number of managed compilers:

mcs/gmcs: The C# compilers

vbnc: The Mono Visual Basic compiler

booc: The Boo language compiler

ilasm/ilasm2: The Mono CIL compilers

While this appendix focuses only on the C# compilers, again recall that the Mono project does ship with a Visual Basic .NET compiler. While this tool is currently under development, the intended goal is to bring the world of human-readable keywords (Inherits, MustOverride, Implements, etc.) to the world of Unix/Linux and Mac OS X (see http://www.mono-project.com/Visual_Basic for more detail).

Boo is an object-oriented statically typed programming language for the CLI that sports a Python-based syntax. Check out http://boo.codehaus.org for more details on the Boo programming language. Finally, as you might have guessed, ilasm/ilasm2 are the Mono CIL compilers (the second of which supports .NET 2.0 programming constructs).

Working with the C# Compilers

The first C# compiler for the Mono project was mcs, and it’s fully compatible with C# 1.1 (in fact, mcs is written in C#). Like the Microsoft C# command-line compiler (csc.exe), mcs supports response files, a /target: flag (to define the assembly type), an /out: flag (to define the name of the compiled assembly), and a /reference: flag (to update the manifest of the current assembly with external dependencies). You can view all the options of mcs using the following command:

mcs -?

The “generic mono C# compiler,” or gmcs, as the name implies, is a version of mcs that has support for .NET 2.0–specific C# language features (generics, covariance/contravariance, nullable types, partial types, anonymous methods, etc.) and references the .NET 2.0–based base class libraries. The command-line options of gmcs are identical to mcs, which you can verify with the following command:

gmcs -?

Given the presence of two C# compilers, you might naturally assume that only gmcs can be used to build .NET applications that make use of the C# 2.0 language enhancements. In reality, mcs was the first of the two compilers to support 2.0 features, which were perfected and ported to gmcs. The code examples in this appendix can be compiled using either of the two C# compilers, so pick your poison.

Microsoft-Compatible Mono Development Tools

In addition to various managed compilers, Mono ships with various development tools that are functionally equivalent to tools found in the Microsoft .NET SDK (some of which are identically named). Table B-3 enumerates the mappings between some of the commonly used Mono/Microsoft .NET utilities.