Creating COM objects in C # (from the computer World)

Source: Internet
Author: User
Tags definition bool class definition implement connect requires
Create | object in this article, we will discuss the following questions:
• Create a simple COM object using C # (using COM's interop attributes).
• Access COM from VC + + client software. The client software uses the TypeLibrary (. tlb file).
For simplicity and convenience for developers to use and test, we used the Northwind database in the default installation of SQL Server database software.
• Modify the name of SQL Server in a COM object and connect to SQL Server.
• We have created the user name and password for the connection database for Scott, Tiger, and we can use it or other existing username and password.
Part I: Creating a simple COM object with C #
A COM object is a classlibrary class that generates a DLL file. To create a simple COM object in the VS development environment, we can select "File"-> "new"-> "project"-> "visualc# Project"-> "Class Library" and then create a project named Database_comobject.

Note that the following conditions are required to invoke the Vc# object in COM:
• The class must be public in nature.
• Features, methods, and events must be public in nature.
• Attributes and methods must be defined in the class interface.
• Events must be defined in the event interface.
Class members that are not of the public nature defined in these interfaces cannot be accessed by COM, but they can be accessed by other. NET Framework objects. To enable COM to access features and methods, we must define them in the class interface so that they have DISPID attributes and implement them in the class. The order in which these members are defined is the order in which they are in COM. To allow COM access to events in a class, you must define these events in the event interface and give them DISPID properties. The event interface should not be completed by the class, class implements only the class interface (it can implement more than one interface, but the first interface is the default interface), the methods and attributes that need to be made available for COM access should be implemented in the default interface, and methods and attributes must be identified as public and conform to the definition in the class interface. Events that require COM access are also completed in the default class interface, which must also be identified as public and conform to the definition in the event interface.
Before the interface name, each interface requires a GUID attribute. To generate a unique GUID, you need to run the Guidgen.exe tool software and select "Sign-up form"
The following is a class interface:

[Guid ("694c1820-04b6-4988-928f-fd858b95c880")]
public interface Dbcom_interface
{
[DispId (1)]
void Init (string userid, string password);
[DispId (2)]
BOOL Executeselectcommand (string selcommand);
[DispId (3)]
BOOL NextRow ();
[DispId (4)]
void Executenonselectcommand (string inscommand);
[DispId (5)]
String getcolumndata (int pos);
}



COM event interface:
Event Interface Database_comobjectevents
[Guid ("47c976e0-c208-4740-ac42-41212d3c34f0"),
InterfaceType (Cominterfacetype.interfaceisidispatch)]
public interface Dbcom_events
{
}


The following is the actual class definition:

[Guid ("9e5e5fb2-219d-4ee7-ab27-e4dbed8e123e"),
ClassInterface (ClassInterfaceType.None),
ComSourceInterfaces (typeof (Dbcom_events))]
public class Dbcom_class:dbcom_interface
{


Note that in front of the class, you need to set the following attributes:

ClassInterface (ClassInterfaceType.None),
ComSourceInterfaces (typeof (Dbcom_events))]

ClassInterfaceType.None says there is no class interface generated for the class, and if the interface is not explicitly implemented, the class can only provide late-bound access through IDispatch. Users want to enable external objects to access the functionality of the class through an interface explicitly implemented by the class, which is also the recommended ClassInterfaceAttribute setting.
ComSourceInterfaces (typeof (Dbcom_events)) determines many of the interfaces that are provided as COM events to external objects. In the example of this article, we do not open any events to external objects.

The following is the complete source code for the COM object:

Using System;
Using System.Runtime.InteropServices;
Using System.IO;
Using System.Text;
Using System.Data.SqlClient;
Using System.Windows.Forms;

Namespace Database_comobject
{
[Guid ("694c1820-04b6-4988-928f-fd858b95c880")]
public interface Dbcom_interface
{
[DispId (1)]
void Init (string userid, string password);
[DispId (2)]
BOOL Executeselectcommand (string selcommand);
[DispId (3)]
BOOL NextRow ();
[DispId (4)]
void Executenonselectcommand (string inscommand);
[DispId (5)]
String getcolumndata (int pos);
}

Event Interface Database_comobjectevents
[Guid ("47c976e0-c208-4740-ac42-41212d3c34f0"),
InterfaceType (Cominterfacetype.interfaceisidispatch)]
public interface Dbcom_events
{
}


[Guid ("9e5e5fb2-219d-4ee7-ab27-e4dbed8e123e"),
ClassInterface (ClassInterfaceType.None),
ComSourceInterfaces (typeof (Dbcom_events))]
public class Dbcom_class:dbcom_interface
{
Private SqlConnection myconnection = null;
SqlDataReader myreader = null;

Public Dbcom_class ()
{
}

public void Init (string userid, string password)
{
Try
{
String myconnectstring = "User id=" +userid+ ";p assword=" +password+
";D Atabase=northwind; Server=skywalker; Connect timeout=30 ";
myconnection = new SqlConnection (myconnectstring);
Myconnection.open ();
MessageBox.Show ("CONNECTED");
}
catch (Exception e)
{
MessageBox.Show (E.message);
}
}

public bool Executeselectcommand (string Selcommand)
{
if (myreader!= null)
Myreader.close ();

SqlCommand mycommand = new SqlCommand (Selcommand);
Mycommand.connection = myconnection;
Mycommand.executenonquery ();
myreader = Mycommand.executereader ();
return true;
}

public bool NextRow ()
{
if (! Myreader.read ())
{
Myreader.close ();
return false;
}
return true;
}

public string getcolumndata (int pos)
{
Object obj = Myreader.getvalue (POS);
if (obj = null) return "";
return obj. ToString ();
}

public void Executenonselectcommand (string inscommand)
{
SqlCommand mycommand = new SqlCommand (Inscommand, MyConnection);
int retrows = Mycommand.executenonquery ();
}

}
}


Before you create a COM object, we must register the object with COM interop. Right-click the project name in the solution Manager, click the Properties option on the shortcut menu, and then click Configure-> "create" to extend the output section to set the value of the Register for COM Interop option to True. In this way, a COM object can interact with a manageable application.

To enable a COM object to be invoked by an external object, the class library combination must have a strong name. Creating a strong name requires a SN.EXE name:
Sn-k database_com_key.snk
Open AssemblyInfo.cs, and modify the following line:
[Assembly:assemblykeyfile ("Database_com_key.snk")]

Creates an object. Creating an object generates a class library that can be imported into a manageable or unmanaged code.
Part Two: Creating client software to access COM objects using Visual C + +
• Create a simple project using the VC + + development environment.
• Import type libraries using #import directive.
• Create a smart pointer in the interface that performs the functions provided by the COM class from the interface. Make sure that the CoInitialize () call is added when the application loads:
CoInitialize (NULL);

Database_comobject::D bcom_interfaceptr P (__uuidof (database_comobject::D bcom_class));
Db_com_ptr = p;
Db_com_ptr->init ("Scott", "Tiger");

The following code executes an SQL command on the Customers database table that returns information about the customer for the given ID:
Char cmd[1024];
sprintf (cmd, "Select COMPANYNAME, ContactName,
ContactTitle, address from CUSTOMERS WHERE CUSTOMERID = '%s ', m_id);
const char *p;

BOOL ret = Db_com_ptr->executeselectcommand (cmd);

if (! Db_com_ptr->nextrow ()) return;

_bstr_t Mdata = Db_com_ptr->getcolumndata (3);
p = mdata;
M_address = (CString) p;


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.