Reader Level:
ARTICLE

Calling a COM Component From C# (Late Binding)

Posted by Pramod Singh Articles | Visual C# January 08, 2001
This code sample shows how to call a COM component in .NET framework using C#.
  • 0
  • 0
  • 95544
Download Files:
 

Tools Used: .NET SDK

The .NET framework is a natural progression from COM since the two share many central themes including component reuse and language neutrality. For backward compatibility, COM Interop provides access to existing COM components without requiring that the original component be modified. When a .NET Framework developer wants to incorporate COM code into a managed application, he or she imports the relevant COM types by using a COM Interop utility for that purpose. Once imported, the COM types are ready to use. This is early binding , but some time u require late binding of object. You can do that too in .NET ie you can call COM object via late binding by using Namespace Reflection.

In this application we are trying to call Excel and make it visible by using late binding.

For late binding the Type Class of Reflectionb is used. This Type class has many methos to get the COM object like the one which we have used is GetTypeFromProgID("Application") , this method get the COM ID from the System Registry and then by using the STATIC class member of Activator.CreateInstance() we create a new instance of the COM object.

To invoke the methods, function and Properties of the COM object we have to use the InvokeMethod() of the Type object with proper settings, this methos takes many arguments of which the inportant one is the methos type ex property (get or set)in example we have used a set property for Excel.Visible to make the Excel application visible.

We will try to call Excel application from .NET environment. This is a late binding application for early binding you have to use RCW(RunTime Callable Wrraper) of COM Object  to do so use command line tool tblimp.

ex. c:\> tblimp <name.dll> /out:<name.dll>

Download the attachment. This is a console application. Here is the code which calls excel exe. 

//Variable
Type excel;
object[] parameter= new object[1];
object excelObject;
try
{
//Get the excel object
excel = Type.GetTypeFromProgID("Excel.Application");
//Create instance of excel
excelObject = Activator.CreateInstance(excel);
//Set the parameter whic u want to set
parameter[0] = true;
//Set the Visible property
excel.InvokeMember("Visible", BindingFlags.SetProperty, null, excelObject, parameter);
}
catch(Exception e)
{
Console.WriteLine("Error Stack {0} ", e.Message) ;
}
finally
{
//When this object is destroyed the Excel application will be closed
//So Sleep for sometime and see the excel application
Thread.Sleep(5000);
//Relaese the object
//GC.RunFinalizers()
}

Article Extensions
Contents added by vahini narra on Jul 29, 2013
  
Zurück

Late Binding and Polymorphism in C#


Late binding

The decision to which version of the method to invoke cannot be made at compile time. That decision must be deferred and made at runtime. This is sometimes referred to as late binding.

Example

using System;
using System.Collections;
using System.Text;

namespace VirtualMethods
{
    public class MyControl
    {
        // These members are protected and thus visible
        // to derived class methods. We'll examine this
        // later in the chapter

        protected int top;
        protected int left;

        // Constructor takes two integers to
        // fix location on the console

        public MyControl(int top, int left)
        {
            this.top = top;
            this.left = left;
        }

        // Simulates drawing the window
        public virtual void DrawWindow()
        {
            Console.WriteLine("MyControl: drawing Control at {0}, {1}",
            top, left);
        }
    }

    // ListBox derives from MyControl
    public class ListBox : MyControl
    {
        // Fields
        private string listBoxContents;

        // Constructor adds a parameter
        public ListBox(
            int top,
            int left,
            string contents): base(top, left)  // Call base constructor
        {
            listBoxContents = contents;
        }
  
        // An overridden version (note keyword) because in the
        // derived method we change the behavior

        public override void DrawWindow()
        {
            base.DrawWindow();  // Invoke the base method
            Console.WriteLine("Writing string to the listbox:
           {0}",listBoxContents);
        }
    }

    // Button derives from MyControl
    public class Button : MyControl
    {
        public Button(
            int top,
            int left): base(top, left)
        {
            // Empty Body
        }

        // An overridden version (note keyword) because in the
        // derived method we change the behavior

        public override void DrawWindow()
        {
            Console.WriteLine("Drawing a button at {0}, {1}\n", top, left);
        }
    }

    // Test Class
    public class Tester
    {
        static void Main()
        {
            // Static Binding at Compile Time
            MyControl win = new MyControl(1, 2);
            ListBox lb = new ListBox(3, 4, "Stand alone list box");
            Button b = new Button(5, 6);
            win.DrawWindow();
            lb.DrawWindow();
            b.DrawWindow();

            // Dynamic Binding at Run Time, create an Array
            // holding the References to the Controls

            MyControl[] winArray = new MyControl[3];
            winArray[0] = new MyControl(1, 2);
            winArray[1] = new ListBox(3, 4, "List box in array");
            winArray[2] = new Button(5, 6);

            // The correct DrawWindow() is called = Late Binding
            for (int i = 0; i < 3; i++)
            {
                winArray[i].DrawWindow();
            }

        }
    }
}

The compiler now knows to use the overridden method when treating these objects polymorphically. The compiler is responsible for tracking the real type of the object and for handling the «late binding» so that it is ListBox.DrawWindow() that is called when the Control reference really points to a ListBox object.

Contents added by tonypower on Jul 07, 2011

Nice work, but how to get methods and parameters of the com late binding?

COMMENT USING

Trending up