[Overview] This article starts from the basic concepts, in the interface, type library, guid, etc. of COM. At the same time, this article also introduces the creation of the COM object, what is MTS, how to use the MTS management COM object, his strengths and programming, and combine specific examples, another focus of this article is to introduce COM applications on the Internet, through Safety, efficiency, etc., showing the powerful application prospects of COM on the Internet. In the process of discussed, this paper combines C , VB, and ASP to explain.
[SUMMARIZE] In this article, the author introduce the technology of COM.From the interface, the type library and GUID Clearly show the character of COM.This article also list how to create COM object, how to Using MTS to manage the COM object And how to make MTS in Program.as Another Emphasis, The Article Demonstrate The Application of COM in Internet, Through The Analysis of Security and Efficiency, Show The Power of COM.
Keywords: COM, MTS, component technology
Foreword has developed in the Internet today, there are many programming standards in the network environment. COM is one of them and the fastest development, the most developed standard. However, in China, there is no book that truly introduces COM. Plus COM itself understands that there is difficult, promotion and use COM, this article tries to display COM to the reader from the perspective of concept and application. And introduced the application of COM on the Internet. One. COM Technology Introduction Com (Component Object Model) Microsoft Component Object Model. It is a small binary executable program that provides services for applications and operating systems and other components. Many of Microsoft's other technologies such as: ActiveX, DirectX, OLE, etc. are based on COM. The release form of the COM is: the executable code consisting of Win32 dynamic link library (DLL) or in the form of executable file (exe). The components implemented in the manner released in the form of a DLL, which runs the component program and the client in the same process when the customer call is called, so it is called components within the process. Published in EXE, when the customer calls, he has its own independent process space. Recommended components outside the process. COM is not a function set as Win API: it does not support or provide a variety of functions to make specific operations for the system. The COM itself is a series of services called the COM library, which provides a series of services such as the customer's query, and the registration / anti-registration of the component, in general, the COM library is implemented by the operating system, the program Members don't have to care about the details of their implementation. Overall, COM provides a standard method for writing components. Components that follow the COM standard can be combined to form an application. As for those of these components, it is not important to achieve it. Contacts between components and customers through "interface". 1.COM interface is a set of logically interrelated operations, which defines a certain behavior, which is the specification of this set of operations, not a specific implementation, and the entrance is that the interface represents the interface calorie and the implementation. One convention. The understanding of the interface is very important because all the operations of the COM are done by the interface pointer. Through Interface We show the functionality of the component to the caller (ASP PAGES, etc.) each COM interface provides a named IUnknow interface, including addRef (), Release (), and queryinterface () three interfaces, before The two interfaces are used to manipulate the object reference count, because each COM object is created to consume the resources of the system, and after the two functions are introduced, when the object is created or otherwise, when the object is created or otherwise, when the pointer points to the object, call AddRef () Method, add the reference count, when the object is no longer used, call the Release () method, reduce the reference count, when the count is 0, the object releases yourself, you can avoid re-every reference object Create, make resources can be used reasonably. QueryInterface () The interface is used to find the object to support other interfaces, you need to pass the IID of the interface to the interface and a pointer to the output parameter. Each COM interface is derived from the iUnknow interface, and three entries in its VTBL are pointers to the above three functions.
Next, the implementation method of these three interfaces: / * Reference Object * / Ulong iUnknown :: addRef (void) {m_refcount ; / * Reference count plus one * / return m_refcount; / * Return the current number of current references * /} / * Release the object's * / ulong iunknow :: release (void) {m_refcount--; / * Reference number minus one * / if (m_refcount == 0) / * If the count value is 0, the object releases yourself * / {Delete this; return 0;} return m_refcount; / * Returns the total number of current references * /}
/ * Query interface * / hResult iunknow :: queryinterface (RIID RIID, LPVOID FAR * PPV) {if (riid == iid_iunknown || riid == iid_idroptarget) / * Check if the object supports the interface * / {PPV = LPVOID) THIS; / * Assign the pointer of the requested interface to the output parameter * / addRef (); / * Reference Object * / Return S_OK; File: // Successful tag} else {* ppv = null; / * output The parameter pointer is empty * / return e_nointerface; / * Return to fail information * /} VB implemented COM is automatically completed, users only define all methods of implementation, all other work is given to the system Processing, and declarations and implementations of interfaces in VC and Delphi are required to implement, and users can freely control some low-level things. 2. Type Library: Type library is a collection of information, which involves the class, interface, and interfaces of the interface and interfaces, and parameter types of these methods. Type library Access through the iTypelib interface, for the smart development environment such as VB, you cannot use the C header file to find information about the interface method and the information. At this time, you can use the type library as an independent header file, you can easily solve it. Such as user interfaces, making program development more simple. 3. GUID: Also known as global unique identifier, used to distinguish the identity of entries in COM. The structure of the GUID is as follows: typedef struct_guid {unsigned long data1; unsigned long data3; unsigned long data4 [8];} GUID; Generate GUID to identify object classes or interfaces. It has a total of 128 bits, in theory, there is no conflict between Guid. In the run phase, the program can be done through the API function cocreateguid (), while in the development phase, you can get it by running the application: guidgen.exe. There are three GUID: CLSID (Identification Class Objects), PROGID (Identity Class Easy), and IID (Identity Interface) in COM, which corresponds to Proid and CLSID, because ProID is easier to remember and identify, intelligent development in VB In the environment, basically use proid, but when the specific implementation, VB is still to run the CLSIDFROMProid function to get the CLSID of the object, then call the COCREATEINSTANCE function to create a COM object. Finally introduce the COM object: The client passer Function CocreateInstance () Creates an object (specifying the required CLSID and interface), and identifies the object to be created through the CLSID in the program, COM uses the CLSID to find the server in the registry, then create an object. There are two ways to create objects in VB: 1. New
MTS :: Microsoft Transaction Server Microsoft Transaction Manager. It provides an application infrastructure that creates scalable, robust enterprise applications, which is a component-based transaction system for creating, deploying, and managing server applications, MTS is also part of the WindowsNT Option Pack. The MTS object has a timely activation of the Just-in-Time Activation feature. If the customer program frequently creates objects and deletes objects, this is bound to affect the performance of the system due to the operation of creating an object and deleting object is a very consumable system. The MTS provides an object's reuse function. When the object is finally released, it is not clear from memory immediately. If the customer requests to create an object again, the MTS can reuse the original object, and the object is reinitialized, thus avoiding frequent creation. And delete the object of the object. MTS makes COMs are more mature, perfect, and he controls the objects in the object, and the objects such as transactions, security, etc., so that the object is free from the trivial details of the underlying, but does not lose functions. The object of the MTS refers to an instance of the COM component running in the MTS environment. MTS maintains an environment object (also known as context object) for each object, and the environment object implements the IObjectContext interface, and provides transactions, activities. Status, security control capability, etc., when multiple objects participate in the same transaction processing, MTS uses associated context objects to track transaction processing. The MTS customer is the client of the MTS object, which can be an application (based customer) running outside MTS or another MTS object. So MTS objects and customers are a relative concept.
MTS mainly uses role-based security models in security control, which is the security role of the MTS service process, not separately defined the security role of the component, and MTS also provides another advanced security model, that is, in environment variables In addition to implementing the IObjectCountCountRol interface, another interface ISecurityProperty is implemented, using this interface to get the SID of the customer's client and the security identifier of the customer who currently calls the object. The application system can achieve custom access control through this information. It is not enough to add COM DLL to the MTS package. It is not performed for MTS. It must also be written. In order to use transaction processing and work in MTS in MTS in an effective manner, you must follow the following four rules: 1) A reference to the ObjectContext object: A object context information stores in the ObjectContext object, the ObjectContext object tracks the work made by the MTS object, also records the security information of the MTS object, the object can get a context object to them by calling the getObjectContext function. Quote. 2) If the work is successful, call the setcomplete method: When the object is involved in a transaction process, if it is successful, the setComplete method of the ObjectContext object must be called, the method notifies the MTS, and the work made by the object can be submitted, and the held Resources (including this object itself) can be recycled. 3) If the work fails, call Setabort: When the object fails, the SETABORT method must be called, which informs that all modifications performed by the object and all modifications to other objects within the same transaction must roll back and the object is held. Some of all objects can be recycled 4) Manage object status: Status is object data. Local variables and global variables can reserve the object state, but MTS reclaim object when the transaction is completed, which will lose all information in local and global variables, so you want to keep the status, you must pass some methods such as class properties, Function return value, address parameters, etc. I will give a VB implementation creation MTS component instance '********************************************* ** 'Function: ListCustomer ()' purpose: Simplely find customer information, then display it to '************************************* ********** Public Function ListCustomers () As ADODB.Recordset On Error GoTo ErrorHandle Dim objADOConn As ADODB.Connection Dim strSQL As String Set objADOConn = GetObjectContext.CreateInstance ( "ADODB.Connection") file: // Note that this is not used in a general CreateObject () method, but returns a pointer to the ADO connection object with the CreateInstance () method in getObjectContext.
strSQL = "SELECT CustomerID, CompanyName, Address, City, Country, Phone FROM Customers" objADOConn.Open "Northwind", "sa", "password" // 'open the connection SQLSERVER database Set ListCustomers = objADOConn.Execute (strSQL) file: // remove the desired record set GetObjectContext.SetComplete file: // after a successful operation to release the object objADOConn.Close set objADOConn = Nothing strSQL = "" Exit FunctionErrorHandle: Err.Clear file: // clear error GetObjectContext.SetAbort file: // The release object tells MTS with setcomplete, which has been called, which can release his resources to the MTS thread pool to go to the corresponding setabort method, tell MTS, the call is canceled, the same release his resources to the MTS thread pool go with. After the component of the application, the component of the MTS technology can be compiled, the ListCustomer () method can be obtained by calling Server.createObject ("Northwind.customer") in the ASP page. three. COM Technology Application on the Internet
The main application of COM technology is due to the development and promotion of the Trend and Branch Applications of the Three-layer Structure of the Network Application. At present, most applications are two-layer (C / S) structure, which is very large in a two-layer architecture, because each customer of the two-layer structure is directly connected to the database server. On the press, the server is very large. After introducing a three-layer structure, we define the representation layer directly to deal with the user to handle the business logic layer submitted by the user and the data access layer that is used for database processing (Data Access Layer) ). Now the three-layer structure is more and more widely used: there is reason to believe that in the near future, COM will become the most common method to build Internet applications. At present, there is a lot of choices when building e-commerce web applications, such as currently, a very popular JSP in foreign countries, he has a cross-platform advantage, and it is doubled. It can also be used as PHP MySQL, which is a gold combination of small and medium-sized applications in the Linux environment. However, Microsoft's platform still has an absolute position in China's enterprises, and Microsoft's ASP has rapidly occupying its ease of use. A large e-commerce market, and the current Microsoft's .NET plan has greatly improved Microsoft's position in the network business platform. However, both ASP or future ASP.NET have a relatively large limit, security and efficiency are two major problems. Now it is a solution through COM technology. It is liberated from the commercial layer from the commercial layer with COM. The processing of the layer is used to construct a component of the commercial layer with VB, VC, Java, Delphi, etc. COM is: 1. In the Internet era, the openness of software is very important, and openness means that it is necessary to comply with standards. And on the Windows platform, COM is the standard. 2. Microsoft proposed ActiveX technology contains all COM-based Internet-based software technology, and ActiveX technology is undoubtedly the most technically promising technology on the Internet. In the near future, with the ActiveX controls, we have reason to believe in Any development on the Internet will use it as templates and foundations, while COM is the foundation of ActiveX. From the server, ASP combines IIS and other software products, providing very powerful and easy-to-use web application implementation, from customer software products, its content is more rich, the Internet SDK provides a lot of direct Using components or features, such as XML object models, WebBrower control, etc., through these components, providing more convenience for Internet users, but also provides more and colorful information. 3. Now COM has penetrated into product Internet, including some basic protocol software. Not only the software developers should apply COM, and even the basic home maintenance people are afraid to use COM to improve their page. 4. The advantage of expanding the ASP network application with COM is that our application is more maintainable and more efficient during execution! At the same time, he also reached the package source code to protect intellectual property rights. 5. The Internet application is distributed, while COM (mainly distributed COM) an important feature is that its processing power can increase as the user's number, the amount of data required is increased. 6. CoM's no extension COM , has powerful features such as memory databases, load balancing.
Of course, the application COM also has a disadvantage: first is COM standard, it still needs to be improved (in fact, the standard, including COM is constantly improving), followed by writing and debugging COM, even if it is using VB and other intelligent environments, it is fully implemented COM features is not an easy task. From the efficiency of COM, when the connection is relatively small, use COM is equal to adding a layer of interface, and of course affects a little efficiency. However, when the number of users is large, since the DCOM can balance the load to several servers, the JIT technology, which has been MTS, can greatly improve efficiency. COM itself provides two types of security, access security (specifying those users can call components, including how to securely start and how to protect public resources) and excitation security (which users can in a new process Creating a new component object), these are mainly for process external components, and the internal components are generally not considered. Security is especially important for applications on the Internet. Since the ASP program is written on a page, it is very important to expose business rules, while business rules are very important for applications, and use COM we can put Commercial rules compiled into binary code, the purpose of protecting code is achieved. At the same time, it can also be packaged in the code with COM, because the DLL has been compiled, and the ASP is interpreted, and it is also a lot than the efficiency of execution.
Below, use an actual example of adding Access database record: first create a new class in VB: such as CLSADD and define an interface function: addpublic sub add (byval uid as string, byval pwd as integer, byref vNTerror As Variant) Dim objConnection As ADODB.Connection Dim objCommand As ADODB.CommandOn Error GoTo Error_Handler vntError = "" 'make sure vntError is not holding anything Set objConnection = New ADODB.Connection' create Connection and Command object Set objCommand = New ADODB.Command the following code a the DSN, is connected to a database, to achieve operation of the database: 'open a connection to the datasource With objConnection .ConnectionString = "DSN = ExpandingASP" .CursorLocation = adUseClient .Mode = adModeReadWrite .Open End With Once the connection is connected Create, use the insert statement to insert the UID and PWD into the database! 'add the uid with objcommand set .activeconnection = objconnection / * Establish connection * / .commandtext = "Insert Into Authors (UID, PWD) Values ('" & UID & "," & PWD & ");" / * SQL command * / .CommandType = adCmdText / * set type executed * / .Execute End With Exit_Handler: 'clean up set objCommand = Nothing If objConnection.State = adStateOpen Then objConnection.Close / * Close the connection * / set objConnection = Nothing / * Clear connection * / EXIT SUB ERROR_HANDAL: VNTERROR = Err.description & "(" & Err.Number & "-" & Err.Source & ")" / * vnTerror is used to record detailed error message * / resume exit_handlerend Sub
Then we use this DLL to register, if the complete DLL name is DBHANDLE: regsvr32.exe c: /yourDir/dbhandle.dll can be tested with the ASP page! First we define the Dim Objauthor 'Custom Class (ActiveX Server) DIM STRERROR' Error String This helps us debugging in the future. Of course this is not a must! Then we create objects (here we don't use MTS) set objauthor = server.createObject ("expandingasp.authors") objauthor.add request.form.Item ("txtuid"), request.form.Item ("txtpwd") If the strerror is not empty, there is a problem with Objauthor.Add operation, and the error message if the error information is displayed. "Error Saving Author:" & Strerror '... Response.Endend IF IV. From DCOM to COM , the DCOM component launched by Microsoft Company, is a new phase of distributed component object model, which is a new phase of COM development. He expanded component object model technology to support different computers on local area networks, wide area networks and even internets. Communication between objects. With DCOM, your application can achieve distribution at the location to meet your customers and applications. DCOM is somewhat characteristics, such as: 1. Position independence 2. Language independent 3. Scalability 4. Safety 5. The development of DCOM has promoted the development of COM in the network environment. The latest COM not only inherits many of the characteristics of COM, DCOM, and MTS, but also adds some new services, such as memory databases. , Event model, load balancing, etc., these new services make COM abnormalities. (This is the university graduation papers, now in order to earn points, put it out, simple, please forgive me)
Guide Teacher: Professor Wu
Main reference books and websites:
COM principle and application Pan Aimin Tsinghua University Press in 1999
COM Entry David S.PLAUT Machinery Industry Press 2000
Www.9cbs.net programmers
Www.15seconds.com