|
|
|
|
|
Home
»
VB.NET
»
Using your C# Components in Visual Basic through COM
|
|
|
Author Rank:
|
|
Total page views :
20355
|
|
Total downloads :
265
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
|
|
|
|
|
|
|
|
Fig 1.1 - Output from VBA application accessing the GridViewControl.
Those of you who may have thought that the .NET environment wouldn't allow you to create Components for Visual Basic or Visual C++ or Delphi, Guess again! Microsoft has created several attributes and utilities to make it easy to place a .NET component into the clutches of good old COM. In this article I'll discuss how you can take an existing component and make it accessible in VBA. (The same code could of course apply to VB).
In my previous article on this site, I showed you how you could create a simple gridview control using the listview component. Now we are going to add a few attributes to some of the code to give the GridView accessibility from COM in a predictable way. Below are a few of these attributes and a description of each:
|
COM Attribute |
Description |
|
[GuidAttribute(guid)] |
Used to assign a guid to a class or interface. Use GuidGen.exe to generate the guid |
|
[DispId(dispatch id)] |
Assigns a dispatch id to a property, field or method in the class for access through the IDispatch interface; could be any integer value |
|
[ProgId(progid)] |
The Program Id of the class or interface |
|
[ComRegisterFunction] |
Tells the RegAsm.exe utility to call a method of the component while registering the Component. It's placed above the method in the class you wish to execute. |
You can use each of these attributes in the grid view to set you up for creating accessibility through COM.
Below are a few lines showing how the attributes are used.
namespace GridViewSample { using System;using System.Collections; using System.Core; using System.ComponentModel; using System.Drawing; using System.Data; using System.WinForms; using System.Runtime.InteropServices; // necessary library to use COM attributes. /// <summary> /// Summary description for GridView. /// </summary> /// [GuidAttribute("14547C64-EE88-4e4f-BE81-CBB7AB6BB8C6")]
public class GridView : System.WinForms.UserControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components; private System.WinForms.ListView listView1; ......
Listing 1 - Using the GuidAttribute to expose a class to COM
In the listing above, the GuidAttribute is used to expose the class. Note that it can also be used to expose an interface. I used the Guid generator (guidgen.exe) utility that ships with most visual studio applications to generate the guid and pasted it from the clipboard into our GuidAttribute. This generates a unique guid for our component. Its also worthy to point out that you need to include: using System.Runtime.InteropServices in order to utilize the COM attributes.
Below I use the Dispatch Id attribute over the method SetColumnName to assign it a dispatch id of 1:
[DispId(1)]
public void SetColumnName(int index, string aName) { if (index >= listView1.Columns.Count) { MessageBox.Show("SetColumnName:Column out of range"); return; // precondition } listView1.Columns[index].Text = aName; }
Listing 2 - Using the DispId Attribute to expose class methods to COM.
The only other code requirement for exposing your COM component is that you must have a default constructor(constructor with no arguments) so that COM can create an instance of the object. Note that the default constructor of the GridView exhibits no change from the previous article, but nevertheless, it needs to be there:
public GridView() { // This call is required by the WinForms Form Designer. InitializeComponent(); InitializeGrid(); // TODO: Add any initialization after the InitForm call. }
Listing 3 - Default Constructor necessary for COM to access the component.
After you compile your project, you're not finished with the COM exposure process just yet! There are two utilities that ship with the sdk that you need to use to make your assembly accessible through COM. One is the Type Library Exporting Utility (tlbexp.exe) and The Register Assembly Utility (regasm.exe). Both these utilities should already be in your path and can be run from the command prompt. The command line for tlbexp.exe is shown below. It's best to run it in the directory of the compiled component to produce a tlb file in that directory:
tlbexp.exe GridViewControl.dll
This will produce the type library GridViewControl.tlb.
You can actually produce a type library and register it all in one go using the regasm.exe utility as shown below:
RegAsm GridViewControl.dll /tlb:GridViewControl.tlb
Now you would think you are ready to use your control as a COM component and well.. you can. The only thing is that with they way Microsoft structured COM components with the new security model, if your component is not a strongly named assembly, it can not be used unless it is placed in the same directory as the application that is using it (such as VB or a VBA application such as Excel). A strongly named assembly can be accessed from anywhere if it has a key and is signed, and all of this other stuff that I didn't have time to research for this article. (I was able to gather that you need to use utilities makecert.exe, al.exe, and sn.exe to get this to happen and somehow get them to work in a shared assembly cache.) The command sn -v GridViewControl.dll kindly tells me that I don't have a strongly named assembly, so I copied the control into the local directory with my VBA application.
To access the control, I use the name of the namespace containing the class(GridViewControl) followed by the name of the class(GridView). This string is better known as ProgID and is automatically generated by the regasm.exe utility into the registry and the type library. Below is the VBA code that utilizes the grid control and outputs it to the screen. You can test this out with any VBA application as long as you place the GridViewControl.dll in the local directory with the application and register it using regasm.exe as shown above:
Sub DisplayGridView() ' Declare the variable for the GridViewControl ' Remember to reference in in the Tools menu Dim gc As GridViewControl.GridView 'Create the GridView Com Object Set gc = CreateObject("GridViewControl.GridView") ' Set up the properties and the size gc.Visible = True gc.Enabled = True gc.TopLevel = True gc.Text = "My COM Example" gc.SetBounds(10, 10, 400, 200) ' set the column names gc.SetColumnName(0, "ID") gc.SetColumnName(1, "First Name") gc.SetColumnName(2, "Last Name") ' set the column widths gc.SetColumnWidth(0, 10) gc.SetColumnWidth(1, 20) gc.SetColumnWidth(2, 20) ' set the contents of the cells gc.SetCell(0, 0, "1") gc.SetCell(0, 1, "Mike") gc.SetCell(0, 2, "Gold") gc.SetCell(1, 0, "2") gc.SetCell(1, 1, "Bob") gc.SetCell(1, 2, "Hope") gc.SetCell(2, 0, "3") gc.SetCell(2, 1, "John") gc.SetCell(2, 2, "Doe") End Sub
One nice thing worth noting, is that the regasm utility automatically generates interfaces for the base class members of the GridView, so you can use methods like SetBounds and properties like Visible to adjust the GridView. I found some properties did not work, though, because there was no equivalent types in COM that mapped properly even though they were still exposed in the type library. This may either be a deficiency in Beta 1, or something I was doing wrong :-). Anyway it seems to work well enough for testing purposes. I couldn't quite figure out how to embed the control in the UserForm in VBA, but the control does seem to come up stand alone.
|
|
|
Login
to add your contents and source code to this article
|
|
|
|
|
|
|
|
Mike Gold
Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems. He can be reached at mike@c-sharpcorner.com
|
|
|
|
|
|
|
|
|
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional
consulting company, our consultants are well-known experts in .NET and many of them
are MVPs, authors, and trainers. We specialize in Microsoft .NET development and
utilize Agile Development and Extreme Programming practices to provide fast pace
quick turnaround results. Our software development model is a mix of Agile Development,
traditional SDLC, and Waterfall models.
|
|
Click here to learn more about C# Consulting. |
|
|
|
|
|
|
|
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon.
Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees.
As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
|
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
|
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
|
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today. With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications. Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
|
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from
DevExpress - Absolutely Free-of-Charge without any royalties or distribution
costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin
edit, tab control and so much more!
DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
|
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or
application via a range of API's. Learn More about our API connections.
|
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
|
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
|
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
|
|
|
|
|
|
|
|
|
|
|
|
|