You are on page 1of 46

SimSci

PRO/II 9.3
COM Server
Programmers Guide
and Tutorial

May 2014
All rights reserved. No part of this documentation shall be reproduced, stored in a retrieval
system, or transmitted by any means, electronic, mechanical, photocopying, recording, or
otherwise, without the prior written permission of Invensys Systems, Inc. No copyright or patent
liability is assumed with respect to the use of the information contained herein. Although every
precaution has been taken in the preparation of this documentation, the publisher and the author
assume no responsibility for errors or omissions. Neither is any liability assumed for damages
resulting from the use of the information contained herein.

The information in this documentation is subject to change without notice and does not represent
a commitment on the part of Invensys Systems, Inc. The software described in this documentation
is furnished under a license or nondisclosure agreement. This software may be used or copied
only in accordance with the terms of these agreements.

2014 by Invensys Systems, Inc. All rights reserved.

Invensys Systems, Inc.


26561 Rancho Parkway South
Lake Forest, CA 92630 U.S.A.
(949) 727-3200
http://www.simsci.com/

For comments or suggestions about the product documentation, send an e-mail message to
ProductDocumentationComments@invensys.com.

All terms mentioned in this documentation that are known to be trademarks or service marks have
been appropriately capitalized. Invensys Systems, Inc. cannot attest to the accuracy of this
information. Use of a term in this documentation should not be regarded as affecting the validity
of any trademark or service mark. Invensys, Invensys logo, PRO/II, and SimSci are trademarks of
Invensys plc, its subsidiaries and affiliates.
Table of Contents
1 Introduction ..............................................................4
1.1 Summary ................................................................................ 4

1.2 Component Object Model ....................................................... 4

1.3 About this Document .............................................................. 5

1.4 Additional Documentation ....................................................... 5

2 Hardware and Software Requirements ...................6


2.1 Programming Prerequisites .................................................... 6

3 COM Server Overview ..............................................8


3.1 Structure of the PRO/II COM Server ....................................... 8

3.2 PRO/II Data Organization ....................................................... 9

3.3 Data Types ........................................................................... 10

4 Basic Operations ....................................................12


4.1 Outline of a COM Server Application .................................... 12

4.2 Start the PRO/II COM Server ................................................ 13

4.3 Open a PRO/II Database ...................................................... 14

4.4 Load Data Objects into Memory............................................ 15

4.5 Read and Write Attributes ..................................................... 15

1
4.6 Perform Units-of-Measure Conversion .................................. 16

4.7 Commit and Free Objects ..................................................... 16

4.8 Save and Close the Database .............................................. 17

4.9 Shut down the PRO/II COM Server ...................................... 17

4.10 Modifying the Simulation Database .................................... 17

5 Writing Applications in Different Languages .......18


5.1 Description of Example ......................................................... 18

5.2 Visual Basic 6.0 Implementation ........................................... 18

5.3 C++ Implementation ............................................................. 19

5.4 VB Script Implementation ..................................................... 21

6 Using the Operator Interface .................................23


6.1 Introduction ........................................................................... 23

6.2 Initial setting of Excel application .......................................... 23

6.3 Viewing the inbuilt Example .................................................. 24

6.4 Creating a new operator interface ......................................... 24

6.5 Editing Comments ................................................................ 25

6.6 Running the Simulation ......................................................... 28

7 COM Server Examples ...........................................30


7.1 Introduction ........................................................................... 30

7.2 Accessing Calculated Stream Conditions ............................. 30

2
7.3 Calculating Stream Properties .............................................. 30

7.4 Accessing Calculated Column Data ...................................... 33

7.5 Invoking an Excel macro from the PRO/II GUI ...................... 35

7.6 Performing a Flash Calculation ............................................. 39

7.7 Flash Drum Outlet Conditions ............................................... 42

3
1 Introduction
1.1 Summary
The PRO/II COM Server provides read/write access to information in a PRO/II simulation
database from COM-aware applications and languages. You can write applications to
access data (both input and calculated) in PRO/II simulation databases using Microsoft
Excel, Microsoft Visual Basic, and C++ (using the MFC or ATL frameworks).

Applications created using the PRO/II COM server interface can:

Create specialized reports and datasheets

Transfer data between PRO/II and other applications or databases, or

Define case management scenarios where results are analyzed based on


changes to different types of inputs

The PRO/II COM server also provides calculation utilities, which allow a client application
to:

Perform flash calculations

Calculate stream properties, and

Solve the flowsheet

Client applications can also modify information in the PRO/II simulation database and
rerun the flowsheet simulation. However, the PRO/II COM Server is not intended as a
complete replacement for using the PROVISION GUI or PRO/II keyword file to define a
complete simulation. Additional information on the effects of modifying an existing
database using the PRO/II COM Server is explained in Chapter 4 under the Modifying
information in the Database.

1.2 Component Object Model


The Component Object Model (COM) is the Microsoft-developed architecture for defining
and building reusable software components. It is the foundation for many other
technologies, including OLE (Object Linking and Embedding), OLE Automation, ActiveX,
and OPC (OLE for Process Control). It is also used as implementation architecture for
industry standards such as CAPE-OPEN.

Introduction 4
1.3 About this Document
The purpose of this document is to provide information on using the PRO/II COM Server.

Visual Basic is a common language used for COM application development and is
included in many Microsoft products, including Excel. The examples in this document are
written primarily in Visual Basic.

Chapter 2 describes the programming prerequisites necessary to develop applications for


the PRO/II COM Server.

Chapter 3 describes the overall structure of the PRO/II COM Server.

Chapter 4 describes the basic programming steps required to create an application to


access data in a PRO/II simulation database. Each step is illustrated with a simple Visual
Basic code example.

Chapter 5 provides a short, complete example application implemented in different


programming languages.

Chapter 6 contains many example applications for performing common operations with
the PRO/II COM Server.

1.4 Additional Documentation


For additional information on the PRO/II COM Server, refer to these documents, included
with the Database Server Programming documentation:

PRO/II COM Server Reference Guide

The primary reference materials for Visual Basic, Excel, and other Microsoft
Technology are the documents and reference material included with the
Microsoft products. The website msdn.microsoft.com is the primary starting
point for developers needing more information on specific Microsoft technologies.

Introduction 5
2 Hardware and Software
Requirements
To develop PRO/II COM applications a PC with an installed version of PRO/II is required.
Refer to the PRO/II Installation Guide for specific hardware and software requirements for
specific versions of PRO/II.

You will also need the appropriate development environment or development tool for
writing COM applications. This includes (but is not limited to):

Visual Basic

Visual C++

Microsoft Excel

The applications you create using the PRO/II COM Server can run on any platform that:

Supports the version of PRO/II being targeted and

Supports the runtime environment required by the development tool you are
using

Some calculation features of the PRO/II COM server also require a valid PRO/II license.

2.1 Programming Prerequisites


To effectively write applications with the PRO/II COM Server you should be:

Familiar with PRO/II

Familiar with the specific development language or tool you are planning to use,
such as Visual Basic or C++

Knowing how to access and use COM objects from the chosen development
language

If the chosen development tool is Microsoft Excel, then it is helpful to be familiar with some
of the advanced features of Microsoft Excel, including:

Accessing values in spreadsheet cells using Visual Basic, the macro language of
Excel

Using the pre-defined Excel objects in Visual Basic, such as the Application,
Workbook, Worksheet, and Range objects

Hardware and Software Requirements 6


Creating and using named spreadsheet cell ranges

Creating and using spreadsheet templates and add-ins

Record, write, and edit macros in Visual Basic for Applications

Refer to the on-line help for your Microsoft product. You can also visit
http://office.microsoft.com and http://msdn.microsoft.com search for "Excel Object
Model Overview") for more information.

Hardware and Software Requirements 7


3 COM Server Overview
3.1 Structure of the PRO/II COM Server
Figure 1 shows the basic structure of the PRO/II COM Server and the applications that
use it.

Figure 1. PRO/II COM Server Architecture

The PRO/II COM Server consists of the following parts:

The PRO/II COM Server provides the support for the COM interface into PRO/II.
COM applications written in Excel, Visual Basic, C++, and other COM-aware
languages interact with this interface. The COM Server is called p2oledbs.exe
and is located in the BIN directory under the PRO/II installation path

The PRO/II Server consists of the various DLLs used by PRO/II with PROVISION
for GUI and keyword support. This support includes the functions that access
and manage the PRO/II data objects. It also includes many calculation features
of PRO/II such as solving a flowsheet, calculating stream properties, and
performing flash calculations

The PRO/II Database (with extension "prz") contains the simulation data

The various client applications, which can access the PRO/II COM server, include the
following:

VB Script

COM Server Overview 8


Visual Basic (Standalone)

Visual Basic for Application: VBA is the macro language of Microsoft Office and
certain other applications. Microsoft Office components Excel and Access would
be typical applications to use the PRO/II COM Server

C++, C#, or other COM applications: many languages provide support for access
to COM objects and methods

PRO/II Class Library: The PRO/II Class Library is another COM Server that can
be used to access information in the PRO/II Server. This server is called
p2wrap81.dll (for PRO/II 8.1). Excel macros, Visual Basic applications, and
applications written in other COM-aware languages can access the PRO/II Class
library to ultimately gain access to the PRO/II COM Server

3.2 PRO/II Data Organization


Simulation data in PRO/II are stored as Data objects in the database. A data object
contains integer, real, and text data (Attributes) accessible by individual attribute names.
Data objects are organized into Classes; each class defines a common set of attributes.
For example, the data object class Flash defines the data attributes used by all Flash
Drum unit operations. The PRO/II COM Server Reference Guide provides the list of data
classes and attribute names that are available through the PRO/II COM Server.

Most simple unit operations store all their data into a data object of one class. For
example, the Mixer unit operation stores all of its data, input and calculated, into the
"Mixer" data object class. Complex unit operations and streams, however, store their data
into multiple data object classes. A stream, for example, stores its input data in the
"StreamIn" class, the calculated process conditions in the "Stream" class, and the
calculated stream properties in several additional data classes (such as the "StrBulkProp"
class). Refer to the PRO/II COM Server Reference Guide to identify the specific data
object classes containing the desired input or calculated data.

There is a common set of methods in the PRO/II COM Server to access the PRO/II data
objects. The common tasks for these data objects are as follows:

Creating a new data object

Loading ("activating") an existing data object from the database into memory

Reading and writing attribute data from and to the data object

Saving ("committing") the data object back to the database

Deleting a data object

The methods to perform these tasks are described briefly in this document and in detail in
the PRO/II COM Server Reference Guide.

COM Server Overview 9


3.3 Data Types
The actual data in the PRO/II Data Objects is stored as "integer", "real", or "text". The
"integer" data is 32-bit; the "real" data always contain double precision floating point
numbers.

Text data is divided into subcategories. Raw text data, such as the "NotesIn" attribute of
unit operations, contains simple text. Other text data is considered as a type of "identifier",
or ID type.

PRO/II uses several ID data types described in the following table. These "ID" datatypes
are used to identify text strings as being names of actual objects in the database. These
names typically have syntax limitations, such as string length, as described in the table
below.

Table 1: Syntax Limitations


PRO/II ID Data Type Character Notes
string length
Component ID 16
Thermodynamic method ID 12
Stream ID 12
Unit Operation ID 12
Specification object ID 12
Reaction Set ID 12
Reaction ID 24 The first 12 characters represent the reaction
ID; the last 12 characters represent the
reaction set ID to which it belongs. For
(Contd.)
example, REACTION1 SET1
Procedure ID 12
Recycle loop ID 12
Unit of Measure 26 The first four characters represent the UOM
th
class; the 5 character is a blank space,
followed by the measurement unit. For
example, a temperature in Kelvin would be
represented as TEMP K, a pressure in psia
would be represented as PRES PSIA

COM Server Overview 10


PRO/II uses several special values to indicate missing data, or data that was not supplied
by the user in the keyword file or in the GUI or data that was not calculated. The following
table summarizes the missing values for various data types:

Table 2: Missing values for various data types


Data Type Missing Value
Integer -2111111111
Real (Double precision by default) -1.5 E+35
Character string Blank string
PRO/II ID types Blank string

To test for a missing real value, use the following code.


If (value < -1.0 E+35) Then
' Value is missing
End If

COM Server Overview 11


4 Basic Operations
4.1 Outline of a COM Server Application
A PRO/II COM application performs the following basic steps:

1. Start the PRO/II COM Server

2. Open a database

3. Load a data object into memory

4. Read/write attributes (performing Units-of-Measure conversion if required)

5. Save the data object back to the database (if it was modified) and free the object

6. Close the database

7. Shut down the PRO/II COM Server

These seven steps are performed using three types of objects provided by the PRO/II
COM Server as outlined below.

Server Object: This is the main server object and is used to initialize and manage
interaction with the PRO/II COM Server.

Database Object: This object is used to interact with a specific simulation database.

The PRO/II COM Server can open only one database at a time.

Data Object: Each data object is used to interact with a specific object in PRO/II:
components, thermodynamic systems, streams, and unit operations. Data are read from
and written to these objects using the GetAttribute and PutAttribute methods.

For more information on each of these objects, refer to the PRO/II COM Server Reference
Guide.

Basic Operations 12
The basic sequence of operations for an application using the PRO/II COM Server is
shown in Figure 2.

Figure 2. COM Application Program Flow

The following sections describe each of these steps in more detail. The examples are
illustrated using the Visual Basic language.

4.2 Start the PRO/II COM Server


The first step that must be performed by a PRO/II COM Application is to create and
initialize the PRO/II COM Server. To create the Server Object, use the language-specific
method, which creates a COM object. In Visual Basic, the required code is:

Dim P2SRV as Object


Set P2SRV = CreateObject(SimSciDbs.Database.81)
...

Where SimSciDbs.Database.81 is the progid of the specific version of PRO/II COM


Server to be created.

Basic Operations 13
Since multiple versions of PRO/II may coexist on the same machine, the application must
specify the exact version of the PRO/II COM Server to be used. The specific value of
"progid" depends on the version of PRO/II to be used and is outlined in table 3.

Table 3: Progid
Progid PRO/II version
SimSciDbs.Database.81 PRO/II 8.1.x
SimSciDbs.Database.80 PRO/II 8.0.x
SimSciDbs.Database.71 PRO/II 7.1.x
SimSciDbs.Database.70 PRO/II 7.0.x
SimSciDbs.Database.601 PRO/II 6.01

After the Server object has been created, it must be initialized using the Initialize method.
The simple form of this method is:

P2SRV.Initialize

The full form of this method is

p2ConfigFile$ = "c: \SimSci\proii81\User\proii.ini"


dbsSchemaFile$ = "c:\SimSci\proii81\System\Schema.sdf"
debugFile$ = "c:\SimSci\proii81\User\dbsdebug.txt"
P2SRV.Initialize p2ConfigFile$, dbsSchemaFile$, debugFile$

The simple form will use default values of all arguments. The full form allows the
application to specify individual values for the PRO/II configuration file ("proii.ini"), the
database schema file, and the debug output file. The full form is typically used for
advanced diagnostic and debugging only.

Once the PRO/II COM Server has been created and initialized, a simulation database can
be opened.

4.3 Open a PRO/II Database


To open an existing PRO/II database, use the Visual Basic code:

Dim P2DB As Object


p2Database$ = "c:\SimSci\proii81\user\Applib\R3R.prz"
Set P2DB = P2SRV.OpenDatabase(p2Database$)

This statement will open the PRO/II database file "R3R.prz". Note that file names must be
specified with full path.

Basic Operations 14
Only one database can be open at any given time. If the application needs to
access a second database, it must first close the one opened earlier.

Once the database has been opened, the application can then load data objects into
memory.

4.4 Load Data Objects into Memory


To load a data object into memory, use the ActivateObject method. The following Visual
Basic code loads the data object "1" of the "Stream" class into memory:

Dim P2OBJ As Object


Set P2OBJ = P2DB.ActivateObject("Stream", "1")

The first argument is the name of the data object class. The second argument is the name
of the object. The PRO/II COM Server Reference Guide lists all the object classes
available.

Once the object is in memory, its information can be accessed and modified using the
GetAttribute and PutAttribute methods.

4.5 Read and Write Attributes


Data in an object can be scalar or an array. To read the value of a scalar attribute, use the
GetAttribute method. Normally the GetAttribute method requires an index. For a scalar
data value, however, enter a dummy index (which will be ignored) or do not supply the
index at all:

dTemp = P2OBJ.GetAttribute("Temperature")

To get the value of a single element of an array attribute:

dFrac = P2OBJ.GetAttribute("TotalComposition", 0)

To get an entire array attribute in one call, supply an index of -1:

dFracArray = P2OBJ.GetAttribute("TotalComposition", -1)


for i% = LBound(dFracArray) to UBound(dFracArray)
dFracValue = dFracArray(i%)
next

To modify data, use the PutAttribute method. This method also uses an index to specify
the element of a vector attribute. To change the value of a scalar attribute, supply a
dummy index (which will be ignored) or do not supply the index at all:

P2OBJ.PutAttribute(NewValue, "ScalarAttribute")

Basic Operations 15
To change the value of a single element of an array attributes:

P2OBJ.PutAttribute(NewValue, "ArrayAttribute", index)

(In these two examples, "ScalarAttribute" and "ArrayAttribute" are used as examples, and
do not represent actual attributes of the "Stream" object.) The available attribute names
for each object class and their data types (Real, Integer, String, Scalar, Array) are listed in
the PRO/II COM Server Reference Guide.

Please see Modifying Information in the Database section at the end of the chapter for
complexities in writing data to the database to be used in future simulations.

4.6 Perform Units-of-Measure Conversion


Floating-point data, such as temperatures, pressures, and flowrates, is stored in PRO/II
"internal units-of-measure". This data can be converted to the input units or output units,
as defined by the user using the ConvertValue method. To get the printable string of the
unit-of-measure, use the method GetUOMString.

For example, the following code reads the stream temperature and displays it in a
message box:

Set P2OBJ = P2DB.ActivateObject("Stream","1")


dTemp = P2OBJ.GetAttribute("Temperature")
dTemp2 = P2DB.ConvertValue(dTemp, "TEMP", "internal", "output")
uomT$ = P2DB.GetUOMString("TEMP", "output")
i = MsgBox("Temperature is " & Format$(dTemp2) & _
" " & uomT$, vbOkOnly, "Output")
Set P2OBJ = Nothing

The string TEMP refers to the Temperature unit of measure class. The complete list of
recognizable Unit of Measure classes is given in Appendix A of the PRO/II COM Server
Reference Guide.

4.7 Commit and Free Objects


To save a modified object back to the database, use the "commit" method:

P2OBJ.Commit

When the application has finished interacting with the data object, it should release the
object from memory by assigning "Nothing" to the object variable:

Set P2OBJ = Nothing

If the object is released without first being committed to the database, then all the
changes will be lost.

Basic Operations 16
4.8 Save and Close the Database
To save and close a database, assign the "Nothing" value to the object variable:

Set P2DB = Nothing

where P2DB is the object variable returned by the original OpenDatabase method.

4.9 Shut down the PRO/II COM Server


At the end of the application, shut down the PRO/II COM server by assigning the value of
"Nothing" to the object variable:

Set P2SRV = Nothing

At this point, all objects and database files will be released from memory and the database
will be closed.

4.10 Modifying the Simulation Database


The PRO/II COM Server allows an application to modify data in a simulation database.
However, the underlying data structure of the simulation objects can be complex as
outlined below:

Along with the actual input values, many of the PRO/II objects contain one or
more flags that must be properly initialized for a valid simulation file to be created

The COM server does not automatically handle inter-object side effects of
modified data. For instance, if you delete a stream, you must remove all
references to that stream from other objects

The COM Server does perform some automatic resizing of objects based on the
values of other attributes. But reducing the size of an array attribute always
discards data from the end of the array. If you want to remove entries from the
middle of an array, then you must perform the required packing operations

Normally, this complexity is hidden by the PROVISION interface and the keyword input
processing.

A complete PRO/II simulation comprises many interrelated objects in the database. It is


beyond the scope of this document to describe all the steps required to generate a
consistent database ready for a flowsheet calculation. For the best results, it is
recommended that the PRO/II PROVISION GUI or keyword input file be used to define a
simulation database; then the COM application be used to perform simple modifications.
For example, a common activity is to perform a "case study" by making multiple simulation
runs after varying some flowsheet attribute.

Basic Operations 17
5 Writing Applications in
Different Languages
This section shows how all the steps of a COM application described previously work
together to form a complete application. A sample application will be presented and its
implementation demonstrated in several programming languages.

5.1 Description of Example


The example application uses the "R3R" example from the PRO/II Application Library. It
opens R3R.prz and reads the stream temperature, pressure, and composition from stream
"1". This example application does not modify any data or rerun the flowsheet.

5.2 Visual Basic 6.0 Implementation


Visual Basic is the macro language of Microsoft Office, including Microsoft Excel. It is also
available as part of Microsoft Visual Studio to develop standalone Windows applications.
In the Visual Basic language, COM objects such as the PRO/II COM Server can be
accessed and manipulated using the "Object" data type.

' Read and display simple stream data in Visual Basic


Dim P2SRV As Object
Set P2SRV = CreateObject("SimSciDbs.Database.81")
P2SRV.Initialize

Dim P2DB As Object


p2Database$ = "c:\SimSci\proii81\user\Applib\R3R.prz"
Set P2DB = P2SRV.OpenDatabase(p2Database$)

' Get component names


Dim P2OBJ As Object
Set P2OBJ = P2DB.ActivateObject("CompCalc", "CompCalc")
compNames = P2OBJ.GetAttribute("ComponentId", -1)
Set P2OBJ = Nothing

' Load stream into memory


Set P2OBJ = P2DB.ActivateObject("Stream", "1")

' Get stream attributes


dTemp = P2OBJ.GetAttribute("Temperature")
dPres = P2OBJ.GetAttribute("Pressure")
dRate = P2OBJ.GetAttribute("TotalMolarRate")
dFracArray = P2OBJ.GetAttribute("TotalComposition", -1)
MsgBox "Temperature = " & dTemp & " K", vbOKOnly, "Attributes"
MsgBox "Pressure = " & dPres & " kPa", vbOKOnly, "Attributes"
MsgBox "Molar Rate = " & dRate & " kg-mol/sec", _
vbOKOnly, "Attributes"
For i% = LBound(dFrac) To UBound(dFrac)

Writing Applications in Different Languages 18


MsgBox"Fraction("&compNames(i%)&")="& _
dFracArray(i%),vbOKOnly, "Attributes"
Next

Set P2OBJ = Nothing


Set P2DB = Nothing
Set P2SRV = Nothing

5.3 C++ Implementation


This implementation in C++ uses the COM compiler support that is built
into the Microsoft C++ compiler. Microsoft adds a new preprocessor
directive #import that can directly read the type library information and
generate the required header files and smart pointer object classes. This
feature makes COM programming in C++ similar to Visual Basic.

// Read and display simple stream data using C++


// with Microsoft C++ COM compiler extensions.
#include "stdafx.h"
#include <string>
#include <iostream>
#include "atlbase.h"
// Note: you must specify the full path to p2oledbs.exe
// in the import statement or
// set the "include" path for this project by selecting the
// menu option "Project / Settings / C++ / Category:Preprocessor /
// Additional include directories:"
#import "C:\\SIMSCI\\PROII93\\Bin\\p2oledbs.exe" no_namespace
using namespace std;
int main(int argc, char* argv[])
{
USES_CONVERSION;
CoInitialize(0);
string sP2ProgID("SimSciDbs.Database.92");
string sP2Path("c:\\simsci\\proii93");
string sP2Database = sP2Path + "\\user\\a1.prz";
// Start the PRO/II COM Server
// IServerPtr defined in the "*.tlh" file generated
// by the #import directive
// IServerPtr is really a _com_ptr_t smart pointer
// which is defined in the Microsft header files
// comdef.h and comip.h
IServerPtr pP2Server;
cout << "Start PRO/II COM Server using progid "<< sP2ProgID << endl;
pP2Server = 0;
CLSID clsid;
::CLSIDFromProgID(A2W(sP2ProgID.c_str()), &clsid);
CoInitialize(NULL);
HRESULT hr = CoCreateInstance(clsid, NULL, CLSCTX_LOCAL_SERVER,
__uuidof(IDispatch),(void**)&pP2Server);
// Initialize the server. The arguments are optional,
// therefore we use empty VARIANTs.
// The _variant_t data type is a wrapper class defined
// in the Microsoft header file comutil.h
_variant_t vConfigFile;

Writing Applications in Different Languages 19


_variant_t vSchemaFile;
_variant_t vDebugFile;
pP2Server->Initialize(vConfigFile, vSchemaFile, vDebugFile);
// Open up the PRO/II Database
cout << "Open database " << sP2Database << endl;
IDatabasePtr pP2Database;
IDispatchPtr pDispatch = pP2Server->OpenDatabase(sP2Database.c_str());
hr = pDispatch->QueryInterface(__uuidof(IDispatch),(void**)&pP2Database);
// Get component names
IDatabaseObjectPtr pP2Obj;
_variant_t vIndex = ((long) -1);
_variant_t vCompNames;
pDispatch = pP2Database->ActivateObject( (LPCSTR)"CompCalc",
(LPCSTR)"CompCalc" );
if(pDispatch != 0)
{
hr = pDispatch->QueryInterface(__uuidof(IDispatch),(void**)&pP2Obj);
}
// GetAttribute returns a SAFEARRAY of VARIANTS containing
// BSTR values
vCompNames = pP2Obj->GetAttribute("ComponentId", vIndex);
pP2Obj.Release();
vIndex.Clear();
// Load stream into memory.
vIndex.vt = VT_R8;
pDispatch = pP2Database->ActivateObject((LPCSTR)"Stream", (LPCSTR)"1");
if(pDispatch != 0)
{
hr = pDispatch->QueryInterface(__uuidof(IDispatch),(void**)&pP2Obj);
}
// Get attributes
_variant_t vTemp = pP2Obj->GetAttribute("Temperature", vIndex);
_variant_t vPres = pP2Obj->GetAttribute("Pressure", vIndex);
_variant_t vRate= pP2Obj->GetAttribute("TotalMolarRate",vIndex);
vIndex = ((long) -1);
// GetAttribute returns a SAFEARRAY of VARIANTS containing 'double'
// values
_variant_t vFrac=pP2Obj->GetAttribute("TotalComposition", vIndex);
cout <<"Temperature= " << (double) vTemp <<" K" << endl;
cout <<"Pressure = " << (double) vPres <<" kPa" << endl;
cout <<"Flowrate = " << (double) vRate <<" kg-mol/sec"<< endl;
VARIANT vName;
VARIANT vFracElement;
VariantInit(&vName);
VariantInit(&vFrac);
long lStart, lEnd, lIndex;
hr = SafeArrayGetLBound(vFrac.parray, 1, &lStart);
hr = SafeArrayGetUBound(vFrac.parray, 1, &lEnd);
for (lIndex=lStart; lIndex<=lEnd; lIndex++)
{
SafeArrayGetElement(vCompNames.parray, &lIndex, &vName);

cout<<"Fraction("<<_com_util::ConvertBSTRToString(vName.bstrVal)<<")= ";
SafeArrayGetElement(vFrac.parray, &lIndex, &vFracElement);
cout << vFracElement.dblVal << endl;
}

Writing Applications in Different Languages 20


// Release the stream object pointer.
cout << "Free stream object" << endl;
pP2Obj.Release();
// Release the database pointer, which closes the database.
cout << "Close database" << endl;
pP2Database.Release();
// Release the server pointer, which shuts down the
// P20LEDBS server
cout << "Shut down server" << endl;
pP2Server.Release();
CoUninitialize();
return 0;
}

5.4 VB Script Implementation


VBScript is a simplified version of Visual Basic that is often used for simple scripting in
Internet Explorer.

' Read and display simple stream data using VBScript


' To run, use the 'cscript.exe' program at the Command Prompt

WScript.echo "Start PRO/II COM server"


set P2SRV = CreateObject("SimSciDbs.Database.81")
P2SRV.Initialize

p2Database = "c:\SimSci\proii81\user\Applib\R3R.prz"
WScript.echo "Open database " & p2Database
set P2DB = P2SRV.OpenDatabase(p2Database)

WScript.echo "Get component names"


set P2OBJ = P2DB.ActivateObject("CompCalc", "CompCalc")
compNames = P2OBJ.GetAttribute("ComponentId", -1)
set P2OBJ = nothing

WScript.echo "Activate Stream '1'"


set P2OBJ = P2DB.ActivateObject("Stream", "1")
dTemp = P2OBJ.GetAttribute("Temperature")
dPres = P2OBJ.GetAttribute("Pressure")
dRate = P2OBJ.GetAttribute("TotalMolarRate")
dFrac = P2OBJ.GetAttribute("TotalComposition", -1)

WScript.echo " Temperature = " & dTemp & " K"


WScript.echo " Pressure = " & dPres & " kPa"
WScript.echo " Molar Rate = " & dRate & " kg-mol/sec"

for i = LBound(dFrac) to UBound(dFrac)


WScript.echo " Fraction(" & compNames(i) & ") = " & dFrac(i)
next

WScript.echo " Free object from memory"


set P2OBJ = nothing

WScript.echo "Close database"

Writing Applications in Different Languages 21


set P2DB = nothing

WScript.echo "Shut down PRO/II COM server"


set P2SRV = nothing

To run a VBScript program, open a Command Prompt window and use the
"cscript.exe" program:
cscript myscript.vbs

Writing Applications in Different Languages 22


6 Using the Operator Interface
6.1 Introduction
The Configurable Excel interface to PRO/II will enable the users to solve the flowsheet
using a third party application such as Microsoft Excel in the absence of considerable
knowledge on the simulator. Underlying macros uses cell comments for customization
while developing the excel spreadsheet. This feature has been illustrated using
OperatorInterface.xls spreadsheet for the following examples located in Applib folder.

G2_Deethanizer
G5_Expander_plant

The example excel spreadsheet that have been developed will enable the users

To work with excel spreadsheet in VBA and various built-in functions.


In customizing the spreadsheet based on the requirement.

The steps explained below will help the users in customizing the spreadsheet.

1. Initial setting of an excel application


2. Viewing the inbuilt example
3. Creating a new operator interface
4. Editing comments
5. Running the simulation

6.2 Initial setting of Excel application


Open an excel application and Click File/Open.
Locate OperatorInterface.xls file (\Proii81\User\Applib)
Click Open. A dialog box may pop-up requesting the users to Enable or Disable
Macros depending upon the internal setting of your excel application. Click
Disable Macros.

Using the Operator Interface 23


6.3 Viewing the inbuilt Example
By default, users can view G2_Deethanizer spreadsheet with comments indicator
enabled.

Figure 3. Example: Operator Interface

Note: Users need to ensure that Comments Indicator Only option is checked under
View Tab of Options dialog box. (Tools/Options). Based on comments, the
information is read from the database and written into the database.

6.4 Creating a new operator interface


From the menu bar, select Insert\Worksheet to add a new worksheet.
Identify the flowsheet for which new operator interface needs to be created
through excel. Rename the newly created sheet to the name of the identified .prz
file. For example, if the identified flowsheet is Crude Column.prz, then the excel
sheet should be renamed to Crude Column'.

Note: The simulation database should be in the same directory as the Excel
spreadsheet in order for it to open automatically when the sheet is selected. If this is
not the case, Excel will ask for the location of a simulation with that name. Once an
alternate file location is chosen, it becomes the default file path.

Using the Operator Interface 24


On the sheet, design the layout of the interface similar to the sheet as shown
above (Figure 3).
Note: There is no size limitation, but all should fit on one sheet. It is recommended
for the user to understand the simulation input data and output results thoroughly
before attempting to build the Excel Interface.

Add comments to the cells by clicking Insert/Comments from the menu bar.
Edit the comment window before entering the syntax as shown below.

6.5 Editing Comments


The comment should be in a certain format in order for the information to be retrieved or
displayed correctly in operator interface excel sheet.

Note: The Unix pipe symbol or vertical bar symbol ( | ) is used as the delimiter in the
comment statement.

The format (or syntax) is as follows:

|Read|Write|Class|Name|Attribute|Index|UOM|Location

Where:

Syntax Description

Read Information should be read from the simulation database on file open or
read the simulation results after the simulation has converged.

Write Write cell contents (input data) to the simulation database. Write is not
relevant for simulation results, but the embedded vertical bar should be
present to maintain proper sequential order of information.

Class Class of information object in simulation database.

In some cases like stream object, there is an input class StreamIn to write
and read input data and there is an output class Stream to read
simulation results back from the PRO/II database.

Refer PRO/II COM Server Reference Guide.

Using the Operator Interface 25


Name Name of information object in simulation database.

Attribute Information to be retrieved from/written to object in simulation database.


Refer PRO/II COM Server Reference Guide

Index Optional. Number of the element in Attribute vector if data is in the form of
an array. Most attributes have only one element (value), but some
attributes like Stream Composition have an index indicating the component
number for which the composition has to be retrieved. Index is not
relevant where the attribute is a single element, but the embedded vertical
bar should be present to maintain proper sequential order of information.

UOM Optional. Units of Measure (UOM) class to be used in converting the value
retrieved/written. See Appendix A of PRO/II COM Server Reference Guide
for Units of Measure Class codes. For example, the UOM for temperature
is TEMP.

Location Optional. If present, the printable version of the UOM will be displayed in a
cell relative to the one the comment belongs to. For example, if the location
value is C1, the UOM (E.g. C for Temperature in English Units) will be
placed one cell to the right of the cell with the comment and if the location
value is C-1, then the UOM will be placed one cell to the left of the cell with
the comment.

Examples:

|Read|Write|StreamIn|100|Composition|0

The above syntax indicates will read and write the first (0) component from the
composition of object StreamIn named 100.

|Read||Expander|X1|WorkActualCalc||WORK|C2

Reads the actual work parameter from the X1 expander. Convert the retrieved value using
UOM class WORK and display the printed version of the UOM (e.g. HP) two cells towards
the right of the current cell with the comment.

|Read|Write|Spec|COL1SPEC1|SpecValue

Both read and write the spec value for spec COL1SPEC1.

It is possible to nest this syntax. For example, this is useful when retrieving the name of a
specification from a column. Subsequently, use the name and retrieve or write a value.

Using the Operator Interface 26


|Read|Write|Spec|(|Read||ColumnIn|T1|IntSpecData)|SpecValue

From column T1, read the name of the spec object in the Spec Class corresponding to the
column T1 specification. Subsequently, use this name to retrieve and write the value from
this object.

|Read|Write|Define|(|Read||Compressor|C1|DefineData)|RefValue

From compressor C1, read the name of the define object. Subsequently, use this name to
retrieve and write the reference value from this object.

Using the Operator Interface 27


6.6 Running the Simulation
Right-click on the toolbar and select the Control Toolbox. Select a Command
button and add it to the sheet as shown in figure 3.
Click on the Properties icon on the Control Toolbox to view the dialog box as
shown below. Change the name of the Button to cmdRunSimulation and the
Caption to Run Simulation.

Figure 4. Properties

Using the Operator Interface 28


Double-click on the Run Simulation button and the Microsoft Visual Basic Editor
will open up. Delete all the code that is currently in the Sheet2 . To copy all the
codes from Sheet1 into Sheet2 follow the steps below.
Double-click on Sheet1.
Click on Edit\Select All and Edit\Copy.
Double-click on Sheet2.
Click on Edit\Paste.
Test to make sure the subroutine cmdRunSimulation is called by double-
clicking on the Run Simulation button in the Excel Sheet.
Select the area of the worksheet that contains only input data.
Click on Insert\Name\Define and label this area according to the sheet with the
suffix _Input. (e.g. Flash_Input and click on OK)
Carry out the same steps for the area with results only (suffix _Results). E.g.
Flash_Results. This will clean and update these areas properly. If the name of
the sheet contains a space, it should be replaced with an underscore character
(_). For example, the input area for the sheet Crude Column should be named
Crude_Column_Input.
Finally, save the file. Your customized Operator Interface is now ready for use.

Common Errors in Comment Statements

If the value for an attribute is retrieved as Zero from the PRO/II database while it is
not the desired value, then the attribute name is incorrect. Check the spelling for the
attribute name carefully.
If database operations such as Read, Write are not working properly, then carefully
check for syntax and spelling mistakes.
The COM Server would automatically shut down when an error is encountered in the
information provided. In such cases the error should be rectified and the operator
interface application should be re-opened.

Using the Operator Interface 29


7 COM Server Examples
7.1 Introduction
This section contains several complete examples demonstrating various features of the
PRO/II COM Server. Each example is a complete Visual Basic application and can be
used as a template or example for more complex applications.

7.2 Accessing Calculated Stream Conditions


This example extends the example in Chapter 5, Writing Applications in Different
Languages by adding unit-of-measure processing. The method ConvertValue is used to
convert values from PRO/II internal units-of-measure to output units. GetUOMString is
used to generate the display text.

Dim P2SRV As Object


Set P2SRV = CreateObject("SimSciDbs.Database.81")
P2SRV.Initialize

Dim P2DB As Object


p2Database$ = "c:\SimSci\proii81\user\Applib\R3R.prz"
Set P2DB = P2SRV.OpenDatabase(p2Database$)
Set P2OBJ = P2DB.ActivateObject("Stream", "1")

dTemp = P2OBJ.GetAttribute("Temperature")
dPres = P2OBJ.GetAttribute("Pressure")
dRate = P2OBJ.GetAttribute("TotalMolarRate")

dTemp2 = P2DB.ConvertValue(dTemp, "TEMP", "internal", "output")


dPres2 = P2DB.ConvertValue(dPres, "PRES", "internal", "output")
dRate2 = P2DB.ConvertValue(dRate, "MRAT", "internal", "output")

uomT = P2DB.GetUOMString("TEMP", "output")


uomP = P2DB.GetUOMString("PRES", "output")
uomR = P2DB.GetUOMString("MRAT", "output")

MsgBox "Temperature = " & dTemp2 & " " & uomT, vbOKOnly, "Temperature"
MsgBox "Pressure = " & dPres2 & " " & uomP, vbOKOnly, "Pressure"
MsgBox "Flowrate = " & dRate2 & " " & uomR, vbOKOnly, "Flowrate"

Set P2OBJ = Nothing


Set P2DB = Nothing
Set P2SRV = Nothing

7.3 Calculating Stream Properties


A common task for an application using the PRO/II COM Server is to retrieve stream data
from a calculated run for transfer to a datasheet or another application. This section
describes where this stream data is stored.

COM Server Examples 30


The process conditions and properties for a particular stream are distributed among the
stream data classes listed in the following table.

Table 4: Process conditions and properties


Class Attributes
StreamIn User-input stream data.
Stream Calculated stream conditions: temperature, pressure, phase fractions,
molar flowrate, and component mole fractions.
SrBulkProp Bulk stream properties: total, liquid, and vapor phases.
SrDecProp Properties for the decanted stream (excluding water, applies for those
thermodynamic methods that decant water).
SrRefProp Refinery inspection properties.
StreamLLE Properties for L1 and L2 liquid phases.

COM Server Examples 31


The following table outlines the common stream properties desired and which object they
are located in.

Table 5: Common stream properties

Stream Object They Are Located In:


Property

Composition Compositions of the overall stream; the liquid and vapor phases are
stored in the Stream object class.

Common Common stream properties such as temperature, pressure, flowrate,


Properties critical properties, and enthalpy are stored for each phase in the
SrBulkProp and SrDecProp object classes.

Transport Transport properties (viscosity, thermal conductivity, and liquid surface


Properties tension) will only be calculated if the thermodynamic data was configured
with a transport property calculation method. Only then will these
properties will be calculated for each phase and stored in the SrBulkProp
and SrDecProp object classes.

Refinery Common refinery properties such as TVP and RVP are calculated for the
Properties various phases and stored in the SrBulkProp object class.

Refinery Will only be calculated if the appropriate methods have been selected in
Inspection the thermodynamic data section. Only then will these properties be
Properties calculated for the bulk phase and stored in the SrRefProp object class.

When PRO/II solves a flowsheet, it uses the information in the StreamIn class and
process flowsheet conditions to calculate and store the attributes of the "Stream" class.
The data for the other classes is not automatically calculated for reasons of efficiency.
That information must be calculated and stored by calling the CalculateStreamProps
method.

To determine if the stream properties have been calculated, check to see if the
"SrBulkProp" object exists. If not, then call CalculateStreamProps. The following
example code demonstrates the procedure:

Dim P2SRV As Object


Set P2SRV = CreateObject("SimSciDbs.Database.81")
P2SRV.Initialize

Dim P2DB As Object

COM Server Examples 32


p2Database$ = "c:\SimSci\proii81\user\applib\R3R.prz"
Set P2DB = P2SRV.OpenDatabase(p2Database$)

' Get a security license (for better performance)


retCode = P2SRV.GetSecuritySeat(2)

' Have the stream properties been calculated?


If Not P2DB.ObjectExists("SrBulkProp", "1") Then
' Properties have not been calculated.
' Calculate them now.
P2DB.CalculateStreamProps ("1")
End If

' Load the SrBulkProp object and read the properties


Dim P2OBJ As Object
Set P2OBJ = P2DB.ActivateObject("SrBulkProp", "1")
dBulkMW = P2OBJ.GetAttribute("BulkMwOfPhase")
Set P2OBJ = Nothing

' Release the security license


P2SRV.ReleaseSecuritySeat

Set P2DB = Nothing


Set P2SRV = Nothing

Some stream properties are not directly available as individual attributes in the
database, but they can be calculated from attributes that are available. For instance, to
calculate the total mass flowrate of a stream:
Set P2STREAM = P2DB.ActivateObject("Stream","1")
Set P2BULK = P2DB.ActivateObject("SrBulkProp","1")
MoleRate = P2STREAM.GetAttribute("TotalMolarRate")
InertRate = P2STREAM.GetAttribute("InertWeightRate")
MolecWt = P2BULK.GetAttribute("BulkMwOfPhase")
TotalWtRate = MoleRate * MolecWt + InertRate
Set P2STREAM = Nothing
Set P2BULK = Nothing

For a list of the specific attributes available in each stream class, consult the PRO/II Com
Server Reference Guide.

7.4 Accessing Calculated Column Data


Input data for a distillation column is stored in the ColumnIn object. Calculated data is
stored in the Column object. Tray-by-tray properties can be retrieved using one of the two
methods:

TrayProp object

A predefined list of common tray-by-tray properties is available in the TrayProp object.


This object is created by calling the CalculateUnitProps method for the desired column.

COM Server Examples 33


Dim P2SRV As Object
Set P2SRV = CreateObject("SimSciDbs.Database.81")
P2SRV.Initialize
Dim P2DB As Object
p2Database$ = "c:\SimSci\proii81\user\Applib\R3R.prz"
Set P2DB = P2SRV.OpenDatabase(p2Database$)

' Ensure that merged column results have been


' copied back to original column/sidestrippers.
P2DB.TowerBurst

' Have the tray-by-tray properties been calculated?


If Not P2DB.ObjectExists("TrayProp", "COL1") Then
' Properties have not been calculated.
' Calculate them now.
P2DB.CalculateUnitProps ("COL1")
End If

uomLD$ = P2DB.GetUOMString("LDEN", "output")


uomVD$ = P2DB.GetUOMString("VDEN", "output")

Dim P2OBJ As Object


Set P2OBJ = P2DB.ActivateObject("TrayProp", "COL1")
dLDens = P2OBJ.GetAttribute("WetLiqActDensity", -1)
dVDens = P2OBJ.GetAttribute("WetVapActDensity", -1)
For i = LBound(dLDens) To UBound(dLDens)
dLDens2 = P2DB.ConvertValue(dLDens(i), "LDEN", _
"internal", "output")
dVDens2 = P2DB.ConvertValue(dVDens(i), "VDEN", _
"internal", "output")
MsgBox "Tray " & i + 1 & ", LiqDens=" & dLDens2 & " (" & _
uomLD$ & "), VapDens=" & dVDens2 & " (" & uomVD$ & ")", _
vbOKOnly, "Tray Property"
Next

Set P2OBJ = Nothing


Set P2DB = Nothing
Set P2SRV = Nothing

Refer to the PRO/II Com Server Reference Guide or a list of supported properties.

CopyTrayToStream method

To calculate additional tray-by-tray properties not provided by the TrayProp object, an


application could copy the tray temperature, pressure, and composition to a temporary
stream, and then call the CalculateStreamProps on the resulting stream. By proceeding
tray-by-tray down the column an application can generate profiles for any stream property.

The following example illustrates the technique:

Dim P2SRV As Object


Set P2SRV = CreateObject("SimSciDbs.Database.81")
P2SRV.Initialize

COM Server Examples 34


Dim P2DB As Object
p2Database$ = "c:\SimSci\proii81\user\Applib\R3R.prz"
Set P2DB = P2SRV.OpenDatabase(p2Database$)

' Ensure that merged column results have been


' copied back to original column/sidestrippers.
P2DB.TowerBurst

Dim P2OBJ As Object


Set P2OBJ = P2DB.ActivateObject("Column", "COL1")
nTrays = P2OBJ.GetAttribute("NumberOfTrays")
Set P2OBJ = Nothing

' Create temporary stream


tmpStream$ = "TMPSTR"
Set P2OBJ = P2DB.CreateObject("Stream", tmpStream$)
Set P2OBJ = Nothing

P2SRV.GetSecuritySeat (2)
Dim P2OBJ1 As Object
Dim P2OBJ2 As Object
Dim retCode As Boolean
For i% = 1 To nTrays
retCode = P2DB.CopyTrayToStream( _"COL1", i%, 0, 0, 1, tmpStream$)
retCode = P2DB.CalculateStreamProps(tmpStream$)
Set P2OBJ1 = P2DB.ActivateObject("Stream", tmpStream$)
Set P2OBJ2 = P2DB.ActivateObject("SrBulkProp", tmpStream$)
dTemp = P2OBJ1.GetAttribute("Temperature")
dTotRate = P2OBJ1.GetAttribute("TotalMolarRate")
dLDens = P2OBJ2.GetAttribute("LiqDensityAct")
dVDens = P2OBJ2.GetAttribute("VapDensityAct")
Set P2OBJ1 = Nothing
Set P2OBJ2 = Nothing
Next

P2SRV.ReleaseSecuritySeat

' Delete temporary stream


P2DB.DeleteObject "Stream", tmpStream$

Set P2DB = Nothing


Set P2SRV = Nothing

7.5 Invoking an Excel macro from the PRO/II GUI


A COM application that is implemented as an Excel spreadsheet macro can be hooked
into the PRO/II PROVISION GUI and invoked from the menu. This requires two steps:

1. Modify the spreadsheet macro to implement communication with the PRO/II


PROVISION GUI

2. Modify the PRO/II initialization file (proii.ini) to add the new macro into the menu
selections

COM Server Examples 35


To communicate with the PRO/II GUI, the spreadsheet macro must invoke a small set of
Dynamic Data Exchange( DDE) commands. These commands are used to get information
from the active session of PRO/II, including which icon is selected on the flowsheet and
which simulation database is open. The specific steps are:

1. Use Visual Basics command DDEInitiate to open up a DDE channel. Use


the application PROVISION and the topic PFDInfo

2. Use Visual Basics DDERequest command to request the following data:


"INIFile" and "TempDbFile"

3. Start the PRO/II COM Server and initialize it using the information from INIFile

4. Open the simulation database file specified by the PRO/II PROVISION GUI and
requested in step 2 using "TempDbFile"

5. Activate an object

6. Read/write attributes including Unit-of-Measure conversion

7. Commit, if necessary, and free the object

8. Close the database

9. Shut down the Database Server

10. Notify the PRO/II PROVISION GUI that the spreadsheet macro has completed its
operations. To do this, use the DDERequest command to send the IAmDone
message. This message tells the PRO/II GUI that it can reopen the temporary
database

11. Use Visual Basics command DDETerminate to close the DDE channel

Steps 1, 2, 10, and 11 are the additional tasks that must be performed.

COM Server Examples 36


While a spreadsheet tool is running, the PRO/II PROVISION GUI acts as a DDE Server
with the application name PROVISION and the topic PFDInfo. Once a DDE channel
has been established, there are several data items that the spreadsheet macro can
request:

Table 6: Data items and its description


Data Item Description
OptionData Additional data included with the macro specification in the
initialization file (proii.ini)
INIFile Path and name of the PRO/II initialization file (proii.ini)
DbFile Path and name of the permanent database
TempDbFile Path and name of the temporary database actually being used by
the PRO/II PROVISION GUI. The PRO/II GUI always creates and
operates on a temporary simulation database while it is active. The
permanent database is not modified until the user selects File/Save
or File/Save As
FirstSelectedItem Object name and object type of the first selected item on the
flowsheet. Returned as a two-element array.
NextSelectedItem Object name and object type of the next selected item on the
flowsheet. Returned as a two-element array.

Before the spreadsheet macro is invoked from the PRO/II GUI, PRO/II closes the
temporary database to allow the spreadsheet macro read/write access to the data. When
the spreadsheet macro is complete, it must notify the PRO/II PROVISION GUI that its
operations are complete and that PRO/II can safely reopen the temporary database. This
is done by sending the DDE command IAmDone to the PRO/II PROVISION GUI.

This sample Excel Macro to demonstrates the process:

Sub ShowStream()
' Open up a DDE channel to PRO/II to get information
iChannel = Application.DDEInitiate("PVISION", "PFDInfo")
If IsError(iChannel) Then
Exit Sub
End If

' Data from a DDE Request comes back as an array and must
' be put into a Variant variable.
' Get the name of the initialization file.
DDEData = Application.DDERequest(iChannel, "INIFile")
sINIFile = ""
If Not IsError(DDEData) Then
sINIFile = DDEData(1)
End If

' Get the name of the temporary database file being

COM Server Examples 37


' used by PRO/II.
DDEData = Application.DDERequest(iChannel, "TempDbFile")
sDataFile = ""
If Not IsError(DDEData) Then
sDataFile = DDEData(1)
End If

' Get the name of the selected stream on the PFD.


DDEData = Application.DDERequest(iChannel, "FirstSelectedItem")
sItemName = ""
sItemType = ""
If Not IsError(DDEData) Then
sItemName = DDEData(1)
sItemType = DDEData(2)
End If

' Initialize the Database Server.


Dim P2SRV As Object
Set P2SRV = CreateObject("SimSciDbs.Database.81")
P2SRV.Initialize sINIFile

' Open the PRO/II Database.


' It is assumed that PRO/II has already closed the database.
Dim P2DB As Object
Set P2DB = P2SRV.OpenDatabase(sDataFile)

Set P2OBJ = P2DB.ActivateObject("Stream", sItemName)


dTemp = P2OBJ.GetAttribute("Temperature")
MsgBox "Temperature ="&dTemp, vbOKOnly, _
"Temperature of Stream"&sItemName
Set P2OBJ = Nothing

Set P2DB = Nothing


Set P2SRV = Nothing

' Close the DDE channel


Application.DDEExecute iChannel, "IAmDone"
Application.DDETerminate (iChannel)
End Sub

After the spreadsheet macro has been modified, it can be added as a menu option into the
PRO/II PROVISION interface. To do so, modify the PRO/II initialization file "proii.ini":

1. Start up an ASCII editor (Notepad, PFE, or WordPad) and open the initialization
file (proii.ini)

2. Locate the [Spreadsheet] section, update the Number= parameter, and add a
new snnn= line to the section:

[Spreadsheet]
Number=4
s000=...
s001=...
s002=...

COM Server Examples 38


s003=menu_bar_text,xls_filename,macro_name,extra_info

Where:

snnn is the spreadsheet number beginning with 's' and using a 3-digit number with leading
zeros. (Use s000= for the first menu item.)

menu_bar_text is the text that goes in the PROVISION menu bar under
Tools/Spreadsheet. Place an ampersand (&) in front of the character to be underlined.

xls_filename is the name of the file in which you macro is located (a *.xls or *.xla file).

macro_name is the name of the macro that is actually going to run.

extra_info is any extra information you want to be available. In the supplied examples,
this is used to identify the spreadsheet template file that will be used as the basis of the
reports.

3. Save the file and close the editor

At this point, PRO/II can be restarted and the new item will appear in the "Tools /
Spreadsheet" menu.

7.6 Performing a Flash Calculation


Flash Calculation on an Existing Stream

Use the FlashStream method to perform a flash calculation on an existing stream in a


flowsheet. The stream must have all input data defined and the thermodynamic method to
be used must be specified.

Dim P2SRV As Object


Set P2SRV = CreateObject("SimSciDbs.Database.81")
P2SRV.Initialize

Dim P2DB As Object


p2Database$ = "c:\SimSci\proii81\user\Applib\R3R.prz"
Set P2DB = P2SRV.OpenDatabase(p2Database$)

P2SRV.ClearMsgs
sResults$ = P2DB.FlashStream("1")
MsgBox sResults$, vbOKOnly, "Flash Results"

nMsg% = P2SRV.MsgCount
If nMsg% > 0 Then
For i% = 0 To (nMsg% - 1)
sMessage$ = P2SRV.MsgText(i%)
Next
End If

Set P2DB = Nothing

COM Server Examples 39


Set P2SRV = Nothing

Flash Calculation on a New Stream

A PRO/II COM Server application can also create a new database, define components
and thermodynamic data, define a new stream, and perform a flash calculation on that
new stream. The following example demonstrates this approach:

Sub Main()
Dim P2SRV As Object
Set P2SRV = CreateObject("SimSciDbs.Database.81")
P2SRV.Initialize

' Create the new database


Dim P2DB As Object
p2Database$ = "c:\SimSci\proii81\user\TestFlash"
Set P2DB = P2SRV.NewDatabase(p2Database$)

' Define the components and mole fractions to be added


CompNames = Array("NITRIC", "N2")
CompFracs = Array(0.998, 0.002)

' Create all the components in the new database


iPrint% = 0
For i% = LBound(CompNames) To UBound(CompNames)
iPrint% = iPrint% + 1
CreateComponent P2DB, CompNames(i%), iPrint%
Next
P2DB.BuildCompCalc

' Define the thermodynamic system in the new database


CreateThermo P2DB, "PR01", 102, 1

' Create the new stream


strmName$ = "S1"
Set P2OBJ = P2DB.CreateObject("Stream", strmName$)
P2OBJ.Commit True
Set P2OBJ = Nothing
Set P2OBJ = P2DB.CreateObject("StreamIn", strmName$)
P2OBJ.PutAttribute 1, "NoCheckBasisFlag"
P2OBJ.PutAttribute 1, "CompositionBasisFlag"
P2OBJ.PutAttribute "", "CompositionDimenUnit"

' Store the stream composition


nComp% = UBound(CompNames) - LBound(CompNames) + 1
P2OBJ.PutAttribute nComp%, "CompVectorDimension"
P2OBJ.PutAttribute nComp%, "ComponentInputCount"
iIndex% = 0

For i% = LBound(CompNames) To UBound(CompNames)


P2OBJ.PutAttribute CompNames(i%), "ComponentID", iIndex%
P2OBJ.PutAttribute CompFracs(i%), "Composition", iIndex%
iIndex% = iIndex% + 1
Next

COM Server Examples 40


' Store the stream process conditions
Data = P2DB.ConvertValue(100#, "TEMP", "input", "internal")
P2OBJ.PutAttribute Data, "Temperature"
Data = P2DB.ConvertValue(14.7, "PRES", "input", "internal")
P2OBJ.PutAttribute Data, "Pressure"
P2OBJ.PutAttribute 0, "StrmTempPressFlg"
P2OBJ.PutAttribute 0, "InputPhaseFlag"
P2OBJ.PutAttribute 0, "PhaseBasisFlag"
P2OBJ.PutAttribute 1, "LiqFracBasisFlag"
P2OBJ.PutAttribute 1, "LfracBasisFlag"
P2OBJ.PutAttribute 1, "StrmLiqFracFlg"
Data = P2DB.ConvertValue(100#, "MRAT", "input", "internal")
P2OBJ.PutAttribute Data, "TotalRate"
P2OBJ.PutAttribute 1, "RateBasisFlag"
P2OBJ.PutAttribute 1, "StreamTypeFlag"
P2OBJ.PutAttribute 0, "StrmCompRateFlg"
P2OBJ.Commit 1
Set P2OBJ = Nothing

' Perform the Flash Calculation on the stream


P2SRV.ClearMsgs
sResults$ = P2DB.FlashStream(strmName$)
MsgBox sResults$, vbOKOnly, "Flash Results"

' If there are errors then get the error messages


nMsg% = P2SRV.MsgCount
If nMsg% > 0 Then
For i% = 0 To (nMsg% - 1)
sMessage$ = P2SRV.MsgText(i%)
Next
End If

Set P2DB = Nothing


Set P2SRV = Nothing

' End of main routine


End Sub

' Subroutine to create a component in the database


Sub CreateComponent(P2DB As Object, cmpID As Variant, _
iPrint As Integer)
iMiss = -2111111111
Set P2OBJ = P2DB.CreateObject("CompIn", cmpID)
P2OBJ.PutAttribute 2, "InputLibDataFlag"
P2OBJ.PutAttribute 100, "ComponentTypeIn"
P2OBJ.PutAttribute 1, "ComponentSubType"
P2OBJ.PutAttribute cmpID, "ComponentLibIdIn"
P2OBJ.PutAttribute iMiss, "PhaseIn"
P2OBJ.PutAttribute iPrint, "PrintNumber"
P2OBJ.PutAttribute "PROCESS", "BankSearchOrderIn", 0
P2OBJ.PutAttribute "SIMSCI", "BankSearchOrderIn", 1
P2OBJ.Commit True
Set P2OBJ = Nothing
End Sub

' Subroutine to create a thermodynamic system in the database

COM Server Examples 41


Sub CreateThermo(P2DB As Object, thID As String, _
thCode As Integer, isDefault As Integer)
Set P2OBJ = P2DB.CreateObject("ThermoSet", thID)
P2OBJ.PutAttribute 1, "VLLEFlagInpt"
P2OBJ.PutAttribute thCode, "SystemFlagInpt"
P2OBJ.GetThermoDefaults
P2OBJ.Commit False
P2OBJ.PutAttribute 0, "KvalLLEDataFlg"
P2OBJ.PutAttribute 1, "LiqEnthDataFlg"
P2OBJ.PutAttribute 1, "VapEnthDataFlg"
P2OBJ.PutAttribute 0, "LiqDensDataFlg"
P2OBJ.PutAttribute 1, "VapDensDataFlg"
P2OBJ.PutAttribute 0, "VapPhiDataFlg"
P2OBJ.PutAttribute 1, "LiqEntrDataFlg"
P2OBJ.PutAttribute 1, "VapEntrDataFlg"
P2OBJ.Commit True
Set P2OBJ = Nothing

If isDefault = 1 Then
Set P2OBJ = P2DB.ActivateObject("ThermoGlob", " ")
P2OBJ.PutAttribute thID, "DfltMethInp"
P2OBJ.Commit True
Set P2OBJ = Nothing
End If
End Sub

7.7 Flash Drum Outlet Conditions


This example demonstrates the procedure for retrieving the outlet conditions of a flash
drum unit operation.

PRO/II uses "internal" streams for storing intermediate results. Internal streams are
objects with a name that begins with a "$" sign. These streams are normally not included
in the list of stream objects retrieved with the GetObjectNames method.

Internal streams are used to store the outlet conditions of many unit operations before the
outlet products are split into the individual vapor, liquid, and decant water products. To
access the internal stream representing the overall outlet conditions, use the
"MergedProduct" attribute. Using this name, an application can load the internal stream
into memory and access the outlet conditions like any other stream object.

This example reads the outlet conditions from the "MergedProduct" of the Flash "FL1" unit
operation of the R3R application.

Dim P2SRV As Object


Set P2SRV = CreateObject("SimSciDbs.Database.81")
P2SRV.Initialize

Dim P2DB As Object


p2Database$ = "c:\SimSci\proii81\user\Applib\R3R.prz"
Set P2DB = P2SRV.OpenDatabase(p2Database$)

Set P2OBJ = P2DB.ActivateObject("Flash", "FL1")

COM Server Examples 42


MergedProduct$ = P2OBJ.GetAttribute("MergedProduct")
Set P2OBJ = Nothing

Set P2OBJ = P2DB.ActivateObject("Stream", MergedProduct$)

dTemp = P2OBJ.GetAttribute("Temperature")
dPres = P2OBJ.GetAttribute("Pressure")
dRate = P2OBJ.GetAttribute("TotalMolarRate")

dTemp2 = P2DB.ConvertValue(dTemp, "TEMP", "internal", "output")


dPres2 = P2DB.ConvertValue(dPres, "PRES", "internal", "output")
dRate2 = P2DB.ConvertValue(dRate, "MRAT", "internal", "output")

uomT = P2DB.GetUOMString("TEMP", "output")


uomP = P2DB.GetUOMString("PRES", "output")
uomR = P2DB.GetUOMString("MRAT", "output")

MsgBox "Temperature = " & dTemp2 & " " & uomT, vbOKOnly, "Temperature"
MsgBox "Pressure = " & dPres2 & " " & uomP, vbOKOnly, "Pressure"
MsgBox "Flowrate = " & dRate2 & " " & uomR, vbOKOnly, "Flowrate"

Set P2OBJ = Nothing


Set P2DB = Nothing
Set P2SRV = Nothing

COM Server Examples 43


Invensys Systems, Inc.
26561 Rancho Parkway South
Lake Forest, CA 92630
United States of America
http://iom.invensys.com

Global Customer Support


Inside U.S.: 1-866-746-6477
Outside U.S.: 1-508-549-2424 or contact your
local Invensys Representative.
Email: Invensys.iom.support@Schneider-electric.com
Website: http://support.ips.invensys.com

You might also like