Microsoft Knowledge Base Email Alertz

KBAlertz.com: (302902) - When you automate an application such as a Microsoft Office application, the calls to the properties and methods of the Office application's objects must be connected in some way to those objects. The process of connecting property and method calls to...

Receive Microsoft Knowledge Base articles by E-Mail?

Every night we scan the Microsoft Knowledge Base. If technologies you're interested in are updated, we'll send you an e-mail. You only get one e-mail a day, and only when new articles are added.

Click here to create a
FREE account
Already have an account?
[Click here to Login]

Search KbAlertz

Advanced Search

Webmasters
Put kbAlertz on your website.
[ Click Here for more! ]





ASP.NET 3.5 Web Hosting with Windows 2008 and SQL 2008: Click Here!
Discount ASP.NET Hosting
ASP.NET 2.0 and 3.5
Windows2008 and SQL2008
US and UK Hosting
The ad says 3 - but KBAlertz referrals get
** SIX MONTHS FREE **


Bug Tracking Software
For bug tracking software or defect tracking software or issue tracking software, visit Axosoft.


Community Site



We Send hundreds of thousands of emails using ASP.NET Email



Expert Web Design & Graphic Design
Design44.com

ASP.NET 3.5 Web Hosting with Windows 2008 and SQL 2008: Click Here!
Discount ASP.NET Hosting
ASP.NET 2.0 and 3.5
Windows2008 and SQL2008
US and UK Hosting
The ad says 3 - but KBAlertz referrals get
** SIX MONTHS FREE **




Mentioned In








Microsoft Knowledge Base Article

This article contents is Microsoft Copyrighted material.
©2005-©2007 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks




Article ID: 302902 - Last Review: March 27, 2007 - Revision: 7.3

Binding for Office automation servers with Visual C# .NET

This article was previously published under Q302902

On This Page

SUMMARY

When you automate an application such as a Microsoft Office application, the calls to the properties and methods of the Office application's objects must be connected in some way to those objects. The process of connecting property and method calls to the objects that implement those properties and methods is commonly called binding. In Visual C#, the two types of binding that are available are early binding and late binding. The type of binding you choose can affect many aspects of your program, including performance, flexibility, and maintainability.

This article explains and compares early and late binding for Visual C# Automation clients and provides code samples that demonstrate both types of binding.

Early binding

With early binding, Visual C# uses type information that is available about the Office Application in question to bind directly to the methods or properties it needs to use. The compiler can perform type and syntax checks to ensure that the correct number and type of parameters are passed to the method or property, and that the returned value will be of the expected type. Because less work is required at run time to make a call to a property or method, early binding is sometimes faster; however, although early binding may be faster, performance differences when compared to late binding are often negligible.

Early binding does have the minor disadvantage that it can introduce possible version compatibility issues. For example, suppose that an Automation server such as Microsoft Excel 2002 introduces a new method or property that was unavailable in Excel 2000, or makes a change to an existing property or method. These changes may alter the binary layout of the object and cause problems with a Visual C# application that uses the Excel 2002 type information to automate Excel 2000. To avoid this problem with early binding, it is generally recommended that you use the type information for the earliest version of the Office Application that you wish to support when you develop and test your Automation client.

The following steps demonstrate how to build an Automation client that uses early binding. Note that, as the steps illustrate, early binding requires you to reference the type library for the Automation client.

Create an Automation client that uses early binding

  1. Start Microsoft Visual Studio .NET. On the File menu, click New and then click Project. Select Windows Application from the Visual C# Projects types. Form1 is created by default.
  2. Add a reference to the Microsoft Excel Object Library. To do this, follow these steps:
    1. On the Project menu, click Add Reference.
    2. On the COM tab, locate theMicrosoft Excel Object Library and click Select.

      Note Office 2003 includes Primary Interop Assemblies (PIAs). Office XP does not include PIAs, but they can be downloaded. For additional information about Office XP PIAs, click the following article number to view the article in the Microsoft Knowledge Base:
      328912  (http://kbalertz.com/Feedback.aspx?kbNumber=328912/ ) Microsoft Office XP primary interop assemblies (PIAs) are available for download
    3. Click OK in the Add References dialog box to accept your selections. If you receive a prompt to generate wrappers for the libraries that you selected, click Yes.
  3. On the View menu, select Toolbox to display the Toolbox, and add a button to Form1.
  4. Double-click Button1. The code window for the Form appears.
  5. In the code window, replace the following code
    private void button1_Click(object sender, System.EventArgs e)
    {
    }
    					
    with:
    private void button1_Click(object sender, System.EventArgs e)
    {
    	Excel.Application objApp;
    	Excel._Workbook objBook;
    	Excel.Workbooks objBooks;
    	Excel.Sheets objSheets;
    	Excel._Worksheet objSheet;
    	Excel.Range range;
    
    	try
    	{
    		// Instantiate Excel and start a new workbook.
    		objApp = new Excel.Application();
    		objBooks = objApp.Workbooks;
    		objBook = objBooks.Add( Missing.Value );
    		objSheets = objBook.Worksheets;
    		objSheet = (Excel._Worksheet)objSheets.get_Item(1);
    
    		range = objSheet.get_Range("A1", Missing.Value);
    
    		range.set_Value(Missing.Value, "Hello, World!" );
    
    		//Return control of Excel to the user.
    		objApp.Visible = true;
    		objApp.UserControl = true;
    	}
    	catch( Exception theException ) 
    	{
    		String errorMessage;
    		errorMessage = "Error: ";
    		errorMessage = String.Concat( errorMessage, theException.Message );
    		errorMessage = String.Concat( errorMessage, " Line: " );
    		errorMessage = String.Concat( errorMessage, theException.Source );
    
    		MessageBox.Show( errorMessage, "Error" );
    	}
    }  
    					
  6. Scroll to the top of the code window. Add the following line to the end of the list of using directives:
    using System.Reflection;
    using Excel = Microsoft.Office.Interop.Excel;
    					

Late binding

In contrast to early binding, late binding waits until run time to bind property and method calls to their objects. To do this, the target object must implement a special COM interface: IDispatch. The IDispatch::GetIDsOfNames method allows Visual C# to interrogate an object about what methods and properties it supports and the IDispatch::Invoke method then allows Visual C# to call those methods and properties. Late binding in this fashion has the advantage of removing some of the version dependencies that are inherent with early binding. However, it has the disadvantages of removing compile-time checks on the integrity of automation code, as well as not providing Intellisense features that can provide clues to correct calls to methods and properties.

To use late binding in Visual C#, use the System.Type.InvokeMember method. This method calls IDispatch::GetIDsOfNames and IDispatch::Invoke to bind to the Automation server's methods and properties.

Create an Automation client that uses late binding

  1. Start Microsoft Visual Studio .NET. On the File menu, click New and then click Project. Select Windows Application from the Visual C# Projects types. Form1 is created by default.
  2. On the View menu, select Toolbox to display the Toolbox, and add a button to Form1.
  3. Double-click Button1. The code window for the Form appears.
  4. In the code window, replace the following code
    private void button1_Click(object sender, System.EventArgs e)
    {
    }
    						
    with:
    private void button1_Click(object sender, System.EventArgs e)
    {
    	object objApp_Late;
    	object objBook_Late;
    	object objBooks_Late;
    	object objSheets_Late;
    	object objSheet_Late;
    	object objRange_Late;
    	object[] Parameters;
    
    	try
    	{
    		// Get the class type and instantiate Excel.
    		Type objClassType; 
    		objClassType = Type.GetTypeFromProgID("Excel.Application"); 
    		objApp_Late = Activator.CreateInstance(objClassType);
    
    		//Get the workbooks collection.
    		objBooks_Late = objApp_Late.GetType().InvokeMember( "Workbooks", 
    		BindingFlags.GetProperty, null, objApp_Late, null );
    
    		//Add a new workbook.
    		objBook_Late = objBooks_Late.GetType().InvokeMember( "Add", 
    			BindingFlags.InvokeMethod, null, objBooks_Late, null );
    
    		//Get the worksheets collection.
    		objSheets_Late = objBook_Late.GetType().InvokeMember( "Worksheets",
    			BindingFlags.GetProperty, null, objBook_Late, null );
    
    		//Get the first worksheet.
    		Parameters = new Object[1];
    		Parameters[0] = 1;
    		objSheet_Late = objSheets_Late.GetType().InvokeMember( "Item", 
    			BindingFlags.GetProperty, null, objSheets_Late, Parameters );
    
    		//Get a range object that contains cell A1.
    		Parameters = new Object[2];
    		Parameters[0] = "A1";
    		Parameters[1] = Missing.Value;
    		objRange_Late = objSheet_Late.GetType().InvokeMember( "Range",
    			BindingFlags.GetProperty, null, objSheet_Late, Parameters );
    
    		//Write "Hello, World!" in cell A1.
    		Parameters = new Object[1];
    		Parameters[0] = "Hello, World!";
    		objRange_Late.GetType().InvokeMember( "Value", BindingFlags.SetProperty, 
    			null, objRange_Late, Parameters );
    
    		//Return control of Excel to the user.
    		Parameters = new Object[1];
    		Parameters[0] = true;
    		objApp_Late.GetType().InvokeMember( "Visible", BindingFlags.SetProperty,
    			null, objApp_Late, Parameters );
    		objApp_Late.GetType().InvokeMember( "UserControl", BindingFlags.SetProperty,
    			null, objApp_Late, Parameters );
    	}
    	catch( Exception theException ) 
    	{
    		String errorMessage;
    		errorMessage = "Error: ";
    		errorMessage = String.Concat( errorMessage, theException.Message );
    		errorMessage = String.Concat( errorMessage, " Line: " );
    		errorMessage = String.Concat( errorMessage, theException.Source );
    
    		MessageBox.Show( errorMessage, "Error" );
    	}
    }
    					
  5. Scroll to the top of the code window. Add the following line to the end of the list of using directives:
    using System.Reflection; 
    					

REFERENCES

For more information, visit the following Microsoft Developer Network (MSDN) Web site:
Microsoft Office Development with Visual Studio
http://msdn2.microsoft.com/en-us/library/aa188489(office.10).aspx (http://msdn2.microsoft.com/en-us/library/aa188489(office.10).aspx)
For additional information about binding, click the following article numbers to view the articles in the Microsoft Knowledge Base:
245115  (http://kbalertz.com/Feedback.aspx?kbNumber=245115/ ) Using early binding and late binding in Automation
244167  (http://kbalertz.com/Feedback.aspx?kbNumber=244167/ ) Writing Automation clients for multiple Office versions
247579  (http://kbalertz.com/Feedback.aspx?kbNumber=247579/ ) Use DISPID binding to automate Office applications whenever possible

APPLIES TO
  • Microsoft Visual C# .NET 2003 Standard Edition
  • Microsoft Visual C# .NET 2002 Standard Edition
  • Microsoft Office Access 2003
  • Microsoft Access 2002 Standard Edition
  • Microsoft Office Excel 2003
  • Microsoft Excel 2002 Standard Edition
  • Microsoft Office PowerPoint 2003
  • Microsoft PowerPoint 2002 Standard Edition
  • Microsoft Word 2002
Keywords: 
kbpia kbautomation kbhowtomaster KB302902
       

Community Feedback System

Very often, it takes hours to solve a problem. Very often, you've looked high and low, and have tried a lot of solutions. When you finally found it, chances are, it was because someone else helped you. Here's your chance to give back. Use our community feedback tool to let others know what worked for you and what didn't.

Please also understand that the community feedback system is not warranted to be correct, it's simply a system that we've built to let people try and help each other. If something in a feedback response doesn't make sense to you, or you're not comfortable making changes that the feedback talks about (like registry edits), please consult a professional.

Thank you for using kbAlertz.com Feedback System.

-- Scott Cate

Be the first to leave feedback, to help others about this knowledge base article.

(Optional) Name

(Optional) Public URL Or Email

Comments
No HTML -- Text Only Please