3.4. Improved COM Interoperability

Many of the language enhancements we have looked at so far can greatly ease working with legacy code such as COM objects.

Let's look in more detail by adapting an example from Scott Hansleman's blog (www.hanselman.com/blog/CLRAndDLRAndBCLOhMyWhirlwindTourAroundNET4AndVisualStudio2010Beta1.aspx).

In Scott's example, the Microsoft Office API is used to open an existing text file. To see this example, add the following code and a reference to Microsoft.Office.Interop.Word, and then take a look at the IntelliSense for the Open() method (see Figure 3-1):

using Microsoft.Office.Interop.Word;

var WordApplication = new Microsoft.Office.Interop.Word.Application();
WordApplication.Visible = true;
object missing = System.Reflection.Missing.Value;
object file =@"c:	est.txt";
object visible = true;
object readOnly = false;

Document aDoc = WordApplication.Documents.Open(
    ref file,ref missing,ref readOnly,ref missing,
    ref missing,ref missing,ref missing,ref missing,
    ref missing,ref missing,ref missing,ref visible,
    ref missing,ref missing,ref missing,ref missing);

Figure 3.1. Working with Microsoft Office Interop is fun, honest

.NET optional and named parameters make this much easier:

var betterWay = WordApplication.Documents.Open(file, ReadOnly: true, Visible: true);
betterWay.Activate();

The new dynamic functionality (which we will look at shortly) can also make your code more readable by allowing you to infer many casting operations. For example, the compiler can now work out the type of object you are using (duck typing), allowing code such as

((Excel.Range) excel.Cells[1, 1]).Value2 = "Excell-ent!";

to be rewritten as

excel.Cells[1, 1].Value = "Excell-ent!";

It may not be very different, but it's much more readable.

3.4.1. We're Out of PIA

Another COM-related change worth mentioning is that you no longer need PIA (Primary Interop Assembly) files. In previous versions of Visual Studio, when a COM component was referenced, Visual Studio would create a PIA, an additional assembly to describe the COM DLL to the CLR.

Unfortunately, these PIA files could get pretty large, as they described every method of the COM object (including methods you weren't using). In VS2010, to stop Visual Studio from generating PIA files, simply set the Embed Interop Types property to True in Solution Explorer.

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

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