C# Interop Implementation within .NET Framework
We can import libraries via Visual Studio 2005 via Add Reference option that provides us with the tab called COM and the list of all registered COM components available. Alternatively we can use TlbImp.exe. There is one important thing to remember, COM does not allow parameter overloading, so you need to pass all COM parameters and since they use references, null cannot be passed. In C# we need to create object variables and then pass them or the better way is to use Type.Missing field instead.
class Program
{
private static Object OptionalParamHandler = Type.Missing;
static void Main(string[] args)
{
Application NewExcelApp = new Application();
NewExcelApp.Worksheets.Add(ref OptionalParamHandler,
ref OptionalParamHandler, ref OptionalParamHandler,
ref OptionalParamHandler);
}
}
There are many tools that allow .NET Framework to work with COM
Name | Application Name |
---|---|
Type Library Importer | TlbImp.exe |
Type Library Exporter | TlbExp.exe |
Registry Editor | Regedit.exe |
Intermediate Language Disassembler | Ildasm.exe |
Assembly Registration Tool | Regasm.exe |
Example of COM usage within .NET Code
axAcroPDF1.LoadFile(@"SamplePDFDocument.pdf");
axAcroPDF1.Print();
If we need to handle COM Exceptions we need to employ RuntimeWrappedException class with following Properties
Name | Description |
---|---|
Data | Collection of key/value pairs |
HelpLink | Sets a link to the help file |
InnerException | Manages the Exception |
Message | Manages a message about exception |
Source | Manages or sets the name of the application |
StackTrace | Manages a string representation of the frames |
TargetSite | Manages the method that throws the current exception |
WrappedException | Manages the object that was wrapped by the RuntimeWrappedException |
There are several limitations in COM Interop .NET Framework
- No support for static or shared members
- COM does not allow parameterized constructors
- Limits in using inheritance
- Non Windows OS don’t have registries that limits .NET environments