Multi-level database development 3: Creating multi-storey applications

xiaoxiao2021-03-06  101

Chapter III Creating a multi-layer application a multi-layer Client / Server application is logically divided into several parts, running on different machines, which can be both in a local area, or on the Internet. The biggest advantage of multi-layer architecture can be summarized two points, one is centralized business logic, and the other is that the customer can do "thin". At present, the more common is the three-layer architecture, where the most critical is the application server, which has a role in the three-layer architecture, so the application server is also called Data Broker. Delphi4 can create an application server or create a "thin" customer. If you are not afraid of trouble, you can also create a database backend. In a more complex multi-layer architecture, more service middleware can be added between "thin" customers and remote servers, for example, a secure service middleware can be added, or join a conversion middleware, specifically used to handle different The problem of sharing data in the platform. Once you really understand the three-layer architecture, the multi-layer architecture is solved. 3.1 Overview of multi-layer architecture The support of Delphi 4 for multi-layer architecture is mainly due to its MIDAS technology. Midas is the abbreviation of Multi-Tier Distributed Application Services Suite. MIDAS technology uses another key technique Dax in Delphi 4 to make multiple layers of architectures on intRenet / intranet. 3.1.1 Advantages of multi-layer architecture In multi-layer architecture, due to the server concentration implements application logic (also known as business rules), client programs can focus on display data and interact with users, and customer programs are not even Need to know where the data is stored. Specifically, the multi-layer architecture has the advantage: the business rules are encapsulated in a shared intermediate layer. Different client programs can share the same intermediate layer without having to implement business rules separately by each client program. The client can do very "thin". Because many of the complex work is handled by the application server, the client only needs to pay attention to the user interface itself. "Skinny" customer program is easier to publish, install, configure, and maintenance. Distributed data processing is implemented. Distribute an application to run on several machines, enhance the performance of the application, and guarantee that the entire application crashes through the redundancy configuration. It is conducive to safety. Some sensitive functions can be placed on a layer with strict protective measures, and it is not complex by the user interface. CORBA or MTS in Delphi 4 supports more complex security mechanisms. 3.1.2 MIDAS technology MIDAS technology is the key to multi-layer architecture. Whether it is the application server or the client, MIDAS technology needs to have DBClient.dll support, this dynamic link library is used to manage packets. You need to purchase a server license when publishing a MIDAS application. MIDAS-based multi-layer applications require some special components that are divided into four major categories: the remote data module in the object library. The remote data module is similar to the normal data module. Different, the remote data module can be used as a COM server or a CORBA server to allow the client to access its interface. TDataSetProvider and TPROVIDER components. These two components are used in the application server side, and the main role is to provide an iProvider interface, and the client obtains data and update data sets via the iProvider interface. TclientDataSet components. This is a component that inherited from TDataSet but does not require BDE. MIDAS connection member. Includes TDCOMCONNECTION, TSOCKETCONNECTION, TCORBACONNECTION TOLENTERPRISECONNECONNECONNECTION, TMIDASCONNECTION, and TREMOTSERVER. Among them, TMIDASCONNECTION and TREMOTSERVER are reserved for code compatible with Delphi3.

The role of the MIDAS connection member is to locate the server and the iProvider interface for the client program. Each MIDAS connection component works in a specific communication protocol. 3.1.3 How does the MIDAS application work a user first to start a client program, and the client will try to connect the application server if the application server has not yet run, and the client will activate the application server and get an iProvider interface. The client requests data to the application server. If the TclientDataSet's Fetchondemand property is set to True, the client automatically retrieves the value of the additional packet such as the value of the BLOB field or the content of the nested table as needed. Otherwise, the client needs to explicitly call GetNextPacket to get these additional packets. After the application server receives the request from the client, the data is retrieved from the remote database server, and the package is returned to the client client to receive the packet after receiving the packet, turn the package, then display or proceed. Users edit the data and apply to the application server to update the data, but also to pack it. After the application server receives the user's application, apply to the remote database server to update the data. If an error, the application server returns the error record to the client to check. After the client verifies and modifies the data, it can be abandoned and can continue to update. 3.1.4 The structure of the client program For end users, the client program in the multilayer architecture does not differ, on the structure, the client program is like a file-based single-layer application Like, it is still interacting with the user through standard data controls. However, different from the single-layer application is that the client program in the multilayer architecture is obtained by applying data by the iProvider interface provided by the application server, and is also updated by the iProvider interface. Note: When using MTS, you can choose not to use the iProvider interface. The advantage of using the iProvider interface is that the MTS can be given to the expertise in handling transactions. In the client program, the MIDAS connection component plays an extremely important role. Different MIDAS connecting members using different communication protocols:.... TDCOMConnection DCOM TSocketConnection Windows Sockets (TCP / IP) l TOLEnterpriseConnection OLEnterprise (RPCs) TCorbaConnection CORBA (IIOP) TRemoteServer and TMIDASConnection for compatibility Delphi code 3 is reserved. 3.1.5 Application Server The key components of the application server are remote data modules that provide an IDATABROKER interface. When the client has a connection to the application server, you will get an iProvider interface via the iDatabroker interface. Delphi 4 supports three types of remote data modules: TREMOTEDATAMODULE. This is an automation server that supports dual interfaces, which is suitable for use in DCOM, TCP / IP or Olenterprise. TMTSDATAMODULE. This is also an automated server that supports dual interfaces. The application server created with this type of remote data module is Active Library, which is a dynamic link library, suitable for use of DCOM, TCP / IP or Olenterprise. TcorbadataModule. This is a CORBA server for communication with CORBA customers. The above three remote data modules can be used as a container, but only non-visual components can be placed. In addition, the remote data module is typically placed or several TDataSetProvider or TPROVIDER components to provide an iProvider interface. The TDATABASE component and the TSession component can also be placed on the remote data module.

3.1.6 MTS MTS is a referred to as Microsoft Transaction Server, which is Microsoft to perform a service interface designed for transaction in a distributed environment. The advantage of the remote data module using the TMTSDataModule type is that MTS provides the application server based on role-based security mechanisms. Each customer plays a role that determines whether they can access the remote data module. TMTSDataModule has a function called IsCallerinRole, which can be used to check the role of the customer, and then open the function allowed by this role. The MTS provides the function of the buffer pool, which can put the connection to the database in the pool, and another customer can continue to use it when a customer does no longer need to connect, so that the application server does not have to log in to the remote database server again. Some readers may think that this feature is very similar to the KeepConnection property of the TDATABASE component. However, it is important to note that if the TDATABASE component is used, the KeepConnection property is best set to false. MTS provides powerful transactional ability, its "two-stage submission" technology enables applications to process transactions across servers. A MTS server can be implemented with a TMTSDataModule type remote data module, which can automatically activate or reverse as needed, in other words, only one instance of the module is created only when the remote data module receives the client's connection request. Maximize resources. It can be seen that the MTS server can have two ways of working, one is a single instance, an instance can handle a request for multiple customers, but if the customer is more, the remote data module has a bottleneck, which constitutes the application server. performance. The second is a multi-instance method, each customer requests an instance of a remote data module, which, several customers can access the database at the same time without queuing. In order to play the above advantages of MTS, the instance of the remote data module must be independent of the state, and the iProvider interface rely on status information, which causes conflicts. Therefore, the remote data module of the TMTSDataModule type often does not have an IProvider interface, but creates an interface to deliver data and application updates. Note: When using MTS, you cannot connect the database before instance of the remote data module. 3.1.7 Idatabroker interface and the remote data module on the iProvider interface Application server support the iDatabase, when the client is connected to the application server, look for the IDATABROKER interface. The IDATABROKER interface only implements a method called getProviderNames, calling this method to get a list, this list lists the TDataSetProvider and TProvider components on the application server. The ProviderName property of the TclientDataSet can specify one of the TDataSetProvider or TPROVIDER components. When the client is specified by the TDataSetProvider or TclIndername property of the application server via the iDatabaseTAME interface, the client is still in the state of the application, as long as the customer is still reference the iProvider interface, the status of the remote data module should be maintained, which is similar to MTS. Conflicts, also conflicts with single-instance CORBA servers.

Data is swapped between the client and the application server through the iProvider interface, however, most clients do not directly use the iProvider interface, but indirectly use the iProvider interface over the properties and methods of TclientDataSet. However, you can also get an iProvider interface through the Provider property, and then directly access the iProvider interface. Below this table lists the properties and methods of the iProvider interface, and lists the attributes and methods corresponding to the TPROVIDER component and the TclientDataSet components. IProviderTProviderTClientDatasetApplyUpdatesApplyUpdatesApplyUpdatesConstraints property Constraints client programs can access via this property DataDataDataDataRequestDataRequest client IProvider IProvider interface can interface to access by this method Get_ConstraintsConstraints client interface to access only through IProvider for implementing this method Get_DataGet_Data Data property GetMetaDataGetRecords (Count = 0) Internal GetRecordsGetRecords Used in GetNextPacketResetReset Use SET_CONSTRAINTSCONSTRAINTS clients can only access this property setParamsSetParams for params properties via iProvider interface.

Note: Many properties and methods of the iProvider interface depends on the status information of the remote data module, because of this, do not use the iProvider interface in applications using CORBA or MTS. 3.2 Selecting the connection between the client program and the application server, Delphi 4 provides four different types of connection or communication protocols, including DCOM, TCP / IP, Olenterprise, and CORBA. These different ways of connection have their own advantages and disadvantages. Which connection method is selected, depending on the number of customers, the customer's distribution, and how to publish the application. DCOM is a most direct connection, it does not require special running schedule software support. However, Windows 95 does not support DCOM unless the DCOM95 program is installed. To use the MTS security service, it is best to use the DCOM connection. The MTS security service is based on role. When a customer accesses the MTS through the DCOM, the DCOM tells MTS information about the customer's information, the MTS determines the role of the customer. If other connections are used, there is a need for special running period software support. The customer's call is first passed to these runtime software instead of MTS, and MTS cannot assign roles as soon as possible. The Suitable range of TCP / IP connection is very wide, for example, if the client is distributed on the web in the form of ActiveForm, it is best to use TCP / IP connection mode because you can't affirm whether the ActiveForm's computer supports DCOM, and support TCP / IP environment is very common. To use a TCP / IP connection, the application server side must run a dedicated running period software SCKTSrver.exe or Scktsrvc.exe, where Scktsrvc.exe is only suitable for Windows NT, which can be run as a service in the background. Unlike the DCOM connection, the customer's request is passed to SCKTSRVER.EXE or SCKTSRVC.EXE, then create an instance of the remote data module instead of creating an instance of a remote data module directly by a customer call. The MIDAS connection component on the customer program communicates with Scktsrvr.exe or Scktsrvc.exe via the iProvider interface. However, the client program is likely that there is an abnormality before the reference to the iProvider interface, and the TCP / IP connection method cannot detect this, and it is not possible to notify the application server, so it is possible to cause resources on the application server. The consequences of the release are not occupied. If you want to use Business Object Broker on your application server, you should use the Olenterprise connection. At this point, the Application server side and the client must install Olenterprise running period software. Delphi 4 is the only development tool that supports CORBA. CORBA-based client and application servers can seamlessly docking with other CORBA-based applications. To use the CORBA connection, you need ORB support, which provides a functionality similar to the Business Object Broker. 3.3 Creating a general step in creating a application server To create a multi-layer Client / Server application, first create an application server, then register or install the application server, only the app server is registered and is running, can you create a client. For a client program, you can connect the application server in the design period or the application server can be connected at the runtime. Note: If the client is not in the same system, it is necessary to register or install the application server on the client computer so that the application server can be connected to the design period.

Creating an application server is somewhat similar to creating a two-story database application, the main difference is that the application server needs to provide an iProvider interface, which is usually provided by the TDataSetProvider or the TPROVIDER component, or can via the data set component such as TTABLE PROVIDER properties. provide. The general step of creating a application server is: The first step is to start a new project using the "New Application" command on the "File" menu, then use the new command on the File menu, select the MULTI page, as shown in Figure 3.1. Select a remote data module. If you want to create a COM automation server, allow customers to access this server via DCOM, TCP / IP, Olenterprise, etc., select RemoteMod. If you want to create an Active Library that allows customers to access by MTS, select MTSData Module. If you want to create a CORBA server, select CORBA DATA. The second step is to put a data set component such as TTABLE, TQUERY, or TSTOREDPROC to the remote data module and perform the settings, so that they can access remote SQL databases. Try not to put the TDATABASE component on the remote data module because this may cause a name conflict. If you really want to connect to the SQL database with the TDatabase component, it is recommended to put the TDATABASE component on another data module and then reference the unit file of this data module. The third step is to put the TDataSetProvider or the TPROVIDER member on the remote data module, there is a data set component, there is a TDataSetProvider or TPROVIDER component corresponding to. Then, right-click the TDataSetProvider or the TPROVIDER component, select the exportfrom in data module command in the pop-up menu, which is to lead the Provider interface and register in the type library. The fourth step is to set the DataSet property of the TDataSetProvider or the TPROVIDER component specifies the database to be accessed, actually the data set component placed in the second step. The fifth step is to write code and realize business rules. Of course, this step is far from a few words. The sixth step is to save, compile, register, or install the application server. If you use DCOM, TCP / IP, Olenterprise as a communication protocol, the application server is like an automated server, you must register as ActiveX or COM servers. If you use MTS, the application server is DLL instead of EXE, and this time does not need to register the application server, and the DLL is installed as the MTS object to the MTS package. If you use CORBA, you may not register but it is best to register. If you want the client program to call the server interface to dynamically determine, you must install the server's interface in the interface repository. If you want to automatically activate your application server (if you haven't run it yet), the application server must be registered with OAD (Object Activation Daemon). The seventh step is if the application server does not use DCOM, you must install the relevant runtime software because other connection needs to support these periodless software. For example, for TCP / IP, you need to install Scktsrvr.exe or Scktsrvc.exe, which can only run in a Windows NT environment. For Olenterprise, you need to install the Olenterprise runtime version. For CORBA, you need to install Visibroker ORB. 3.4 Remote Data Module Application Server Key Parts is a remote data module.

Delphi 4 supports three types of remote data modules, which are TremoteDataModule, TMTSDataModule, TCORBADATAMODULE. 3.4.1 TREMOTEDATAMODULE To join a TremoteDataModule type remote data module, use the "new" command on the File menu, select the "Multitier" page, double-click the "Remote Data Module" icon, pop up the "Remote Data Module Wizard" dialog, As shown in Figure 3.2. Type the class name of the remote data module in the "Class Name" box, do not have to head with T. Delphi 4 will generate a derived class of TremoteDataModule with this name and generate an interface with this name. For example, if you type "MyDataServer" in the "Class Name" box, the class name of the remote data module is TMYDataServer, and the interface it implements iMyDataServer, and its ancestor interface is iDatabroker. Select a thread mode in the "Threading Model" box. You can choose "Single-Threaded", "Apartment-Threaded", "Free-Threaded" or "Both". In the "Instancing" box Select whether to generate multiple instances of the remote data module according to the client's request, you can choose "Single Instance" or "Multiple Instance". 3.4.2 TMTSDATAMODULE To join a TMTSDataModule type remote data module, use the "new" command on the "File" menu, select the "Multitier" page, double-click the "MTS Data Module" icon, pop up the "MTSData Module Wizard" dialog, such as Figure 3.3 shows. Figure 3.3 MTS Data Module dialog Type the class name of the remote data module in the "Class Name" box, do not have to head with T. Delphi 4 will generate a TMTSDataModule's derived class with this name and generate an interface in this name. For example, suppose typing "MyDataServer" in the "class name" box, the class name of the remote data module is TMYDATASERVER, and its interface is called ImyDataServer, and its ancestor interface is Idatabroker. For remote data modules for TMTSDataModule types, you must select a thread mode in the "ThreadingModel" box. You can choose "SINGLE", "Apartment" or "Both". Select Transaction Attributes in the "Transaction Attributes" box: If you select "Requires a Transaction", whenever the customer accesses the interface of the remote data module, it is related to the current transaction. Customers cannot apply for a new transaction in the transaction. Select "Requires A New Transaction", whenever the client accesses the interface of the remote data module, a new transaction is automatically started. If you select "Supports Transactions", the remote data module can be used in the transaction environment, you must apply for a new transaction when accessing the remote data module. If you select DOES NOT Support Transactions, the remote data module cannot be used in a transaction environment. Note: The MTS object can only be added to the ActiveX project, and if you try to join the TMTSDataModule type remote data module in an EXE project, Delphi 4 displays a prompt box, as shown in Figure 3.4.

Figure 3.4 A prompt block 3.4.3 TCORBADATAMODULE To join a TcorBadatamodule type remote data module, use the "new" command on the "File" menu, select the "Multitier" page, double-click "CORBA Data Module" icon, pop up "CORBA Data Module Wizard dialog, as shown in Figure 3.5. Figure 3.5 CORBA DATA Module dialog Type the class name of the remote data module in the "Class Name" box, do not have to head with T. Delphi 4 will generate a TCORBADATAMODULE with this name and generate an interface with this name. For example, suppose typing "MyDataServer" in the "class name" box, the class name of the remote data module is TMYDATASERVER, and its interface is called ImyDataServer, and its ancestor interface is Idatabroker. In the "Instancing" box specifies how the application server creates an instance of the remote data module, you can select "Shared Instance" or "Instance-Per-Client". If you select "Shared Instance", the application server only creates an instance of the remote data module to handle all customer requests, so the remote data module must be independent of the status, in other words, it is not possible to use the iProvider interface. If you select "Instance-Per-Client", the remote data module generates an instance whenever a customer tries to connect. As long as the connection between the client and the application server is not disconnected, the instance of the remote data module has been present. This mode allows the iProvider interface to be used. The only problem to consider is that the client probably stops, resulting in no connection to the application server normally. Application Server In order to avoid unnecessary resources, the application can periodically check if the customer is running, if not, delete the instance of the remote data module. Select a thread mode in the "Threading Model" box. You can choose "Single-Threaded", "Multi-Threaded". 3.5 The Provider remote data module is often placed or several TDataSetProvider or TPROVIDER components for providing an iProvider interface. Sometimes, you can also use the TDataSetProvider or TPROVIDER component without explicitly, but is indirectly supplied by the data set components such as TTABLE, TQUERY, or TSTOREDPROC's Provider attributes. The advantage of explicitly use TDataSetProvider or TPROVIDER components is to directly control which information contained in the packet, how the application server responds to the customer's request. If the TDataSetProvider or TPROVIDER component is explicitly used, you must set their DataSet property to specify the data set to access. 3.5.1 Controlling the fields in the packet To control which fields are included in the packet, first create a permanent field. In the future, only the permanent field is added to the packet. If you do not create a permanent field, all fields in the data set will be added to the packet. If the created permanent field contains the calculation field, since the value of the calculation field is calculated in the running period, although these fields can be added to the packet, these fields are transmitted to the client. Since the customer program is likely to edit the data, and the number of permanent fields you created should not be too small, otherwise it is possible to have a repetitive record in the application server.

For example, it is assumed to have a student transcript, composed of a student number, name, language score, mathematical score, historical score, and other fields, only Chinese grades, mathematics results, historical scores, etc., very There may be the above achievements of two students, which means that there is a repetitive record, which is not allowed. If you don't want to see a field, if you don't have this field, you can have the above error, and you can make this field (Tfield object) The provoderflags property contains the pfhidden element, indicating that this field is added to the data. In the package, but it is implied, the customer can't see it. It is important to note that if you use TQuery as a data set component on the application server, the SQL statement should select a sufficient field, even if the customer program does not require so many fields, there may be the above error. 3.5.2 Options Attribute This property is a collection that sets options for packaging and passing. If the PofetchBlobsondemand element is included, the blob field is generally not placed in the package, unless the client's TclientDataSet component is set to TRUE or explicitly call FetchBlobs. If you include a PofetchDetailsondemand element, indicating that the fields in the nested table are not placed in the package, unless the FetchOndeMand property of the client's TclientDataSet component is set to TRUE or explicitly call FetchDetails. If you include a POINCFIELDPROPS element, you represent the properties of the fields, including Alignment, MinValue, DisplayLabel, DisplayWidth, Visible, DisplayFormat, MaxValue, EditFormat, Currency, EditMask, DisplayValues, and so on. If you include a PocaScaDeletes element, the corresponding record in the subk table is also deleted when a record in the parent table is deleted. If the PocaScadeUpdates element is included, the record of the subk table is automatically updated when the value of the key field of the parent is changed. If you include a Poreadonly element, it means that "thin" customers are not allowed to apply for update data to TDataSetProvider. 3.5.3 Adding Customized Information in Packet When the client calls the DataRequest function request data via the iProvider interface, the application server is triggered on the application server side, so that the application server has the opportunity to add some custom information in the packet. . The client can call GetOptionalParam to retrieve this. OnGetDataSetPropertiesEvent Events This declaration: tgetdsprops = procedure (sender: Tobject; dataset: tdatanet; outproperties: olevariant); where the Properties parameter is an array of variable types for specifying the information you want to join. Each element of the Properties parameter consists of three parts: name, value, and a boolean number. Delphi 4 defines several standard information names, which are unique_key, default_order, change_log, server_col, constraints, dataset_context, dataset_delta, lcid, bderecord_x, table_name, md_fieldlinks, updatemode.

Program example follows: Procedure TAppServer.Provider1GetDataSetProperties (Sender: TObject; DataSet: TDataSet; out Properties: OleVariant); Begin Properties: = VarArrayCreate ([0,1], varVariant); Properties [0]: = VarArrayOf ([ 'TimeProvided' , Now, true]); Properties [1]: = Vararrayof (['TableSize', DataSet.Recordcount, False]); END; above this program, joined two custom information, a name called TimeProVided, it The value is the current date and time, TRUE indicates that this information can be returned by the client to the application server. Another information is called TableSize, its value is the number of records of the dataset, and false means that this information cannot be returned by the client to the application server. In the future, when the client applies for updating data, the TDataSetProvider's OnUpdatedata event can read the information in the packet. Program example follows: Procedure TAppServer.Provider1UpdateData (Sender: TObject; DataSet: TClientDataSet); var WhenProvided: TDateTime; Begin WhenProvided: = DataSet.GetOptionalParam ( 'TimeProvided'); ... End; 3.5.4 in response to customer requests for data In most multi-layer applications, the customer request data is automatically performed. The response of the application server to the client is also automatically, it automatically retrieves the data, package the data package, and passes the packet to the customer. Application Server is passed to the customer before passing the packet, and has the opportunity to edit it, for example, can encrypt data in sensitive, or delete some records based on some conditions. OnGetData event TDataSetProvider or TProvider component allows you to achieve the above functions, the program example is as follows: Procedure TDBClientTest.ProviderGetData (DataSet: TClientDataSet); Begin With DataSet Do Begin While not EOF Do Begin Edit; SensitiveData.AsString: = DoEncrypt (SensitiveData.AsString ); Post; next; end; end; end; 3.5.5 Response Customer Update Request Customer Apply Update Data to Application Server by calling Applyupdates. When the TDataSetProvider or the TPROVIDER component on the application server receives the customer's update request, you will trigger the onupdatedata event so you have the opportunity to edit the packet (Delta property). After exiting the handle of the ONUPDATA event, the TDataSetProvider or TPROVIDER component updates the data to the remote server. Update is a record of records. Each record will trigger the BeforeUpdateRecord event in a moment before updating so you have the opportunity to check and modify the data. If an error occurs, the ONUPDATEERROR event is triggered.

The reason for an error is usually the data violates the server's error correction rules, or the other client has also modified records, and it is just when the previous customer has applied for updates. The above error can be processed by the application server or processed back to the customer. Some errors may require users' intervention, which is to be handled. 3.5.6 Editing the Delta Packet before Updating the Database When the application server is called Applyupdates, the ONUPDATEDATA event will be triggered when applying Update data to the remote server, so that the application server has the opportunity to check the data to be updated, or modify the data. . Onupdatedata event is this statement: tProviderDataEvent = procedure (sender: Tobject; DataSet: TclientDataSet) of object; where the DataSet parameter represents the TclientDataSet component on the customer program so that the Delta property can be accessed to get the current updated packet. There is also an important attribute that needs access, this is the updatestatus property, this property represents the update type of the Delta packet. Program example follows: Procedure TDataModule1.Provider1UpdateData (Sender: TObject; DataSet: TClientDataSet);. Begin With DataSet Do Begin First; While not Eof Do Begin If UpdateStatus = usInserted then Begin Edit; FieldByName ( 'DateCreated') AsDateTime: = Date; POST; END; END; END; END; 3.5.7 How to locate records in handling the ONUPDATA event, in addition to the Delta packets, how to locate records or to update to the server on. By default, use the server to write the Delta packet to the remote server with an automatically generated SQL Update, Insert or DELETE statement, for example: Update Employees Set Empno = 748, Name = 'Smith', Title = 'Programmer 1' DEPT = 52 WHERE EMPNO = 748 and name = 'smith' and title = 'programer 1' and dept = 47 Unless otherwise specified, all fields in the packet will appear in the Update clause and where part, in other words In other words, you can locate a record in all fields. However, you can also selectively exclude some fields, which will be used to use the UpdateMode property. This property can be set to the following value: .upwhereAll All fields are used to locate records; .upwhereChanged only the key fields and changes are used to locate records; .upwhereonly onlys the keyfields are used to locate records. However, the updatemode property can only distinguish between key fields, but actual applications are often more complicated.

For example, you may not want to update the Empno field, and don't want the title and dept fields to appear in the WHERE section. This property is a collection that is a collection, which can contain the following elements: .pfinwhere This field The WHERE section of the automatically generated INSERT, DELETE, and UPDATE statements will not appear; .pfinUpdate This field will not appear in the UPDATE clause of the automatically generated Update statement; .pfinkey this field will appear as the SELECT statement executed by the update failed The WHERE section, the SELECT statement is used to select the current value of the error record; .pfhidden field will be used to locate the field, but it is hidden on the client. The following program example excludes the EmpNo field outside the Update clause, excludes the Title field and the DEPT field outside the WHERE section. Procedure TDataModule1.Provider1UpdateData (Sender: TObject; DataSet: TClientDataSet); BeginWith DataSet DoBeginFieldByName ( 'EMPNO') UpdateFlags: = [ufInUpdate]; FieldByName ( 'TITLE') UpdateFlags:. = [UfInWhere]; FieldByName ( 'DEPT'). .Updateflags: = [ufinwhere]; end; end; 3.5.8 In server-side error correction Most database management systems (RDBMs) have implemented error correction to ensure complete and consistency of data. The so-called error correction is actually the pre-specification of some rules, fields, and record values ​​must be in line with these rules. Most of the RDBMs that complies with SQL-92 supports the following error corrections: .Not Null field must have a value; .Not Null Unique field must be valued and cannot be repeated with other records; .CHECK field value must be within one range; .constraint Check the value of the field in the table stage; .primary key specifies one or several fields as a key field; .FOREIGN Key Specifies one or several fields to reference other forms. Of course, not all databases support the above error correction, and some servers also support other error corrections. In fact, many database desktop systems also support error correction, but the advantage of server-side error correction is that multiple client programs can share server-side error corrections without having to repeat some code in each client program. The application server can use the remote database server error correction rules to correct the data passed by the client, which is used to use the constraints property, as long as this property is set to True (default). If you do not want to borrow the error correction rule of the remote database server, you should set the consTRAINTS property to false. 3.6 Creating the General steps of Creating a Customer In a multi-layer architecture, a client must have at least a TClientDataSet component, and its role is to introduce a data set. TclientDataSet is inherited from TDataSet, which does not need to rely on BDE. The general step of creating a client is: The first step is to start a new project using the "New Application" command on the "File" menu, then use the "new" command on the File menu, then double-click "Data Module" Icon add a data module. The second step is to add one or several MIDAS connectors such as TDCOMCONNECTION, TSOCKETCONNECTION, TOLENTERPRISECONNECONNECTION, TOLENTERPRISECONNECONNECTION, TOLENTERPRISECONNECTION, TCORBACONNECTION, TREMOTSERVER, or TMIDASCONNECTION to the data module. As for which MIDAS connection component is selected, it depends on the communication protocol.

The third step is to set the relevant attribute to specify and connect the application server, which is related to the specific MIDAS connection member. Some MIDAS connectors also have an ObjectBroker property that can specify a TSIMpleObjectBroker component so that the application server can be dynamically selected. The fourth step is to put one or several TclientDataSet components on the data module, set the RemoteServer property to specify a MIDAS connection component, set the ProviderName property to specify the TDataSetResolver or TPROVIDER component on the application server, so that the client can via the iProvider interface and app Server communication. The fifth step is to put a TDataSource component on the data module and set its DataSet property to specify the TclientDataSet component, put a data control as TDBGRID on the form, set its DataSource property to specify the TDataSource component. At this point, a simple customer program is created. 3.7 Connection to the Application Server To establish a connection to the application server, the client must use one or several MIDAS connection components that can be found on the "Midas" page of the component palette. Different types of MIDAS connectors use different communication protocols to locate the application server. These MIDAS connection members are described in detail below. 3.7.1 Use DCOM to connect to connect to the application server using the DCOM mode, and use the TDCOMCONNECTION component. The COMPUTERNAME attribute of the TDCOMConnection component is used to specify the computer where the application server is located. If the computername property is empty, the TDCOMConnection assumes that the application server and the client can be found on the same computer, or the application server can be found in the system registry. Conversely, if the application server is not registered at the client, and with the client is not on the same computer, you must set the computername property. Even if the application server is registered in the client, you can still set the computername property to re-specify the application server on another computer. ComputerName properties are typically set to the host name or IP address of the computer. If the specified host name or IP address is illegal or not found, TDCOMConnection triggers an exception. If the client needs to dynamically select the application server during operation, it is best not to switch with the computername property, and join a TSIMpleObjectBroker component, then specify this TSIMpleObjectBroker component by the ObjectBroker property. 3.7.2 Connection with TCP / IP Use TCP / IP mode to connect to the application server, you need to use the TSOCKETCONNECTION component. TCP / IP mode is a widely used connection method because supporting TCP / IP environments is quite common. TsocketConnection uses the Address property or Host property to locate the computer where the application server is located, the former is used to specify the IP address, the latter is used to specify the host name, both attributes are mutually exclusive, only one of them needs to be set. In addition, it is also possible to set the port number to specify the port number, which must be consistent with the port number used by SCKTSrver.exe or SCKTSRVC.exe running on the application server. The default value is 211.3.7.3 Use the OLENTERPRISE connection to connect to the application server. It is necessary to use the ToLenterpriseConnection component. If you want to connect to the application server directly, you don't pass the Business Object Broker, set the computername property to specify the host name where the application server is located, it is like the DCOM mode.

If you want to connect to the application server via the Business Object Broker, set the BrokerName property to specify the name of the Business Object Broker. Computername properties and brokername properties are mutually exclusive, set one, and the other is emptying. 3.7.4 Connection with CORBA Use CORBA to connect to the application server, you must use the TCORBACONNECTION component. For CORBA modes, you only need to set an interface of the RepositoryID property to identify the CORBA data module because the Smart Agent automatically locates an available application server. However, if you do not want the Smart Agent to automatically locate an application server, try to specify a specific application server, set the hostname property to specify the host name or IP address of the application server. The TCORBACONNECTION component can obtain an interface to the CORBA data module on the application server in two ways: If you want to use a static connection mode, you must add the _tlb.pas file (generated by the Type Library Editor) to the client program. The static connection method can not only check the type of compile period, but also the running speed is faster. If you want to use a dynamic cable, the interface of the CORBA data module must be registered with InterfaceRepository. 3.7.5 Identify how to locate the computer where the application server is located, how to identify the application server itself after you have locate your computer. If you connect the application server using the DCOM, TCP / IP or Olenterprise mode, you can identify the application server via the ServerName property or ServerGUID property. Where servername is used to specify the application server, it is actually a registered OLE automation object name. The ServerGUID property is used to specify the global identification number of the remote data module. If the ServerName property is set, the serverGUID property is automatically set. If you use a CORBA way to connect to the application server, you should use the repositoryID property to identify the interface of the CORBA data module on the application server. 3.7.6 TSIMPLEOBJECTBROKER If the client needs to dynamically select the application server during operation, it is best to switch with the TSIMPLEOBJECTBROKER component without using the computername property. TsIMpleObjectBroker automatically maintains a list of available application servers. When the MIDAS connection component needs to connect to an application server, it applies to TSIMPLEOBJECTBROKER, and TSIMPLEOBJECTBROKER usually provides an application server. If the application server provided by TsImpleObjectBroker does not work, TsimpleObjectBroker will change one, until the MIDAS connection component is connected to the application server. Once the MIDAS connection member is connected to the application server, it automatically saves the relevant situation of the application server to the relevant properties, such as ComputerName, Address or Host, because the MIDAS connection component may disconnect, and later connect again At this time, you don't have to apply to TsImpleObjectBroker. In the case of using Olenterprise or CORBA, don't use the TSIMPLEOBJECTBROKER component, because both methods have their own special intermediary services. 3.7.7 Starting the connection After the above-mentioned settings, you can connect the application server.

However, before connecting the application server, it is best to set the TClientDataSet's RemoteServer attribute to specify a MIDAS connection component, and then set the ProviderName property to specify the TDataSetResolver or TPROVIDER component in the application server. When the client tries to access the iProvider interface, the connection to the application server is automatically established, for example, set the TclientDataSet's Active property to True. Of course, it is also possible to connect or disconnect or disconnect by the connect attribute of the MIDAS connection member. The BeforeConnect event is triggered before the connection is to be established with the application server. When the connection to the application server is established, the AfterConnect event is triggered. 3.7.8 Disconnect Connection When the following is performed: This is set to False. Close the client or MIDAS connection member is deleted. After the .midas connection member, ServerName, ServerGUID, ComputerName, Host, Address, etc. also dispensed the original connection, and then re-establish the new application server. Note: Try not to use the properties such as modification computername, Host to switch the application server, preferably use TSIMPLEOBJECTBROKER, or use several MIDAS connection components to establish a connection. The BeforeDisconnect event will be triggered before the connection to the application server will be disconnected. After the connection is truly disconnected, the AfterdisConnect event is triggered. 3.8 Calling the interface on the server You can get an iProvider interface through the TclientDataSet's Provider property. In fact, most cases don't need to call directly to the iProvider interface, because the call to the iProvider interface has been encapsulated in the properties and methods of TclientDataSet, the only exception, the DataRequest function can only be called via the iProvider interface. The appserver attribute of the MIDAS connection member can get the interface of the remote data module on the application server. You can call the remote data module by this interface, for example: MyConnection.AppServer.SpecialMethod (x, y); this way of calling is Dynamic That is, the compiler does not check the parameters of Specialmethod, and even there is no specialmethod. Since the compiler does not perform type check, it is possible to fail when the runtime is actually invoked. Moreover, dynamic keratual does not have a static connection to execute fast. If you use DCOM or CORBA as a communication protocol to connect to the application server, it is best to use a static connection method to access the remote data module interface, the method is to enforce type conversion to the AppServer property with a specific interface type. Assuming that the interface of the remote data module called iMyAppServer (its superior is iDatabase), the program example is as follows: with myconnection.appserver as ImyAppServer do Specialmethod (x, y); the above line code is suitable for the DCOM mode, the following line code is suitable for CORBA Way: with iunknown (MyConnection.App Server) As ImyAppServer Do SpecialMethod (x, y); For DCOM mode, use a static connection mode to call the interface of the remote data module, and its type library must be registered on the client. To register the type library, you can call the Tregsvr.exe in the Delphi4 / bin directory.

For CORBA mode, to call the interface of the remote data module using a static connection mode, you must reference the _tlb.pas file generated by the type library editor in the client program. For TCP / IP or OLENTERPRISE mode, it is possible to invoke the interface of the remote data module using a real static connection method. However, the performance can be improved by the scheduling interface of the remote data module, and the program is as follows: VARTEMPinterface: ImyAppServerDisp; BeginTempinterface : = MyConnection.AppServer; ... Tempinterface.SpecialMethod (x, y); ... END; To access the remote data module by calling the interface, you must reference the type library editor generated in the client program. 3.9 In the client correcting SQL Explorer, the server-side error correction and default expressions can be introduced into a data dictionary so that the client can borrow the server-side rule to borrow the server-side rule by the application server. This is the so-called client correcting. If the user is in violation of the rules if the user enters or modifies the rule, the data will not be passed to the application server side, and will not be passed to the RDBMS terminal. It can be seen that the client error correction can avoid passing the wrong data to the remote database server, saving unnecessary transmission on the network, because these data will be returned even if the data is passed to the remote database server. However, sometimes it needs to be temporarily prohibited at the client correct. For example, it is assumed that one error correction rule requires a field-based maximum, and the client can only retrieve several records at a time, that is, the maximum value of the client statistics is different from the server-side statistics. If the client uses filtration, it is also possible to make the maximum value that the client statistics is different from the server-side statistics. In the above case, it is necessary to temporarily prohibit error correction. To temporarily prohibit error correction, you can call TclientDataSet's DisableConstRAINTS. DisableConstraint is actually adding an internal reference count plus 1. When this reference count is greater than 0, it is not allowed to correct. To re-correction, you can call the TclientDataSet's EnableConstRAINTS. EnableConstraints is actually reduced by one internal count. When this count is reduced to 0, it can be re-performed. 3.10 Subproduction Data When the client retrieves the data from the application server, a copy of these data is established in memory. After editing the data, the TclientDataSet is specifically stored with a Delta property store, including update, deletion, and insert records. In order to make the modified data permanently, apply to the database to update the data. 3.10.1 Updating data General step First, the client program to call the ApplyUpdates function to apply to the application server, and the ApplyUpdates function passes the Delta property to the application server via the iProvider interface. After the application server receives the user's application, apply to the remote database server and temporarily cache the record that is considered an error by the remote database server. The TDataSetProvider or TPROVIDER component on the application server returns the error record to the client, including error information and error code. After the client receives these error records, you can check and modify and continue to update. Note: If the application server side uses the remote data module of the MTS type, you cannot provide an iProvider interface. In this case, you must directly apply for update data through the interface of the remote data module.

3.10.2 ApplyUpdates Function When the user modifies the data, the ApplyUpdates function should be called to apply for update data to the application server. The Applyupdates function has only one MaxErrorS parameter to specify a maximum number of errors. If the error records exceeds this parameter, the update stops. If the MaxErrorS parameter is set to 0, as long as the application server finds an error record, the update operation stops. If the MaxErrorS parameter is set to -1, when the application server finds an error record, try updating the next record, and so all the records have been returned later. The ApplyUpdates function will return the number of errors that are actually encountered, and the application server will return to those records with errors. 3.10.3 Nuclear Error Record When the application server returns an error record to the client, the ONREConcileError event will be triggered on the client, so you have the opportunity to check and modify the record. OnReconcileError event is declared as: TReconcileErrorEvent = Procedure (DataSet: TClientDataSet; E: EReconcileError; UpdateKind: TUpdateKind; var Action: TReconcileAction) of object; wherein, the parameter is the DataSet name TClientDataSet member, whereby access to a field of the dataset NewValue , OldValue, CurValue and other properties, thus analyzing the reason for errors. The method of tclientDataSet can also be called by the DataSet parameter, but it is not possible to make actions that may result in data modification, otherwise it may cause a dead cycle. The E parameter is a pointer to the EREConcileError object, which can extract the reason for error information and errors. Updatekind parameter indicates which operation leads to an error, which can be the following value: ukmodify, ukinsert, ukdlete (delete). The Action parameter is used to decide whether to continue to update the dataset after exiting the handle of the OnReconcileError event, which can be set to the following: Raskip, Raabort, Ramerge, RacorRect, Racancel, Rarefresh. The following example demonstrates how to program calls a dialog box RecError unit: Procedure TForm1.ClientDataSetReconcileError (DataSet: TClientDataSet; E: EReconcileError; UpdateKind: TUpdateKind, var Action TReconcileAction); Begin Action: = HandleReconcileError (DataSet, UpdateKind, E) END; 3.10.4 Refresh Record The client creates a copy of the data in memory, and working on this copy, and other users may have modified the data, that is, the data in the memory is not the actual data in the database. . In order to make the data in the memory are currently the latest, the TclientDataSet can be called Refresh. However, before calling refresh, ensure that the client has no undetermined modification. In other words, there is no modification in the client's log, otherwise it will trigger an exception. However, the TclientDataSet's Refreshrecord can refresh the current record, and the changes recorded in the log will continue to be reserved. Note: Calling Refreshrecord may bring conflicts.

Therefore, before calling refreshrecord, it is best to check if there is a unrescribed modification. If there is, it triggers an exception. The program is as follows: if ClientDataSet1.UpdateStatus <> USUNModified Thenraise Exception.create ('You Must Apply Updates Before Refreshing the current record. '); ClientDataSet1.Refreshrecord; 3.10.5 From the application server acquisition parameters, the client needs to get parameters from the application server:. The client needs to know the output parameters of the stored procedure. The client needs to initialize the input parameters of TQuery or TSTOREDPROC. To get parameters from the application server, call the TclientDataSet's FetchParams function, this function will return the parameters and the value of the params property. The parameters can also be obtained in the design period, and the method is: Right-click the TclientDataSet component and select the "fetch params" command in the pop-up menu. Note: Whether you call the fetchParams function in the runtime, or the "fetchParams" command is used in the design period, the client must have already connected to the application server and get the iProvider interface, because these parameters are provided by the TDataSetProvider or TProvider component on the application server. The DataSet attributes must specify the TQuery component or TSTOREDPROC component. You can also set the params property on the client, and then pass the parameters to the application server. 3.11 Customize the structure of the application server MIDAS is very flexible, you can customize the application server to adapt to the actual needs. You can define application servers from two aspects, one is to extend the interface of the remote data module, and the other is to use a custom dataset. The remote data module is the core component of the application server, which provides the basic interface of the application server and the client program, unless the client calls the iProvider interface. If the application server uses the remote data module of the MTS type, the client can only communicate with the application server through the interface of the remote data module. If you try to bypass the MTS agent, it will be invalid, especially if the remote data module of the MTS type can be independent of the status, this time, if the MTS agent is bypassed, it is possible to cause the program to crash. Similarly, the CORBA data module of the single instance mode is also independent of the state, and there is also the above problems. In order for the client to easily access the MTS or CORBA data module (because there is no approvider interface at this time, you must extend the interface of the remote data module, add some methods to make the customer program call. The interfaces of the MTS or CORBA data module are inherited from Idatabroker. To add new properties or methods to the interface, you can have two ways: First, use the "Add to Interface" command on the "Edit" menu to pop up the "Add to Interface" dialog, as shown in Figure 3.6. Figure 3.6 "Add to Interface" dialog Type a declaration of attributes or methods in the "DECLATION" box, click the OK button, Delphi 4 adds the attribute or method into the interface of the remote data module. The second is to open the Type Library Editor using the "Type library" command on the View menu, as shown in Figure 3.7. Select an interface node in the Type Library Editor, such as IXXH in Figure 3.7, and then click the "New Method" button on the toolbar or the "New Property" button.

After adding a new member, set the relevant properties. To explain, many attributes are invalid for the interface of the remote data module of the CORBA type. For a COM-based remote data module (TREMOTEDATAMODULE or TMTSDATAMODULE), new members will appear in the description file of the implementation unit and the type library of the interface. For CORBA-based remote data modules (TCORBADATAMODULE), new members will automatically generate a _tlb unit in addition to the implementation unit of the interface. This unit must be referenced if the client needs to access the CORBA remote data module. Alternatively, you can generate an IDL script with the Type library editor and then register the interface with Interface Repository and Object Activation Daemon. The client program can obtain the interface of the remote data module through the App Server property of the MIDAS connection component, and then call the remote data module by the interface. Note: If you use MTS, each method of adding to an interface must be called in the final call, telling the MTS transaction to end. For example, the following function is used to get record GetCustomerRecords: Function TMyRemoteDataModule.GetCustomerRecords (MetaData: Boolean; outRecsOut: Integer): OleVariant; BeginTryIf MetaData then Result: = CustomerProvider.GetRecords (0, RecsOut); Else Result: = CustomerProvider.GetRecords ( -1, RecsOut); SetComplete; ExceptSetAbort; end; end; the client can call a function GetCustomerRecords: ClientDataSet1.Data: = CorbaConnection1.AppServer.GetCustomerRecords (False, RecsOut); another example, the following function is used ApplyCustomerUpdates application to update data: Function TMyRemoteDataModule.ApplyCustomerUpdates (Delta: OleVarant; MaxErrors: Integer; outErrorCount: Integer); OleVariant; BeginTryResult: = CustomerProvider.ApplyUpdates (Delta, MaxErrors, ErrorCount); SetComplete; ExceptSetAbort; end; end; client , ApplyCustomerUpdates can call the function: With ClientDataSet1 DoBeginCheckBrowseMode; If ChangeCount> 0 thenReconcile (MyConnectionComponent.AppServer.ApplyCustomerUpdates (Delta, MaxErrors, ErrCount)); End; on the application server, generally based dataset of BDE member to introduce data , The DataSet property of the TDataSetProvider or TPROVIDER component specifies this data set component. However, by default, the TDataSetProvider or TPROVIDER component can communicate directly with the remote database server with a dynamically generated SQL statement without the need to reduce a link.

However, TDataSetProvider or TPROVIDER components sometimes need to apply directly to the data set components on the application server, because the application server is used by the BDE-based dataset, but a TclientDataSet or a custom dataset. At this time, you need to set the resolvetodataset attribute to True. If you can determine that the application server does not need to use BDE, it is best to use the TDataSetProvider component instead of the TPROVIDER component, TDataSetProvider does not need to rely on BDE, which is beneficial to publish and install the application server. 3.12 Multi-layer architecture Under the structure of the client applies for update data to the application server, the TDataSetProvider or TPROVIDER component automatically adds the routine of the update data, in other words, it is under the control of the transaction. If the number of records of the error does not exceed the MaxErrorS parameter, the transaction is officially submitted to the remote database server, otherwise it will be rolled back. In order to better support the transaction, you can manage the connection and transaction of the database with the TDATABASE component, which is the same as the two-layer architecture. If you use MTS on your application server, you can get more powerful transaction power. The MTS transaction can extend to all business logic instead of database access. In addition, MTS's "two-stage submission" technology enables MTS to process transactions across multiple databases. To explain, the "Two-Stage Submit" technology is currently only fully implemented in Oracle and MS-SQL Server. If you want to transaction across the database, and some of them are not Oracle and MS-SQL Server, it is possible to errouce. As mentioned earlier, if you want to use the remote data module of the MTS type, it should be extended to encapsulate the transaction function of MTS with custom methods. 3.13 Designing the client program to ActiveForm Delphi 4 You can use the distributed database structure to the Internet / Intranet, embed the client as an ActiveForm to let people download, and then execute locally. The application server on the Internet / Intranet must support the DCOM or TCP / IP connection mode. Similarly, the client designed to be ActiveForm must also support the DCOM or TCP / IP connection mode, because downloading the Olenterprise or CORBA operation period may not be installed on the ActiveForm's computer. software. When designing the interface of the customer program, use ActiveForm instead of a general form. To this end, first, use the "new" command on the "File" menu to open the "ActiveX" page, select the "ActiveX" page, double-click the "ActiveForm" icon, open the ActiveForm wizard, as shown in Figure 3.8. Click the "OK" button, Delphi 4 creates an ActiveX project. There is only one blank ActiveForm in this project. The following steps are like design a general "thin" customer. After designing a "thin" customer program in the form of ActiveForm, you need to post it to the web server for people to download. To do this, first, use the "Web DeploymentOptions" command on the "Project" menu to open the Web Deployment Options dialog, then set the options for the web release, mainly to specify the URL of the ActiveForm on the web server. Finally, use the "WebDeploy" command on the "Project" menu to post the ActiveForm on the web server. To test this Active form, you can use a web browser such as IE to download web pages that embed an ActiveForm.

转载请注明原文地址:https://www.9cbs.com/read-95947.html

New Post(0)