Вы находитесь на странице: 1из 381

InduSoft Web Studio Advanced Training Course

Part B

www.InduSoft.com 877.463.8763

IWS Training Guide

Copyright

Copyright 2007 by InduSoft. All rights reserved worldwide. No part of this publication may be reproduced or transmitted in any form or by any means without written authorization from InduSoft. The information contained within this document is subject to change without notice. InduSoft does not assume responsibility for any errors or inaccuracies that may occur in this publication. InduSoft is a registered trademark of InduSoft. CEView is a trademark of InduSoft. Windows, Windows XP, Windows 2000, and Windows NT are registered trademarks of Microsoft Corp. in the United States and other countries. Other brand or product names are trademarks or registered trademarks of their respective owners. PN: IND-TG/TG-001

ii

InduSoft Web Studio

Contents
CHAPTER 19. IWS FILE/DATABASE CONFIGURATION............................................................................191 USING THE IWS PROPRIETARY FILE FORMAT ......................................................................................... 191 IWS PROPRIETARY FILE AND DATABASE FORMAT FOR ALARM HISTORY .................................................. 193 IWS PROPRIETARY FILE AND DATABASE FORMAT FOR EVENT HISTORY ................................................. 195 IWS PROPRIETARY FILE AND DATABASE FORMAT FOR TREND HISTORY .................................................. 197 USING THE BUILT-IN ADO.NET INTERFACE ............................................................................................ 198 CONFIGURING THE DEFAULT DATABASE ............................................................................................... 1912 CONFIGURING A TASK OR OBJECT DATABASE ...................................................................................... 1915 PRIMARY AND SECONDARY DATABASES ............................................................................................... 1916 LINKING TO A REMOTE DB PROVIDER WITH STUDIO DATABASE GATEWAY .............................................. 1917 STUDIO DATABASE GATEWAY .............................................................................................................. 1918 CHAPTER 20. USING ODBC DATABASE SOURCE NAMES (DSN) ..........................................................201 USING A DATABASE WITH A DSN ........................................................................................................... 204 CHAPTER 21. ALARMS.................................................................................................................................211 ALARM W ORKSHEETS ........................................................................................................................... 212 ALARM/EVENT CONTROL ....................................................................................................................... 215 EXERCISE: CREATING AN ALARM GROUP AND ALARM SCREEN ................................................................ 217 EXAMPLE: DISABLING ALARMS ............................................................................................................. 2114 EXERCISE: ADDING AN ALARM/EVENT CONTROL DISPLAY ..................................................................... 2115 CHAPTER 22. DATA LOGGING & TREND DISPLAY ..................................................................................221 CONFIGURING THE TREND TASK ............................................................................................................ 221 CONVERTING TREND HISTORY FILES ..................................................................................................... 224 TREND CONTROL OBJECT ..................................................................................................................... 225 Trend Control Development Interface ............................................................................................ 225 Trend Control Runtime Interface.................................................................................................... 226 EXERCISE: CREATING AN ONLINE TREND ............................................................................................... 227 Decreasing the Save Frequency Using the Scheduler ................................................................ 2212 USING AN EXTERNAL TEXT FILE ........................................................................................................... 2213 USING AN EXTERNAL DATABASE .......................................................................................................... 2217 CHAPTER 23. EVENT MANAGER ................................................................................................................231 EXERCISE: CONFIGURING EVENT RETRIEVAL ......................................................................................... 232 CHAPTER 24. GRID OBJECT .......................................................................................................................241 EXAMPLE: USING THE GRID OBJECT WITH EXCEL ................................................................................. 2411 CHAPTER 25. VBSCRIPT ..............................................................................................................................251 VBSCRIPT LIMITATIONS IN IWS ............................................................................................................. 252 DIFFERENCES BETWEEN VBSCRIPT AND VBA ........................................................................................ 253 VBSCRIPT LANGUAGE OVERVIEW .......................................................................................................... 254 VBSCRIPT FUNCTIONALITY .................................................................................................................... 254 VBSCRIPT ELEMENTS ........................................................................................................................... 254 VARIABLE DATA TYPES AND SUBTYPES .................................................................................................. 255 DATA SUBTYPE IDENTIFICATION ............................................................................................................. 255 DATA SUBTYPE CONVERSION ................................................................................................................ 256 VARIABLE NAMING RULES & CONVENTIONS............................................................................................ 256 VARIABLE SCOPE .................................................................................................................................. 256 VBSCRIPT CONSTANTS ......................................................................................................................... 257

InduSoft Web Studio

iii

IWS Training Guide

Contents

DECLARING VBSCRIPT VARIABLES AND CONSTANTS .............................................................................. 257 VBSCRIPT KEYWORDS .......................................................................................................................... 257 OPERATORS ......................................................................................................................................... 258 OPERATOR PRECEDENCE...................................................................................................................... 259 FUNCTIONS......................................................................................................................................... 2510 STATEMENTS ...................................................................................................................................... 2514 VBSCRIPT OBJECT COMMANDS........................................................................................................... 2517 VBSCRIPT USER-DEFINED CLASS OBJECTS......................................................................................... 2518 EXAMPLE: USING VBSCRIPT USER-DEFINED CLASS OBJECTS .............................................................. 2522 VBSCRIPT OBJECTS AND COLLECTIONS............................................................................................... 2523 COM OBJECTS AND COLLECTIONS ...................................................................................................... 2533 VBSCRIPT CONFIGURATION AND OPERATION IN IWS............................................................................ 2537 GLOBAL PROCEDURES ........................................................................................................................ 2538 GRAPHICS SCRIPT .............................................................................................................................. 2539 SCREEN SCRIPTS ............................................................................................................................... 2540 COMMAND DYNAMIC ........................................................................................................................... 2542 ACTIVEX EVENTS................................................................................................................................ 2543 BACKGROUND TASK STARTUP SCRIPT ................................................................................................. 2544 BACKGROUND TASK SCRIPT GROUPS .................................................................................................. 2545 SCOPE OF VBSCRIPT PROCEDURES AND VARIABLES............................................................................ 2547 ACCESSING IWS TAGS AND IWS BUILT-IN FUNCTIONS.......................................................................... 2549 ACCESSING ACTIVEX OBJECTS FROM VBSCRIPT ................................................................................. 2552 INTELLISENSE ..................................................................................................................................... 2554 VBSCRIPT WITH W EB THIN CLIENTS .................................................................................................... 2556 EXERCISE: USING VBSCRIPT WITH SCREENS ....................................................................................... 2557 EXERCISE: USING VBSCRIPT & SCRIPT W ORKSHEETS ......................................................................... 2558 EXERCISE: USING VBSCRIPT............................................................................................................... 2561 CHAPTER 26. DATABASES..........................................................................................................................261 CHAPTER 27. CONFIGURING THE DATABASE .........................................................................................271 CHAPTER 28. SQL THE LANGUAGE OF DATABASES ..........................................................................281 SQL NOMENCLATURE ........................................................................................................................... 282 SQL LANGUAGE DERIVATIVES ............................................................................................................... 283 SQL OPERATORS ................................................................................................................................. 284 SQL DATATYPES................................................................................................................................ 2812 CONSTRAINTS AND KEYS..................................................................................................................... 2814 DDL SCHEMA STATEMENTS ................................................................................................................ 2815 DML QUERY STATEMENTS .................................................................................................................. 2822 JET SQL ........................................................................................................................................... 2841 TRANSACT-SQL ................................................................................................................................. 2842 EXAMPLES USING A SQL QUERY WITH IWS TAGS ................................................................................ 2843 CHAPTER 29. ACCESSING DATABASES WITH VBSCRIPT .....................................................................291 ADO OVERVIEW ................................................................................................................................... 292 RELATIONAL DATABASES SUPPORTED BY ADO ...................................................................................... 294 DATABASE TERMINOLOGY ..................................................................................................................... 295 DATA TYPE MAPPING ............................................................................................................................ 296 THE ADO CONNECTION OBJECT ........................................................................................................... 299 THE ADO COMMAND OBJECT.............................................................................................................. 2916 THE ADO RECORDSET OBJECT .......................................................................................................... 2918 Using the Recordset Object ......................................................................................................... 2923 THE STREAM OBJECT ......................................................................................................................... 2929 USING THE ADOX OBJECT MODEL ...................................................................................................... 2930 ADOCE AND ADOXCE ...................................................................................................................... 2934

iv

InduSoft Web Studio

Contents

IWS Training Guide

ADOVBS CONSTANTS........................................................................................................................ 2937 EXERCISE: USING ADO WITH VBSCRIPT.............................................................................................. 2948 EXERCISE: USING ADOX TO CREATE AN BLANK ACCESS DATABASE...................................................... 2949 CHAPTER 30. READING & WRITING XML USING VBSCRIPT...................................................................301 PERSISTING DATA IN XML FORMAT USING ADO..................................................................................... 301 USING THE XMLDOM ........................................................................................................................... 303 CHAPTER 31. ACTIVEX CONTROLS AND .NET ASSEMBLIES ................................................................311 EXERCISE: INSERTING AN ACTIVEX CONTROL ........................................................................................ 316 SYSTEM.COLLECTIONS.......................................................................................................................... 318 CHAPTER 32. WEB THIN CLIENTS..............................................................................................................321 BUILDING A SIMPLE W EB THIN CLIENT APPLICATION STEP BY STEP ........................................................ 323 W EB THIN CLIENTS THE UNDERLYING TECHNOLOGY ......................................................................... 3211 ISSYMBOL ACTIVEX CONTROL ............................................................................................................ 3213 W EB SERVER CONFIGURATION ............................................................................................................ 3216 W EB TUNNELING GATEWAY CONFIGURATION ....................................................................................... 3217 W EB BROWSER CONFIGURATION ......................................................................................................... 3218 DATA SERVER AND W EB CLIENT CONFIGURATION ................................................................................ 3222 EXAMPLE W EB SERVER/THIN CLIENT ARCHITECTURES ......................................................................... 3226 SECURITY FOR W EB BASED APPLICATIONS .......................................................................................... 3231 PORT USAGE ...................................................................................................................................... 3236 EXERCISE: VIEWING YOUR APPLICATION ON THE W EB .......................................................................... 3237 CHAPTER 33. WEB THICK CLIENTS ...........................................................................................................331 Configuring the Server ................................................................................................................... 331 Configuring the Client..................................................................................................................... 331 CHAPTER 34. SYSTEM LEVEL REDUNDANCY ..........................................................................................341 CHAPTER 35. FTP .........................................................................................................................................351 CHAPTER 36. SNMP......................................................................................................................................361 CHAPTER 37. USING THE REMOTE AGENT ..............................................................................................371 EXERCISE: CONFIGURING THE REMOTE AGENT ...................................................................................... 371 DOWNLOADING A CEVIEW APPLICATION ................................................................................................ 373 CHAPTER 38. RUNTIME CONFIGURATION ................................................................................................381 APPENDIX A. VBSCRIPT EXAMPLES .......................................................................................................... A1 USING THE WSHSHELL OBJECT (W INDOWS XP)...................................................................................... A2 USING THE W INDOWS SHELL (W INDOWS XP)........................................................................................... A3 USING THE W INMGMTS AND WMISERVICES OBJECT (W INDOWS XP)........................................................ A4 USING CDO (W INDOWS XP) ................................................................................................................... A1 USING OFFICE AUTOMATION (W INDOWS XP) ........................................................................................... A2 APPENDIX B. APPLICATION NOTES ........................................................................................................... B1

InduSoft Web Studio

Chapter 19. IWS File/Database Configuration


In this Chapter, we will look at how to configure database connections for Trends, Alarms, Events and the Grid Object. In subsequent chapters, we will cover the Trending, Alarm, Event and Grid Objects and Worksheets in further detail. IWS provides automatic database storage and retrieval for Trend data, Alarms, Events, and the Grid Object. This data can be stored in either the IWS proprietary database format (to local files), or to a relational database (local or remotely located) using the built-in ADO.NET interface. The Grid Object can only be used with the built-in ADO.NET interface (or with Class Objects or Text files).

Using the IWS Proprietary File Format


Trend Data, Alarm Data and Event Data can all be stored (and retrieved) in files on the local computer using the built-in IWS proprietary format. The advantage of the IWS proprietary database format is that the data is very rd compact and a 3 party database is not required. The following chart explains where the database configuration for each Task is located: Task Alarms Interface From the Main Menu Bar, select Project Settings, and then select the Options Tab. In the Alarm History and Events section, select the Proprietary option in the History Format combo box. From the Main Menu Bar, select Project Settings, and then select the Options Tab. In the Alarm History and Events section, select the Proprietary option in the History Format combo box. In a Trend Worksheet, select the Proprietary option in the History Format combo box.

Events

Trend

Notes: Both the Alarms and Events must be saved in the same format (i.e. IWS Proprietary or to a Relational Database). If stored to a Relational Database, the Relational Databases can be different Each Trend Worksheet can be individually configured to store data in the IWS Proprietary format or to a Relational Database.

InduSoft Web Studio

191

IWS Training Guide

Contents

Alarm Data files are stored in the \Alarm subfolder in the Application directory by default. The file format is Text (UNICODE), and IWS uses the vertical bar (pipe) character (|) to separate the fields. Alarm files have an .ALH file extension. The Alarm file name syntax is alYYMMDD.ALH, where al Alarm file prefix YY Last 2 digits of the year (e.g. 07 for 2007) MM Number of the current Month DD Number of the current Day There will be one Alarm history file created for each day. You can modify the Alarm History file path with the SetAlarmPath() function. Event Data files are also stored in the \Alarm subfolder in the Application directory. The file format is Text (UNICODE), and IWS uses the vertical bar (pipe) character (|) to separate the fields. Event files have an .EVT file extension. The Event file name syntax is evYYMMDD, where: ev Event file prefix YY Last 2 digits of the year (e.g. 07 for 2007) MM Number of the current Month DD Number of the current Day Trend Data files are stored in the \Hst subfolder in the Application directory. The file format is binary. The Trend file name syntax is WSYYMMDD, where: WS Trend Worksheet number in hexadecimal format (e.g. 01 for Trend001 Worksheet) YY Last 2 digits of the year (e.g. 07 for 2007) MM Number of the current Month DD Number of the current Day Alarm and Event data will be remain in the local computers file system for a predetermined period of time, according to the Historical Life Time settings. For Alarm and Event data, this parameter is set in the History Life Time field in the Alarm History and Events area of the dialog box accessed by Project Settings Option Tab. If the parameter is set to a value of 0, the historical data files are kept indefinitely. A positive value greater than 0 will determine the number of days the historical data files for Alarm and Event data is kept. The life of historical Trend data files is specified in the Advanced dialog box, accessed from the Trend Worksheet. In the History Life Time, a value in days is entered in the History Life Time field. If the value is greater than 0, this is the number of days that the Trend data is kept. If the value of this parameter is 0, the Trend data is kept indefinitely. An IWS built-in Function (HST2TXT) is available to convert binary historical Trend files into text files. While there is no corresponding function for the Alarm and Event historical data, this information can be displayed in an Alarm/Event Control Object, and can also be printed. Alarm and Event data files are text (Unicode) and can be opened by Notepad rd or other Microsoft and 3 party applications. The vertical bar character (|) separates the fields.

192

InduSoft Web Studio

Contents

IWS Training Guide

IWS Proprietary File and Database Format for Alarm History


When you enable the alarm history file for a group, IWS saves the alarm events to a history database, according to the File Format configured for the Alarm History. Each Alarm Event is saved on a new line in the Alarm History file, separated by the vertical bar (pipe) character. The format of the Alarm History data saved in the history file or to a SQL relational database is described in the following table.
P1 | P2 | P3 | P4 | P5 | P6 | P7 | P8 | P9 | P10 | P11 | P12 | P13 | P14 | P15 | P16 | P17 | P18 | P19 | P20 | P21 | P22 | P23 | P24 | P25 | P26 P1 | P2 | P3 | P4 | P5 | P6 | P7 | P8 | P9 | P10 | P11 | P12 | P13 | P14 | P15 | P16 | P17 | P18 | P19 | P20 | P21 | P22 | P23 | P24 | P25 | P26 .. P1 | P2 | P3 | P4 | P5 | P6 | P7 | P8 | P9 | P10 | P11 | P12 | P13 | P14 | P15 | P16 | P17 | P18 | P19 | P20 | P21 | P22 | P23 | P24 | P25 | P26

Field Number P1 P2 P3 P4 P5 P6

Field Name Version

Data Type Number

Remarks This field is created only when the File Format is Proprietary. Current version: 003 Timestamp indicating when the alarm started. When the File Format is Proprietary, IWS saves the Date (MM/DD/YYYY) in one field and the Time (HH:MM:SS.MSS) in the next field. Tag Name that caused the Alarm Alarm message 0: Indicates the alarm was acknowledged or does not require acknowledgment 1: Indicates the alarm was not acknowledged 0: Indicates the alarm is not active 1: Indicates the alarm is active Tag value when the alarm event occurred Tag value that occurred before the alarm event. This field only exists for Version >=3 Alarm Group Number Alarm Priority Number Alarm Selection value 1: HiHi 2: Hi(On) 4: Lo(Off)

Al_Start_Time

DateTime

Al_Tag Al_Message Al_Ack

String String Number

P7 P8 P9 P10 P11 P12

Al_Active Al_Tag_Value Al_Prev_Tag_Value Al_Group Al_Priority Al_Selection

Number Number Number Number Number String

P13

Al_Type

Number

8: LoLo 16: Rate(Change) 32: Deviation+ 64: Deviation0: Requires acknowledgement (Ack) 1: Does not require acknowledgement Timestamp indicating when the alarm was normalized. When the File Format is Proprietary, IWS saves the Date (MM/DD/YYYY) in one field and the Time (HH:MM:SS.MSS) in the next field.

P14

Al_Ack_Req

Number

P15 P16

Al_Norm_Time

DateTime

InduSoft Web Studio

193

IWS Training Guide

Contents

Field Number P17 P18

Field Name

Data Type

Remarks Timestamp indicating when the alarm was acknowledged.

Al_Ack_Time

DateTime

When the File Format is Proprietary, IWS saves the Date (MM/DD/YYYY) in one field and the Time (HH:MM:SS.MSS) in the next field. User logged when the alarm event occurred. This field only exists for Version >=1 Comment (optional) typed by the operator when the alarm was acknowledged. This field only exists for Version >=1 Full name of the user logged when the alarm event occurred. This field only exists for Version >=2 Name of the station (computer) where the alarm event occurred. This field only exists for Version >=2 0: Alarm message was not deleted 1: Alarm message was deleted This field is created only when the File Format is Database. Time Stamp when the register was created/modified. This field is used to synchronize the databases when using the Secondary Database in addition to the Primary Database. This field is created only when the File Format is Database. Difference (in minutes) from the Time Stamp columns and the GMT time. This field only exists for Version >=3

P19 P20 P21 P22

Al_User Al_Comment Al_User_Full Al_Station

String String String String

P23

Al_Deleted

Number

P24 P25

Last_Update

DateTime

P26

Bias

Number

Note: When saving the History Alarms in a SQL Relational Database (File Format = Database), you can customize the name of the columns created in the database by editing the <ApplicationName>.APP file, as follows: [Alarm] <DefaultName>=<NewName> For example: [Alarm] Message=Alarm_Message Ack=Acknowledgment

194

InduSoft Web Studio

Contents

IWS Training Guide

IWS Proprietary File And Database Format For Event History


Event log files are saved to a history database in the \Alarm subfolder by default. The information is saved according to the File Format configured for the Event History. Each Event log is saved on a new line in the Event History file, separated by the vertical bar (pipe) character. The format of the Event History data saved in the history file or to a SQL relational database is described in the following table. P1 | P2 | P3 | P4 | P5 | P6 | P7 | P8 | P9 | P10 | P11 | P12 | P13 | P14 | P15 | P16 | P17 P1 | P2 | P3 | P4 | P5 | P6 | P7 | P8 | P9 | P10 | P11 | P12 | P13 | P14 | P15 | P16 | P17 .. P1 | P2 | P3 | P4 | P5 | P6 | P7 | P8 | P9 | P10 | P11 | P12 | P13 | P14 | P15 | P16 | P17

Field Number P1

Field Name Version

Data Type Number

Remarks This field is created only when the File Format is Proprietary. Current version: 002 1: SECURITY SYSTEM 2: DISPLAY 3: RECIPE

P2

Ev_Type

Number

4: REPORT 5: CUSTOM MESSAGES 6: SYSTEM WARNING 7: LOG TAGS Timestamp indicating when the event occurred.

P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13

Ev_Time

DateTime

When the File Format is Proprietary, IWS saves the Event Time in the following format: MM/DD/YYYY HH:MM:SS.MSS. Tag Name User logged when the event occurred. Full name of the user logged when the event occurred. Event message Tag value when the event occurred Tag value that occurred before the event. This field only exists for Version >=2 Name of the station (computer) where the event occurred. Comment (optional) typed by the operator when the event occurred. This field only exists for Version >=2 Name of the task that generated the event 0: Event message was not deleted 1: Event message was deleted This field is created only when the File Format is Database.

Ev_Info Ev_User Ev_User_Full Ev_Message Ev_Value Ev_Prev_Value Ev_Station Ev_Comment Event_Source

String String String String Number Number String String String

P14

Ev_Deleted

Number

InduSoft Web Studio

195

IWS Training Guide

Contents

Field Number P15 P16

Field Name

Data Type

Remarks Time Stamp when the register was created/modified. This field is used to synchronize the databases when using the Secondary Database in addition to the Primary Database. This field is created only when the File Format is Database. Difference (in minutes) from the Time Stamp columns and the GMT time. This field only exists for Version >=2

Ev_Last_Update

DateTime

P17

Bias

Number

Note: When saving the History Events in a SQL Relational Database (File Format = Database), you can customize the name of the columns created in the database by editing the <ApplicationName>.APP file, as follows: [EventLogger] <DefaultName>=<NewName> For example: [EventLogger] Event_Info=Information Message=Event_Message

196

InduSoft Web Studio

Contents

IWS Training Guide

IWS Proprietary File and Database Format for Trend History


Trend Data files are saved to the \Hst subfolder to a binary file (IWS proprietary format), or to a SQL relational database. The fields saved in the History Trend file or SQL Relational database are described in the following table: Field Name TimeStamp Data Type DateTime Number <Tag Name> (Integer or Real format depending on the tag type) Number Remarks TimeStamp (Date and Time) when the data was saved. IWS will create one field (column) in the database for each tag configured in the Trend worksheet. Difference (in minutes) from the Time Stamp columns and the GMT time. This field only exists for Version >=2

Bias

InduSoft Web Studio

197

IWS Training Guide

Contents

Using the built-in ADO.NET Interface


IWS provides a built-in ADO.NET interface for the Alarm, Event and Trend Tasks and the Grid Object, allowing simple configuration and use. ADO.NET is Microsofts ActiveX for Data Objects that operates under the Microsoft .NET framework. The diagram below shows how this works in an IWS environment.

Built-in ADO.NET to Relational Databases The components are as follows: IWS Application An IWS application uses the ADO.NET interface to execute SQL (Structured Query Language) commands to manipulate data in a relational database. Available ADO.NET commands include commands to connect to a particular Database, as well as to store and retrieve records. The Alarm, Event and Trend Tasks and the Grid Object all have a built-in ADO.NET interface to store and retrieve data from a relational database. ADO.NET Providers The ADO.NET Provider (also known as a Data Provider) connects the client application via the ADO.NET API (applications programming interface) to the database. The ADO.NET providers can connect directly to certain databases (e.g. SQL Server, Oracle, MySQL), or through OLE-DB Providers or ODBC Providers. Data Providers include functions such as a SQL Query processor, a cursor engine (points to records in the database) and an interface to one or more databases Database This is generally a relational database, although CSV files can be supported through the Microsoft JET OLE-DB Provider
rd

One of the first considerations when using a 3 party database to store Alarm, Event, Trend or other data is the particular Relational Database to be used. There are usual tradeoffs between cost and performance, as well as corporate standards that may need to be adhered to.

198

InduSoft Web Studio

Contents

IWS Training Guide

Another consideration is the ADO.NET Provider to use. Several ADO.NET Providers are included with the Microsoft Operating System (e.g. Windows XP, 2000, Server 2003, or Vista) or the ADO.NET Provider may rd come from a 3 party. Some ADO.NET Providers provide connect directly to the database (usually for higher performance), while others connect to the Microsoft JET OLE-DB Provider or to ODBC. The following contains a partial list of ADO.NET Data Providers: ADO.NET Provider .NET for SQL Server* .NET for Oracle .NET for OLE-DB (SQLOLEDB)* .NET for OLE-DB (MSDAORA)* .NET for OLE-DB (Jet 4.0)* .NET for ODBC with SQL Server Driver .NET for ODBC with Oracle Driver .NET for ODBC with Access Driver Download Connector/Net 1.0 Download Connector/Net 5.0 * Required MDAC 2.6 or later Database Supported Microsoft SQL Server (Version 7 or later) Oracle (Oracle Client 8.1.7 or later) Microsoft SQL Server (Prior to Version 7) Oracle (Oracle Client prior to 8.1.7) Microsoft Access, Excel, CSV Microsoft SQL Server Oracle Microsoft Access MySQL (.NET 1.1) MySQL (.NET 2.0) Source Microsoft Microsoft Microsoft Microsoft Microsoft Microsoft Microsoft Microsoft www.mysql.com www.mysql.com

Notes: Use the .NET Framework Data Provider for SQL Server if using SQL Server version 7.0 or later Use the .NET Framework Data Provider for OLE-DB when using SQL Server 6.5 or earlier, or a singletiered Microsoft Access database. Using Access for middle-tiered applications is not recommended. Use the .NET Framework Data Provider for ODBC for single-tiered and middle-tiered applications that use ODBC data sources. Note that the ODBC Data Provider was not provided with .NET Framework version 1.0, but can be downloaded from the Microsoft website at http://msdn.microsoft.com/downloads. Use the .NET Framework Data Provider for Oracle with single-tier and middle-tier applications using Oracle client software 8.1.17 and later. Using a Microsoft Access database (with the Jet engine) as a data source for multi-threaded applications is not recommended. Microsoft recommends using SQL Server instead. If you use Microsoft Excel as a database, you may want to periodically compact the database. Microsoft recommends using the direct .NET Providers for SQL Server and Oracle when possible (based on the version of SQL Server or Oracle being used). These direct .NET Providers have a direct interface into the respective database and have been optimized for performance. These .NET Providers do not use OLE-DB or ODBC. This was done to improve transactional efficiency required by high-demand database server applications In addition to Data Providers, Service Providers may be available from Database suppliers. Examples of Service Providers include: - Persistence Provider: allows saving of rowset data and metadata to a local file - Remoting Provider: allows access to remote databases Microsoft has announced that they will be deprecating (obsoleting) certain legacy database interfaces, although they are still supported in the current MDAC release (MDAC 2.8). Microsoft wants you to use ADO.NET instead. The deprecated interfaces include: - ODBC Provider (MSDASQL) - Remote Data Services (RDS) Use SOAP instead - JET DAO (Data Access Objects) and Jet Replication Objects (JRO)

InduSoft Web Studio

199

IWS Training Guide

Contents

IWS can interface to virtually any Relational Database supported by a valid ADO.NET Provider, OLE DB Provider or ODBC Driver. Conformance tests were performed by InduSoft on the following databases: Database Microsoft SQL Server Microsoft Access Microsoft Excel MySQL Oracle Sybase Provider ADO.NET Provider for SQL Server ADO.NET Provider for OLE DB ADO.NET Provider for OLE DB ADO.NET Provider for OLE DB ADO.NET Provider for Oracle ADO.NET Provider for Sybase Conformance Test Table

Notes: A primary goal of ADO.NET is to provide a consistent interface between the application and a database, regardless of the database used. However, there will always be some database dependencies, such as supported data types and commands. You will need to acquire the ADO.NET Provider (and possibly OLE-DB Provider or ODBC Provider) rd from either Microsoft, the Database supplier, or a 3 party. Relational Database are sets of information stored in tables with fields (columns) and registers (rows), and inherently support SQL commands to manipulate the data. A database typically has more than one table. Each table has its own fields (columns) and registers (rows). Typically, the fields are pre-defined and the application adds or reads one or more rows, according to the SQL query command.

With the built-in ADO.NET interface provided by IWS, the Relational Database can be on the local computer or on a remote computer. This capability allows connection between an IWS application and an enterprise-level database. Although most applications typically link to only one type of database, IWS gives you the flexibility to link each task to a specific database supported by a Database Provider. Furthermore, by using this architecture, you do not need to worry about the specific characteristics of each database (it is mostly handled by the Database Provider for each database or by the Studio database gateway interface). Therefore, the application settings are mostly uniform, regardless of the specific database chosen by you, the end-user. For example, Alarms and

1910

InduSoft Web Studio

Contents

IWS Training Guide

Events could be logged to a remote database, while the Trend data can be stored locally in files using the IWS proprietary format. The following chart explains where the database configuration for each Task is located: Item <Default> Interface You can specify a default database that will be used unless otherwise specified. To specify the default database: From the Main Menu Bar, select Project Settings, and then select the Options Tab. Click on the Configure button in the Default Database section. From the Main Menu Bar, select Project Settings, and then select the Options Tab. In the Alarm History and Events section, select the Database option in the History Format combo box. Click on the Alarms Database button. From the Main Menu Bar, select Project Settings, and then select the Options Tab. In the Alarm History and Events section, select the Database option in the History Format combo box. Click on the Event Database button. From the Event Settings dialog box in the Database Workspace In a Trend Worksheet, select the Database option in the History Format combo box. Click on the Database Configuration button. In the Grid Object dialog box, select the Database option from the Data Source combo box. Click on the Data button.

Alarms Task

Events Task

Trend Task Grid Object

When the Database Configuration dialog box initially appears, it will likely be set to use the Primary default database (as specified in the Default Database settings). If the Default database is used, the Alarm, Events and Trend Tasks, as well as the Grid Object will have default table names that will be used. The default settings are:

Item Alarms Events Trend

Grid Object

Default Table Name AlarmHistory EventHistory TRENDGGG (GGG = Trend Worksheet Number e.g.: TREND001 for the Trend Worksheet 001) Name of the IWS application (without .App extension)

Of course, the default table names can be changed.

InduSoft Web Studio

1911

IWS Training Guide

Contents

Configuring the Default Database


To configure the Default Database, we need to access the Default Database Configuration dialog box: From the Main Menu Bar, select Project Settings, and then select the Options Tab. Click on the Configure button in the Default Database section.

The Default Database Configuration dialog box has the following settings and options: Database Combo Box Allows you to specify settings for the default Primary Database or the default Secondary Database. Secondary (redundant) databases will be covered in more detail later. Connection String field This field defines the database which IWS will write to and read values from. The Connection String can be entered manually or the Connection String Wizard can be used. User Name field User name used to connect to the database. The user name configured in this field must match the user name configured in the database. Password field Password used to connect to the database. The password configured in this field must match the password configured in the database. Retry Interval field If IWS is unable to connect to the database for any reason, it retries automatically to connect to the database after the number of seconds configured in this field have passed. Advanced button Provides access to customize database connection settings. For most applications, the default values for these settings do not need to be modified. These settings include: Milliseconds combo box: You can configure how the milliseconds will be saved when saving the date in the database. Each database saves the date in different formats; for example, some databases do not support milliseconds in a Date field. The following options are available: Default: Uses the format pre-defined for the current database. The databases previously tested by InduSoft are previously configured with the most suitable option. When selecting Default, IWS uses the setting pre-configured for the current database type. If you are using a database that has not been previously

1912

InduSoft Web Studio

Contents

IWS Training Guide

configured by InduSoft, the Default option attempts to save the milliseconds in a separate field. Disable: Does not save the milliseconds at all when saving the date in the database. Enable: Saves the milliseconds in the same field where the date is saved. Separate Column: Saves the milliseconds in a separated column. In this case, the date is saved in one field (without the milliseconds precision) and the number of milliseconds is saved in a different column. This option is indicated where you want to save timestamps with the precision of milliseconds but the database that you are using does not support milliseconds for the Date fields.

Note: The default option for each database is configured in the StudioADO.ini file, located in the \BIN sub-folder where the IWS Program is located. Save time difference check-box: When this option is checked (default), IWS saves the Time Zone configured in the computer where the application is running in each register of the database (Bias field). This option must be enabled to avoid problems with daylight savings time. Database Gateway: Specifies the Host Name/IP Address where the Studio database gateway will be running. The TCP Port number can also be specified, but if you are not using the default, you will have to configure the Studio database gateway with the same TCP Port. See the Studio Database Gateway section for information about how to configure the Studio ADO Gateway. Disable Primary Keys checkbox. Will disable IWS from using a primary key to speed up database access. This checkbox should be checked when using a database that does not support Primary Keys (e.g. Excel).

Note: The fields Table, Connection String, User Name, Password and Host name can have tags between curly brackets if you want to use dynamic values. When using Microsoft Excel, you need to check the Disable Primary Keys checkbox

The primary parameter that needs to be configured is the Connection String, which is different for every database. In the Default Database Configuration dialog box, enter a User Name and Password if required by the database. Click on the button to access the Connection String wizard. This wizard will help you define a Connection String to your database. You do not need to use the Connection String Wizard, but if you do not know the Connection String, this can be a very useful tool. After pressing the button, a Data Link Properties dialog box will appear. This dialog box has four tabs: Provider Defines the Database Provider that can be used. The list of Database Providers depends on the Providers actually installed and available in the computer where you are running IWS. Consult Microsoft OS documentation or Database documentation for further information on the Provider settings for the database you are using.

InduSoft Web Studio

1913

IWS Training Guide

Contents

Connection Specifies the source of the data and any log on specific information. This dialog box changes based on the Provider used. A Test Connection button is usually available to test the connection to the database Advanced Specifies Network Settings and Access Permissions All Allows you to specify values for any Properties used. This dialog box will depend on the Provider used.

The following are some typical settings to connect to a database:

Microsoft Access
Provider Connection Advanced All Microsoft Jet 4.0 OLE DB Provider Click on the button to specify the Database (*.MDB). Specify any User Name and Password required. Nothing needs to be changed Nothing needs to be changed

Microsoft Excel
Provider Connection Advanced All Microsoft Jet 4.0 OLE DB Provider Click on the button to specify the Database (*.MDB). Specify any User Name and Password required. Nothing needs to be changed Set the Extended Properties value to Excel 8.0, by selecting Extended Properties, then click the Edit Value button. In the Property Value field, type Excel 8.0. If a header is used in the Excel file, then type Excel 8.0; Hdr=Yes in the Property Value field.

Microsoft SQL Server


Provider Connection Advanced All Microsoft OLE-DB Provider for SQL Server Click on the button to specify the Database Server and the Database (Catalog). Specify any User Name and Password required. Nothing needs to be changed Nothing needs to be changed

Oracle 8i/9i/10g
Provider Connection Advanced All Oracle OLE-DB Provider for Oracle 8i, 9i or 10g Click on the button to specify the Database Server and the Database (Catalog). Specify any User Name and Password required. Nothing needs to be changed Nothing needs to be changed

1914

InduSoft Web Studio

Contents

IWS Training Guide

Configuring a Task or Object Database


You can specify a database for an Alarm, Event or Trend Task, or a Grid Object, that is different from the Application Default Database. The Database Configuration dialog box for each of these Tasks or Object can be accessed in the following manner: Item Alarms Task Interface From the Main Menu Bar, select Project Settings, and then select the Options Tab. In the Alarm History and Events section, select the Database option in the History Format combo box. Click on the Alarms Database button. From the Main Menu Bar, select Project Settings, and then select the Options Tab. In the Alarm History and Events section, select the Database option in the History Format combo box. Click on the Event Database button. From the Event Settings dialog box in the Database Workspace In a Trend Worksheet, select the Database option in the History Format combo box. Click on the Database Configuration button. In the Grid Object dialog box, select the Database option from the Data Source combo box. Click on the Data button.

Events Task

Trend Task Grid Object

Each of these items has a similar Database Configuration dialog box. To use a different database than the Application Default Database, do the following: Uncheck the Use application default check box. Configure the Connection String as was done for the Application Default Database, but specifying the new database you want to use for this item. If you want to use a Table different from the default table name, uncheck the Use default name in the Table section of the dialog box. Specify the Table Name in the Name field. If you want IWS to automatically create the Table specified in the Name field if it does not exist, leave the Automatically create check box checked. The Table Name field is a combo box that can look into the Database to determine any existing tables. Click on the Refresh button and then click the down arrow on the Name combo box to see any existing Tables is the Database. The Runtime section has Status and Reload fields that can have tag names. Status is an output defining the Status of the Database connection, and Reload is a trigger to reload values from the Database (e.g. can be used when a tag is used in the Connection String or User Name field and the tag(s) change value).

Notes: Both the Alarms and Events must be saved in the same format (i.e. IWS Proprietary or to a Relational Database). If stored to a Relational Database, the Relational Databases can be different Each Trend Worksheet can be individually configured to store data in the IWS Proprietary format or to a Relational Database.

InduSoft Web Studio

1915

IWS Training Guide

Contents

Primary and Secondary Databases


IWS supports redundant systems. When configuring the database interface, you can configure the Primary Database and, optionally, a Secondary Database. The Secondary Database can be configured in the following modes: Disabled: In this mode, IWS saves data in the Primary Database only. If the Primary Database is unavailable for any reason, the data is not saved anywhere else. This option may cause loss of data if the Primary Database is not available. Redundant: In this mode, IWS saves data in both Primary and Secondary Databases. If one of these databases is unavailable, IWS keeps saving data only in the database that is available. When the database that was unavailable becomes available again, IWS synchronizes both databases automatically. Store and Forward: In this mode, IWS saves data in the Primary Database only. If the Primary Database becomes unavailable, IWS saves the data in the Secondary Database. When the Primary Database becomes available again, IWS moves the data from the Secondary Database into the Primary Database. Other than enabling the Secondary Database and specifying the mode, configuration of the Secondary Database is similar to the configuration of the Primary Database. By using a Secondary Database, you can increase the reliability of the system by using the Secondary Database as a backup when the Primary Database is not available. This architecture is particularly useful when the Primary Database is located in the remote station. In this case, you can configure a Secondary Database in the local station to save data temporarily if the Primary Database is not available (e.g. during a network failure).

Notes: The Primary and Secondary can be different types of databases. However, they must have the same fields. Secondary database support is only available for Relational Databases, not with the IWS Proprietary databases.

1916

InduSoft Web Studio

Contents

IWS Training Guide

Linking to a remote DB Provider with Studio Database Gateway


Depending on the architecture of your project, the ADO.NET Provider for the SQL Relational Database may not be available in the same stations where IWS is running. This scenario is especially common when the application is run on the Windows CE operating system (currently, most Providers don not support the Windows CE operating system). In order to solve this problem, InduSoft designed a flexible solution that allows you to configure distributed systems, as illustrated in the picture below:

The application is running in the Studio Application station where IWS (or CEView) is installed. The application can communicate with the Studio database gateway (running in a remote computer) via TCP/IP. The Gateway implements the interface with the Database through the Database Provider available in the computer where it is running. The Studio database gateway does not require complex configuration. Just copy the files STADOSvr.exe and StudioADO.ini from the \BIN sub-folder of IWS and paste them under any directory of the computer that will be used as the Gateway station and execute the STADOSvr.exe program. There are advanced settings associated with the Studio Database Gateway, but they should be changed only under special circumstances. See the topic Studio Database Gateway for information on how to configure the Studio Database Gateway advanced settings. Notes: The Studio database gateway is a TCP/IP Server for the IWS application and it uses the TCP Port 3997 by default. You can specify a different port number when executing the STADOSvr.exe program according to the following syntax: STADOSvr.exe <Port Number> . Example: STADOSvr 3998 Be sure the TCP/IP Server is enabled during runtime (Project Status Execution Tasks. Be sure the TCP/IP Server is set to run automatically.

InduSoft Web Studio

1917

IWS Training Guide

Contents

Studio Database Gateway


The Studio Database Gateway is a TCP/IP server that interacts with databases using the Microsoft .NET Framework 1.1 or later. It can run on the same computer that is running the IWS application, or on a different computer. The Database Gateway Host in the Advanced Settings (see Database Configuration dialog) specifies whether the gateway will be running on the local computer or not. If you are using the local computer you should enter either localhost or 127.0.0.1 in the Host name. You do not need to worry about starting or stopping the gateway because it will be done automatically by IWS tasks. On the other hand, when running the gateway remotely, you need to start the gateway manually. To do so, copy the files StADOSvr.exe and StudioADO.ini from the IWS BIN folder to the remote computer, then execute the StADOSvr.exe. The gateway can be started multiple times for different TCP/IP port numbers. The default port number is 3997, and it is changed by specifying the desired port number in the command prompt (e.g. StADOSvr 1111). When running the StADOSvr, it will add the following icon to the tray bar:

By right clicking on the tray bar icon, the following options will display:

The hide option defines whether the debug window will be displayed or not. If you de-select it, the following window will display:

Any failure that occurs during operations with databases will be displayed both in this window and also in the IWS LogWin window (be sure Database Messages are enabled). The messages are reported by exceptions generated by the ADO.NET Provider. (For troubleshooting answers, please consult the ADO.NET provider documentation.)

1918

InduSoft Web Studio

Contents

IWS Training Guide

The Studio Database Gateway has Advanced Settings that are configured in the StudioADO.ini file. If you are having problems interfacing with a specific database, you will probably need to change some of these settings or add new providers to the file. The following parameters are available: Parameter SaveMSec Range of Values 1 - Disable 2 - Enable 3 - Separate Column Description This setting specify the default behavior for the provider when saving milliseconds. The default can be changed on the Advanced Settings in the Database Configuration Dialogs. Assembly option for all providers. The assembly has all the classes required to interface with the database. Most of the providers are inside the System.Data assembly.

Assembly

Any string that contains a .Net Framework assembly

ConnectionClass

The Connection Class is the one that Any connection class inside implements the System.Data.IDbConnection the assembly interface. Any data adapter class inside the assembly The Data Adapter class is used on operations where updates to the database are necessary. It must be compatible with the connection class specified and it should implement IDbDataAdapter.

AdapterClass

CommandBuilderClass

The Command Builder class is also responsible Any command builder class for updates on databases. It must be inside the assembly compatible with the connection class. One of the parameters in the connection string is the "Provider". The Studio ADO Gateway compares the value on the connection string with the value for this parameter in each provider and define the proper one to be used. Specify a character that will be placed before column names on SQL statements Specify a character that will be placed after column names on SQL statements This value indicates how constant values are identified on SQL statements. For Microsoft SQL databases for instance, the value should be @Value, for ODBC question mark (?) Indicates whether a sequential number should be added to the ValueString to identify the parameter or not. For Microsoft SQL database this parameter should have the value 1, because parameters are identified by using @Value1, @Value2 , @ValueN. For ODBC this parameter should be 0. When trying to create columns to store boolean values, the data type specified on this parameter will be used. You need to make sure that the data type specified is able to save boolean values.

Provider

Name of the provider

ColumnDelimiterPrefix ColumnDelimiterSuffix

Any character or group of characters. Any character or group of characters. Any string

ValueString

ValueAddNumber

0 or 1

BoolType

Any string representing a valid data type for the database

InduSoft Web Studio

1919

IWS Training Guide

Contents

Parameter

Range of Values Any string representing a valid data type for the database

Description When trying to create columns to store integer values, the data type specified on this parameter will be used. You need to make sure that the data type specified here is able to store 32 bit values. When trying to create columns to store real values, the data type specified on this parameter will be used. You need to make sure that the data type specified here is able to store 64 real values. When trying to create columns to store string values, the data type specified on this parameter will be used. You need to make sure that the data type specified is able to save the number of characters that you are willing to save on your application.

IntegerType

Real Type

Any string representing a valid data type for the database

String Type

Any string representing a valid data type for the database

A single section called [Providers] has all the parameters inside it. The default values are specified in the beginning of the file, using the prefix Default in each parameter as shown below: [Providers] DefaultSaveMSec=3 DefaultAssembly=System.Data DefaultConnectionClass=System.Data.OleDb.OleDbConnection DefaultDataAdapterClass=System.Data.OleDb.OleDbDataAdapter DefaultCommandBuilderClass=System.Data.OleDb.OleDbCommandBuilder DefaultColumnDelimiterPrefix=[ DefaultColumnDelimiterSuffix=] DefaultValueString=Value DefaultValueAddNumeber=1 DefaultTypeBool=INTEGER DefaultTypeInteger=INTEGER DefaultTypeReal=REAL DefaultTypeString=VARCHAR(255) DefaultTypeTimeStamp=DATETIME The next item on the file lists the amount of providers: Count=5 The providers are identified by the Provider parameter followed by a number. When connecting to a database, the Provider parameter in the connection string is compared to the providers identification, in order to determine which provider will be used. If there is no provider with the value on the connection string, all the default values are assumed. Besides its identification, each provider can have its own value per each parameter. Again, if no value is specified, the default is used. Below is an example with five providers: Provider1=MICROSOFT.JET.OLEDB SaveMSec1=3 Provider2=SQLOLEDB ConnectionClass2=System.Data.SqlClient.SqlConnection DataAdapterClass2=System.Data.SqlClient.SqlDataAdapter CommandBuilderClass2=System.Data.SqlClient.SqlCommandBuilder

1920

InduSoft Web Studio

Contents

IWS Training Guide

Provider3=MSDASQL ConnectionClass3=System.Data.Odbc.OdbcConnection DataAdapterClass3=System.Data.Odbc.OdbcDataAdapter CommandBuilderClass3=System.Data.Odbc.OdbcCommandBuilder Provider4=SQLOLEDB Assembly4=System.Data.OracleClient.OracleClient ConnectionClass4=System.Data.OracleClient.OracleConnection DataAdapterClass4=System.Data.OracleClient.OracleDataAdapter CommandBuilderClass4=System.Data.OracleClient.OracleCommandBuilder Provider5=ASAPROV Assembly5=iAnywhere.Data.AsaClient ConnectionClass5=iAnywhere.Data.AsaClient.AsaConnection DataAdapterClass5=iAnywhere.Data.AsaClient.AsaDataAdapter CommandBuilderClass5=iAnywhere.Data.AsaClient.AsaCommandBuilder

InduSoft Web Studio

1921

IWS Training Guide

Contents

Notes

1922

InduSoft Web Studio

Chapter 20. Using ODBC Database Source Names (DSN)


ODBC, short for Open Database Connectivity, is a standard software API method for using relational database management systems (RDBMS). The goal of ODBC is to allow SQL (Structured Query Language) queries to take place on the database independent of the programming language used. An ODBC implementation consists of three (3) components: 1. The Application (in this case, the IWS application) 2. A Core ODBC Library 3. A database Driver The Core ODBC library is provided by the Operating System (e.g. Windows XP) and interprets commands sent by the application to the database (through the Driver). The Driver is specific to a database, and only needs to know how to attach to the Core ODBC library. Almost every database in existence can be interfaced via ODBC. Microsoft now ships ODBC with every version of Windows (except Windows CE which does not support ODBC). In order to use this capability, you must use Microsoft .NET Framework 1.1 or higher. Note: The Microsoft .NET Framework 2.0 is automatically installed with IWS v.6.1 Service Pack 3 The connection between the Application and the Database starts by defining a DSN, or Database Source Name. This is structure to define the connection to the Database, including the protocol, host, port and database. This connection is defined in detail at the Operating System Services level, not at the Application (or VBScript) level. Note: A DSN (e.g. System DSN) must be specified by the Operating System To configure a DSN (e.g. Windows XP Pro), you click on the Start button, select Control Panel, and then Administrative Tools. Next, click on the Data Sources icon. This opens the ODBC Data Source Administrator dialog box. Note that there are three different type of DSNs: System DSN In general, you should use a System DSN. This type of DSN is not dedicated to a specific user, and is available to all users on the local computer. The data source is local to the computer. File DSN This type of DSN can be shared among all users who have the same driver(s) installed. The data source is not user-dedicated and need not be local to the computer. User DSN This type of DSN is only available to the current user and the data source is local to the computer.

InduSoft Web Studio

201

IWS Training Guide

Contents

To add a new System DSN, select the System DSN tab and click on the Add button. A new dialog box will appear, allowing you to select the driver for the ODBC DSN you are creating.

202

InduSoft Web Studio

Contents

IWS Training Guide

Once you have selected the driver, click the Finish button. A new dialog box will appear that allows you to specify the various Database connection parameters (e.g. the Connection parameters for and ODBC DSN to MySQL 5.0).

The Test button allows you to test the connection to the Database using the Connection parameters specified.

Notes: ODBC can be used with all Microsoft Windows Operating Systems except Windows CE ODBC allows you to connect to a wide variety of Database Servers. ODBC is an older technology, and is slower than an OLE-DB interface to a Database Server. You should use OLE-DB or a native ADO.NET Provider whenever possible instead of ODC. Microsoft Access does not support File DSNs. You must use a System DSN.

InduSoft Web Studio

203

IWS Training Guide

Contents

Using a Database with a DSN


Now that you have created a DSN, there are two ways you can use this DSN in an IWS application. The first is with native IWS Objects (Alarm, Trend, Event, and Grid). The second way is with VBScript.

TCP/IP IWS Application InduSoft Web Studio Database Gateway SQL Relational Database

ADO ODBC Drivers Provider

ODBC

IWS Connection to a SQL Relational Database via ODBC for Alarm, Trend, Event and Grid Objects

Using a DSN with Alarm, Trend, Event and Grid Objects To use a database with a ODBC DSN connection for the IWS native Alarm, Trend, Event and Grid Objects, you need to configure this via the Default Database Configuration. This is done by selecting Project Settings Options Default Database Configure button.

When you press this button, it opens up a Database Configuration Dialog that allows you to provide connection strings that will connect to an ODBC DSN. The connection string can be built automatically by clicking on the Browse button (). When the Data Link Window displays, you should select the option Microsoft OLE DB Provider for ODBC Drivers as shown below:

204

InduSoft Web Studio

Contents

IWS Training Guide

By clicking the Next button the following window will display:

Select the DSN (Data Source Name) that you want to connect, any User Name and Password, as well as the initial Catalog to connect to, and then click OK. If you want to specify the user name and password in the

InduSoft Web Studio

205

IWS Training Guide

Contents

Database Configuration dialog instead of being prompted, remember to check the Allow saving password checkbox. You can click on the Test Connection button to verify a valid connection to the database.

Using a DSN with VBScript To connect to a DSN with ADO in VBScript, the following illustrates a typical connection string: Dim oConn Set oConn = CreateObject(ADODB.Connection) oConn.Open (DSN=myDB;) There are additional connection string parameters that can be specified, see the Chapter Accessing Databases with VBScript.

206

InduSoft Web Studio

Contents

IWS Training Guide

Notes

InduSoft Web Studio

207

Chapter 21.

Alarms

Alarming is a key component of any HMI/SCADA system. WS supports On-line Alarms as well as Historical storage and retrieval of Alarms. The Alarm Worksheet, found in the Alarms folder in Tasks tab of the Workspace, configures which Tags are used for alarming, and the values that will trigger an Alarm. The Alarm/Event Control Object is used to display Alarms (historical and on-line) as well as Events. The types of Alarms are: HiHi Alarm limit when Tag value is too high; generates an alarm message when the tag value is equal to or greater than the HiHi Limit value. Hi Alarm limit when Tag value is high; generates an alarm when the tag value is equal to or greater than the Hi Limit value. Lo Alarm limit is when Tag value is low; generates an alarm when the tag value is lower than or equal to the Lo Limit value. LoLo Alarm limit is too low; generates an alarm when the tag value is lower than or equal to the LoLo Limit value. Rate Determines the speed of the variation rate for a tag. If the variation speed is higher than the established one in this field, generate an alarm. The speed can be determined per second, minute, or hour. Deviation+ Deviation for a higher value; generate an alarm when an augmentation in the tag value is equal to or higher than the established limit. Deviation Deviation for a lower value; generate an alarm when a diminution in the tag value is equal to or higher than the established limit. the Tag Properties dialog box, you can set a Deadband Value around the HiHi, HI, Lo and LoLo Alarm You can also specify a Deviation Setpoint, with Deviation+, Deviation- and Deviation Deadband Deadband Value & Time HiHi Hi Deviation+ Rate DeviationDeviation Setpoint Lo

Using limits. limits.

LoLo

When the Tag crosses an Alarm Threshold, it is called Activated. When the Tag value leaves the Alarm state, it is called Normalized. When the User acknowledges the Alarm, it is called Acknowledged.

InduSoft Web Studio

211

IWS Training Guide

Alarm Worksheets

Alarm Worksheets
You first need to specify the Tags used for Alarms in an Alarm Worksheet, entered in the Alarms folder in the Tasks tab of the Workspace. The Alarm Group Number is 1-999 and is specified in the number in the Alarm Worksheet, e.g. ALARMxxx.ALR where xxx=Alarm Group Number. The Alarm Group Number is used for runtime filtering of Alarms by Group Number.

Alarms can be On-line only or On-line & Historical (i.e. Alarms will be saved to a disk database such as the WS Proprietary Database or a Relational Database). The Alarm/Event Control Object is used to display either Online Alarms or Historical Alarms. Once an Alarm is Activated, it will be shown in the On-line Alarm/Event Control Object in the color specified in the Alarm Worksheet (default is Red). At this point, the Alarm can either be Acknowledged (in which case it will now be displayed in the Acknowledgment color default is Green) or it can remain in the Activated state until it returns to a Normalized value (in which case it will be displayed in the Normalization color default is light Blue). Once an On-line Alarm has been Acknowledged and Normalized, it will be removed from the On-Line Alarm Display. Historical Alarms, however, will retain every Alarm state for the Tag. In addition to the settings in the Alarm Worksheet, you can specify additional Tag Properties for alarming. Tag Properties are accessed by selecting the Tag (e.g. from the Tag Datasheet View) and clicking on the Tag Properties dialog Box. The Tag Properties dialog box is where the Deadband Value is set, as well as the Deviation Setpoint and the Deviation Deadband. This is the only dialog box where these Properties are set. All other Alarm Properties (e.g. Limits) can be specified in the Alarm Worksheet. A Deadband value around an Alarm limit is very useful when the Alarm is used for analog values (e.g. from a sensor) that are susceptible to some level of noise or digitization variance. Having a Deadband Value eliminates multiple Alarms triggering. For example. if a Tag has a Hi Alarm limit of 80 and a Deadband Value of 5, WS will generate an Alarm when the Tag value is >= 80. The Alarm is Normalized when the Tag value returns to a value < 75. If the Lo Alarm is set to 20, the Alarm will Activate when the Tag value is <=20. The Alarm will Normalized when the Tag value returns to a value >25.

212

InduSoft Web Studio

IWS Training Guide

Tag Properties Alarm Properties

In addition to the Hi, HiHi, Lo, LoLo and Rate Alarms, the Deviation+ and Deviation- Alarms are supported. These Alarms work around a Deviation Setpoint, defined by a Tag inserted in the Deviation Setpoint field as shown above. A Deviation Deadband can also be defined. Using the settings as shown above, with the Tag v5 set to a value of 50, the following results will occurDeviation+ Alarm occurs when Tag v4 value >= 61 Deviation+ Alarm Normalizes when Tag v4 value <= 59 Deviation- Alarm occurs when Tag v4 value <= 40 Deviation- Alarm Normalizes when Tag v4 value >= 41

Note: When using the Alarm types Rate, Deviation+ and Deviation- it is necessary to configure additional settings by the Tag Properties dialog, launched by the Tag Properties toolbar.

In addition to the above settings, you can filter Alarms based on Time settings. For example, you can specify how long an Alarm must continuously exceed the Alarm threshold before being recognized as an Active Alarm. Likewise, you can specify how long the Alarm must remain in the Normalized state before it will be recognized as being Normalized. These Time settings are specified in the Alarm Worksheet Advanced settings dialog box.

InduSoft Web Studio

213

IWS Training Guide

Alarm Worksheet

Advanced Settings Dialog Box

The Activation field, which contains either a value or an WS tag, specifies, in seconds, the amount of time each alarm in the Alarm Group must remain continuously in its alarm condition before becoming active. This option is useful to avoid generating alarms on intermittent conditions (e.g.: noise). If this field is left in blank, the alarm becomes active as soon as its condition is true. The Normalization field, which contains either a value or an WS tag, specifies, in seconds, the amount of time each alarm in the Alarm Group must remain continuously out from its alarm condition before becoming normalized. This option is useful to avoid normalizing alarms on intermittent conditions (e.g.: noise). If this field is left in blank, the alarm becomes normalized as soon as its condition is no longer true. The Time Stamp/Value field is a combo-box that lets you select the type of time stamp to be maintained by the Tag for the last significant Alarm activity, along with the value of the Tag at that time. You can select the type of activity that updates the time stamp: Activation/Norm (default): The time when the dead band ended that is, when the alarm becomes activated or normalized. Last Tag Change: The time when the value of the tag last changed during the dead band. Start Condition: The time when the dead band started. The Email Settings button opens a dialog box that allows you to specify settings for email messages that can be sent when Alarms occur. Email (SMTP) setting must be configured prior to use of the Alarm Emails. Attachments are not allowed in this dialog, but attachments can be emailed using WS built-in functions.

214

InduSoft Web Studio

Alarm/Event Control

IWS Training Guide

Alarm/Event Control
To display Alarms, either On-line or Historical Alarms, we need to use the Alarm/Event Control tool. This tool is found in the Active Objects Toolbar. When you select the Alarm/Event Control tool, you can place an Alarm/Event Control Object on your screen. An Alarm/Event Control Object looks something like the following:

By double-clicking on the Alarm/Event Control Object, you can open the Object Properties dialog box as shown.

The Type combo-box allows you to select what type of Alarms or Events are being displayed. The choices are: Alarm On-line Displays current Alarms. When an Alarm is Normalized and Acknowledged, it will disappear from this display. Alarm History Retrieves Alarms from the historical Alarm Database. Alarm History + Event Retrieves Alarms and Events from the historical Alarm Database and historical Event Database Event Displays current Events The Fonts button allows you to specify the Font for the Alarm/Event Control Object. The Columns button opens a Columns dialog box that allows you to specify the columns to be displayed in the Alarm/Event Control.

InduSoft Web Studio

215

IWS Training Guide

Alarm/Event Control

The Filters button opens a Filters dialog that allows you to specify filtering parameters, controlling which alarms will be visible during runtime. Alarm filtering can be used to allow the operator to focus on high-priority alarms, or alarms with some logical grouping (e.g. by location, type, etc.). Some of the key Alarm filters are: Alarm Group The Alarm Group corresponds to the Alarm Worksheet number, starting with 1. If Group 0 is specified, this means that all Alarm Groups are to be used. You can specify one or more Alarm Groups (e.g. 1, 3, 5-8). A string Tag can be used in this field to change the Alarm Group at runtime. Alarm Priority The Alarm Priority From and To fields are used to display Alarms in a given priority range. The Alarm Priority is specified in the Alarm Worksheet. Numeric tags or values can be used in these fields. Alarm Selection The Alarm Selection field corresponds to the text typed in the Selection field in the Alarm Worksheet. This can be a string Tag. Type This field allows you to enter the Alarm type to filter by (e.g. HiHi, Hi, Lo, LoLo) State This field allows you to enter the Alarm State which can be used to filter the Alarm display. Tagname, Message, Username You can sort based on the Tag name, the Message, or the User Name (log on name of the User)

The Advanced button opens an Advanced dialog box. Ack All Trigger Used to specify a Tag that will Acknowledge all Alarms. Ack Trigger Used to specify a Tag with will Acknowledge the last (the top) Alarm. Run-time dialog triggers Specifies Tags that will open Columns or Filters dialog boxes at runtime, allowing changes to be made. Total Items Can use an integer Tag in this field to return the total Alarms remaining after filtering the Alarms Selected Tag Can use a string Tag in this field to return the text name of a Tag that is associated with the Alarm. The Tag name can be used as a string Pointer tag to acknowledge the specific alarm. Navigation Triggers Can specify Tags (associated with objects such as buttons) that can navigate the Alarm list.

216

InduSoft Web Studio

Alarm/Event Control

IWS Training Guide

Exercise: Creating an Alarm Group and Alarm Screen


In this exercise, we will develop an Alarm Group and Alarm Screen that generated Alarms based on the level of the tanks used in the TankDemo screen. Create the following tags:
Tag Name Size Type

SelAlarm TotAlarms TotUnAck

0 0 0

String Integer Integer

Select the Tasks tab of the Workspace and then right-click on the Alarms folder. Select Insert from the pop-up menu to open an Alarms Worksheet.

Opening an Alarm Worksheet Complete the Alarms Worksheet as follows:

ALARM001.ALR Worksheet

InduSoft Web Studio

217

IWS Training Guide

Alarm/Event Control

Click the Advanced button Complete the Advanced dialog box as follows:

Advanced Dialog

Click OK to close the Advanced dialog box Save and Close the Alarms Worksheet

Next, we will create an On-Line Alarm display. Open the Alarms.scr Screen Click the Alarm/Event Control tool and create an Alarm/Event Control object on the screen. Double-click the Alarm/Event Control object to open the Object Properties dialog.

Object Properties: Alarm Make sure the Type is set to Alarm Online Click the Advanced button in the Object Properties dialog box to configure the Advanced Settings for the Alarm/Event Control

218

InduSoft Web Studio

Alarm/Event Control

IWS Training Guide

Configure the Advanced dialog box as follows

Advanced Dialog Click OK to close the Advanced dialog box. Close the Object Properties dialog.

Create three (3) buttons on the Alarms.scr Screen with captions as follows:

Alarm Acknowledgement Buttons

InduSoft Web Studio

219

IWS Training Guide

Alarm/Event Control

The first button will toggle the value of the internal Tag AckAll, to acknowledge all alarms that occurred. Give the button the caption Ack All Alarms, add the Command property to the button, and configure the command as shown

Configuring the Ack All Alarms Button The second button will toggle the value of the internal tag AckAlr, to acknowledge the last alarm that occurred. Give the button the caption Ack Last, add the Command property to the button, and configure the command as shown:

Configuring the Ack Last Alarm Button The third button will toggles the Ack Tag Field of the Tag which caused the Alarm. When the User clicks on any individual Alarm, the (string) name of the Tag that caused the Alarm will be returned in the SelAlarm tag (as specified in the Advanced dialog of the Alarm/Event Control). This string Tag can be used as a pointer to the actual Tag that caused the Alarm. By toggling the Ack field of the Tag, it will acknowledge the individual Alarm. Give the button the caption Ack Selected Alarm, add the Command property, and configure the command as shown:

Configuring the Ack Selected Alarm Butto Close the button Object Properties dialog box.

2110

InduSoft Web Studio

Alarm/Event Control

IWS Training Guide

Now, we will add a Historical Alarm display Make sure the Alarms.scr Screen is open Click the Alarm/Event Control tool and create an Alarm/Event Control object on the screen. Double-click the Alarm/Event Control object to open the Object Properties dialog. Position the Alarm/Event Control below the On-line Alarm/Event Control Make sure the Type is set to Alarm History

Alarm History Object Properties

Now, we will finish the Alarm Screen. Add a Text object with the Caption Total Alarms = ######. Add the Text I/O Property, and specify the Tag as TotAlarms. Add a Text object with the Caption Total Unacknowledged = ######. Add the Text I/O Property, and specify the Tag as TotUnAck. Add a Text object above the On-Line Alarm/Event Control object, with the caption On-Line Alarms Add a Text object above the Historical Alarm/Event Control object, with the caption Historical Alarms

InduSoft Web Studio

2111

IWS Training Guide

Alarm/Event Control

The finished Alarms.scr should look similar to the following:

Save and Close the Screen The following table is provided to illustrate how the WS Alarms task counts alarm messages for the Total Alarms and Total UnAck field totals: Alarm State Active Acknowledgement State Unacknowledged Acknowledged Normalized Unacknowledged Acknowledged Counted for Total Alarms Tag? Yes Yes Yes No Counted for Total UnAck Tag? Yes No Yes No

2112

InduSoft Web Studio

Alarm/Event Control

IWS Training Guide

Notes: When using Alarm Worksheets, before changing the Group Name field, you should first save the Alarm worksheet. Otherwise, you can lose alarm settings in an unsaved worksheet. In the Alarm Worksheet Advanced settings dialog, it is recommended to use unique Tag names for the Total Alarms and Total UnAck fields for each Alarm worksheet. When configuring the Alarm Worksheet, if you did not select the Summary option, the alarms for this group will not appear in the alarm objects in the screens or printer during execution. When configuring the Alarms Worksheet, the Printer check-box should not be used with DeskJet or LaserJet printers because they will spend one entire leaf of paper for each alarm message. These printers are not able to print one line and then wait for the next printing command. Alarm messages can contain any system tag using the following syntax: message {tag_name} The Selection field must have a string with a maximum of 7 characters (additional characters will be ignored). When using the Alarm Email function, you must be connected to the Internet (manually or using an automatic dial-up function) and you must have executed the WS built-in function CNFEmail to configure the SMTP server, user name, password, and domain before trying to send an email.

InduSoft Web Studio

2113

IWS Training Guide

Example: Disabling Alarms

Example: Disabling Alarms


There are times when you may want to disable an alarm triggered by a tag or group of tags. This can easily be accomplished by manipulating the tags AlrDisable field during runtime. The AlrDisable field is R/W, and if the field is set to 0, any alarm associated with the tag is enabled. This means that if an alarm condition occurs, an Alarm will be generated If the field is set to 1, any alarm associated with the tag is disabled. This means that if an alarm condition occurs, an Alarm will not be generated. You can read or manipulate (set) the AlrDisable filed by the following syntax: From an IWS Math Script Tag AlrStatus TagName->AlrDisable TagName->AlrDisable Expression TagName->AlrDisable //returns the current Alarm disable status 0 1 //enables Alarms from this tag //disables Alarms from this tag

From VBScript $AlrStatus = $TagName-> AlrDisable $TagName->AlrDisable = 0 $TagName->AlrDisable = 1

//returns the current Alarm disable status for this tag //enables Alarms from this tag //disables Alarms from this tag

2114

InduSoft Web Studio

Exercise: Adding an Alarm/Event Control Display

IWS Training Guide

Exercise: Adding an Alarm/Event Control Display


Open the Header.scr Screen Add an Alarm/Event Control Object Double click on the Alarm/Event Control to open the Object Properties dialog box In the Type field, select Alarm History + Event

Save and Close the Header.scr Screen

InduSoft Web Studio

2115

IWS Training Guide

Exercise: Adding an Alarm/Event Control Display

Notes

2116

InduSoft Web Studio

Chapter 22.

Data Logging & Trend Display

In this Chapter, we will cover Data Logging (using the Trend Task) and Trend Display (using the Trend Control Object placed on a Screen). These two items (Data Logging & Trend Display) are normally used together, but do not have to be. Data Logging can occur without the data being used in a Trend Display, and the Trend Display (Trend Control Object) can be used with historical data from a database.

Configuring the Trend Task


The Trend Task is used to log IWS Tag data to a database. The Trend Task defines which data is logged and where it is logged to. Data can be logged to local files (will have a *.hst file extension) using the IWS proprietary format, or can be logged to a database using the built-in ADO database interface. Like other Tasks, the Trend Task consists of one or more worksheets that are sequentially numbered starting with 1. You can add a new Trend Worksheet by doing the following: Click on the Tasks tab in the Workspace in the development environment Position you mouse cursor over the Trend folder and click the right mouse button. Select the Insert option

As an alternative, you can select File New from the Main Menu Bar, or click on the New icon in the Standard Toolbar, and select Trend Worksheet.

The Header parameters are: Description A description of the worksheet, for documentation purposes only History Format Allows you to define where the Trend Data is to be saved, in a file using the IWS Proprietary format or in a Database. If Proprietary is selected, the Database Configuration button is grayed out. Database Configuration Opens a Database Configuration dialog box. See the Chapter on IWS Database Configuration for more details.

InduSoft Web Studio

221

IWS Training Guide

Configuring the Trend Task

Advanced Allows you to enter settings for Batch, Disk Space Control and Disabling of the data logging. Save on Trigger check box This check box should be checked if you want to log (save) data when the Tag in the Trigger field toggles (changes) value Note: If you want to save data based on a time base, then you should check the Save on Trigger check box and UNCHECK the Save on Tag Change check box. The time base for a Trigger Tag can be specifed in the Scheduler Task.

Trigger field This field is used to enter the Tag used to Trigger the data logging function if the Save on Trigger check box is checked. Save on Tag Change check box This check box, if checked, will save all the tags in the Trend Worksheet whenever any of the tags in the Worksheet change value.

The Trend Advanced Settings dialog box, configured to store data to a Batch File using IWS Proprietary format, is shown below.

The Batch Pane has the following settings: Start/Stop Insert a Tag into this field to trigger the starting or stopping of data logging to the Batch File. If the Tag value is 0, the data logging will be stopped. If the Tag value is <>0, data logging will start (continue logging). If History Format = Proprietary Data will be logged into the Batch File specified If History Format = Database Data will be logged into a new Record (row) in the Database in a Table specified in the Database Configuration dialog

222

InduSoft Web Studio

Configuring the Trend Task

IWS Training Guide

Name This field can be a string value or a string Tag (configured in curly braces, e.g. {strTag}). If History Format = Proprietary Name should be a name of a file where the Batch data will be logged. File should have a *.HST file extension. Format of the Name should be [Path]<FileName>, where Path is an optional Path name. Will default to the Application folder. FileName is the Batch History file. Note: The Batch Name can use one or more Tags in the Path\FileName field. Tags must be enclosed in curly braces. E.g. C:\MyBatch\{BatchName} {BatchNumber}.hst . If History Format = Database

The Name value will be stored in the Batch_Name field of the BatchHistory Table.

Delete Enter a Tag in this field. When the tag toggles (changes value), the Batch will be deleted. If History Format = Proprietary Batch History File will be deleted If History Format = Database Will set the Delete field in the BatchHistory Table to True, but the data will be remain. The Trend Control Object will only view Batch data that has the Delete Field set to 0 (False).

Existent Enter a Tag in this field. It will receive a value of 1 (True) if the Batch specified in the Name field already exists, otherwise it will receive a value of 0 (False). Description This field is only used when History Format = Database. This field can contain a string or a string Tag enclosed in curly braces. When the tag in the Stop/Start field changes to True (non-zero value), the Record (row) added to the BatchHistory Table in the Database will display the string value in this field. Save Data Even if Batch is Not Running check box This check box will determine when data is saved to the Batch file or database. If Unchecked, the historical data will only be logged when the Tag in the Stop/Start field is True (i.e. a non-zero value).

The Disk Space Control Pane has the following settings: History life time (Days) Specifies how many days to keep the history file on the disk. After the specified period. IWS will automatically erase the file. This option is for the History Format = Proprietary only. If a value of 0, the files will not be erased. Compress after (Days) Specifies the number of days to keep the trend history file (*.hst) on the disk before compressing the file. This option is for the History Format = Proprietary only. If a value of 0, the files will not be erased. Disable All Data Saving Enter a Tag in this field. When the value of this Tag is True (<>0), the Trend Task will stop recording for this Worksheet.

InduSoft Web Studio

223

IWS Training Guide

Converting Trend History Files

The Body Parameters have the following fields: Tag Name field Enter the name of a Tag to be logged in this field. Deadband field. This option is only when the Save on Tag Change check box is checked. The value in this field defines the amount the Tag needs to change value (either up or down) in order for the tag to be logged to the database. Field field. When the History Format = Database option is selected, this field will appear. It is used to define the Field (Column) in a database where the Tag will be stored. If this field is left blank, the name of the Tag will be used as the Field Name. If you use an Array Tag or Class tag, the Array Index square brackets [ and ] as well as the Class Name/Class Member separator, the . character (period), will be replaced by the underscore character _ . E.g.: MyArray[1] MyClass.Member MyClass[3].Member MyArray_1 MyClass_Member MyClass_3_Member

Note: Historical Data stored in a file using the IWS Proprietary format can be displayed by the Trend Control Object. Historical Data stored by a Trend Worksheet into a Database can be displayed by the Trend Control Object or by the Grid Object. Once you log data to a File (using the IWS Proprietary format), DO NOT add or remove tags, otherwise the data will be incorrectly read. Use the Scheduler to define time bases (other than Second or Minute). Be mindful of the storage requirements if you log several tags at a high data rate. Be mindful of network bandwidth requirements when logging to a remote database You can store up to 240 tags in a single Trend Worksheet. You can have up to 999 Trend Worksheets.

Converting Trend History Files


Trend History Files stored in the IWS proprietary format are binary files and cannot be read by simple text editors. IWS provides a built-in function Hst2Txt that can be called to convert the binary file into a text file. The Hst2Txt function can be called at a command level using the Windows CMD command processor. IWS provides a function to convert text-based historical data files to IWS proprietary format binary files. This function, Txt2Hst.exe, can only be called from the Windows CMD command processor.

224

InduSoft Web Studio

Trend Control Object

IWS Training Guide

Trend Control Object


The Trend Control Object is used to display data points (values) from different data sources in a graphic format. The main features provided by the Trend Control object are: Display of multiple pens simultaneously Support for different Data Sources, such as Tag, Batch, Database and Text File Capability to generate X/Y graphs from the configured data sources Simultaneous display of an unlimited number of data points. This feature might be limited by the hardware used since available memory and performance will vary. Built-in toolbar, which provides interfaces for the user to interact with the Trend Control object during the runtime Built-in legend, which displays the main information associated to each pen linked to the object Zooming and auto-scaling tools Horizontal and vertical orientation

Trend Control Development Interface


Although the Trend Control object supports flexible configurations to meet the specific needs of your application, most of the settings are set by defaults based on the most common interfaces. Therefore, in many cases, you will only configure data points (displayed during the runtime), which can be done easily by clicking the Points button from the Object Property window. Click the Trend Control tool to add it to your application screen. Double-click on the object to launch its Object Properties dialog window:

Trend Control Object Properties Dialog

The settings in the Trend Control Object Properties dialog box are: Border Specifies a border line Type (style) by clicking on None, Solid, Dashed, Etched, Raised or Sunken. You can also select the color of the border line with the color box to the right of the Type field. Fill If Fill radio button is selected, you can choose a background color for the Trend Control object from the color box. If you select the No Fill radio button, the background of the Trend Control object will be transparent. Axes Allows you to configure the settings for the X and Y axis.

InduSoft Web Studio

225

IWS Training Guide

Trend Control Object

Data Sources Allows you to define the Data Sources to be used by the Trend Control Object. You can have one or more Data Sources. Legend Lets you choose whether to show an embedded legend during the runtime, and if so, which fields to display in it. Toolbar Lets you choose whether to show an embedded toolbar during the runtime, and if so, which buttons (or Tags) that trigger actions to display in it. Advanced Lets you configure additional options, such as runtime triggers and custom point selection.

Trend Control Runtime Interface


When enabled, some embedded interfaces can help you to interact with the Trend Control during the runtime: The Toolbar option lets you choose whether to show an embedded toolbar during the runtime, and if so, which buttons that trigger actions to display in it. The Legend option lets you choose whether to show an embedded legend during the runtime, and if so, which fields to display in it. Using the Scroll bar, you can slide through the X-axis values, according to the period configured for this scale. Using the Time bar, you can modify the Duration, as well as the Start Date/Time and/or the End Date/Time, for the data displayed on the object. Changing these values will affect the tags associated with the X-axis scale (if any).

Toolbar Scroll Legend Time

Embedded Interfaces in the Trend Control Object

226

InduSoft Web Studio

Exercise: Creating an Online Trend

IWS Training Guide

Exercise: Creating an Online Trend


The online trend you create in this exercise will graph the temperatures of the tanks in real-time, updated every second. While the application runs, trend data are saved to an internal history file, so the trend graph can be scrolled to display any period in the trend history.

CREATING A TREND WORKSHEET


First, you must create a Trend worksheet specifying the Tags that will be saved to the history file and made available to any Trend Control objects in the application: Create a new Trend worksheet by right-clicking on the Trend folder (in the Tasks tab of the Workspace) and selecting Insert:

Inserting a Trend Worksheet Notes: You can also create new worksheets using the New dialog, which is accessed by selecting File New or by pressing the Ctrl+N keyboard shortcut. The Trend Worksheet is used to define where & how the data is to be logged. The Trend Control Object is used to define how the data is to be displayed.

Configure the Trend worksheet as shown:

Configuring the TREND001.TRD Worksheet Save and Close the Worksheet

InduSoft Web Studio

227

IWS Training Guide

Exercise: Creating an Online Trend

CREATING THE TREND SCREEN


Next, we will open the TrendData.scr Screen and add a Trend Control object. This will be used to display the trend data. Open the TrendData.scr Screen Click on the Trend Control tool icon in the Active Objects toolbar and add a Trend Control Object on the screen. Open its Object Properties dialog:

Trend Control Object Properties Dialog Because of the large number of properties available on a Trend Control Object, the properties are divided among secondary dialogs. Click the Axes button to open the Axes dialog:

Trend Control Object Properties Axes Dialog The X-axis of the trend graph will be standard Date/Time, but its format must be adjusted.

228

InduSoft Web Studio

Exercise: Creating an Online Trend

IWS Training Guide

In the X Axis area, click the Scale Format button to open the Format: Date-Time dialog:

X Axis Format: Date-Time Change Number of Labels to 4, and then click OK to close the Format: Date-Time dialog and return to the Axes dialog. The Y-axis format must also be adjusted. In the Y Axis area, click the Format button to open the Format: Numeric dialog:

Y Axis Format: Numeric Change Number of Labels to 4, click OK to close the Format: Numeric dialog and return to the Axes dialog.

By default, multiple trend data points are each displayed in their own sections of the trend graph. However, in this exercise the data points should be displayed together in the same section, so that they can be compared as they progress. In the Y Axis area, click the Multiple Sections checkbox to deactivate it (it should be unchecked). Click OK to close the Axes dialog and return to the Object Properties dialog.

InduSoft Web Studio

229

IWS Training Guide

Exercise: Creating an Online Trend

Next, the data points themselves must be configured. In the Object Properties dialog, click the Points button to open the Points dialog:

Trend Control Object Properties Points Dialog Configure three data points as follows Point 1: Label: Tank 1 Temp Color: Black Data Source: Tag Tag/Field: tank[1].Temperature Min: 0 Max: 100 Point 2: Label: Tank 2 Temp Color: Dark Red Data Source: Tag Tag/Field: tank[2].Temperature Min: 0 Max: 100 Point 3: Label: Tank 3 Temp Color: Dark Green Data Source: Tag Tag/Field: tank[3].Temperature Min: 0 Max: 100

2210

InduSoft Web Studio

Exercise: Creating an Online Trend

IWS Training Guide

When you are done, the Points dialog should look something like this:

Points Dialog with Three Points Configured Click OK to close the Points dialog, and then close the Object Properties dialog. The finished TrendData screen should look something like this:

Trend Online Screen Save and Close the Screen If you run the application now, the trend graph will display (in real-time) the simulated data generated by the field process simulator that you created in the previous chapter.

InduSoft Web Studio

2211

IWS Training Guide

Exercise: Creating an Online Trend

Decreasing the Save Frequency Using the Scheduler


As it is now configured, the Trend worksheet saves to the history file and updates the trend graph every second. While this makes for a smooth graph, it also decreases system performance and generates extremely large history files. You can decrease the save frequency by reconfiguring the Save On Trigger field (on the Trend worksheet) with a different tag or expression. The field is currently configured with the Second tag, which is one of the standard Internal Tags in IWS. Every time the value of the tag changes which is every second, of course the save is triggered. You could easily reconfigure the Save On Trigger field with another Internal Tag (e.g. Minute, Hour, Month, and so on), but this may trigger saves too infrequently to be useful. To trigger saves at a nonstandard frequency, use the Scheduler: Create a new Tag in the Application database (review the procedure on page Error! Bookmark not defined. if necessary) with the following specifications: Name: TrendUpdate Size: 0 Type: Boolean Description (optional) Scope: Local Open the Trend worksheet and reconfigure the Save On Trigger field with this new tag:

Create a new Scheduler worksheet (in the Tasks tab of the Workspace), and then add the following line:

Configuring the SCHED001.SCH Worksheet This line will cause TrendUpdate to toggle every 15 seconds. TrendUpdate was defined as a Boolean, and the expression changes the value of the tag to its opposite state: from FALSE to TRUE, then from TRUE to FALSE, and so on. Every time the value of the tag changes, a save is triggered. Save and close both worksheets.

2212

InduSoft Web Studio

Using an External Text File

IWS Training Guide

Using an External Text File


The Trend Control can generate trend charts from any Text File that has the values organized in columns and rows. The columns should be separated from each other by special characters (usually the comma). Each sample (pair of values representing a point in the graph) is represented by a row (a line in the file). Suppose that the user wants to display a chart with the information in the following table: X Value 0 1 2 3 Y1 Value 0 1 2 3 Y2 Value 10 20 30 40

We have one variable that represents the X Axis and two variables (Y1 and Y2) that will represent different lines in the chart. The first step is to convert the data into a text file. If we adopt the comma as our separator the file will be as shown below:

Creating a Text File Using Notepad.exe We strongly recommend that you save the file in the same folder where the application is. By doing so, you do not have to specify the entire path and your application will still work, even if it is copied to a different computer.

InduSoft Web Studio

2213

IWS Training Guide

Using an External Text File

Once you have added the Trend Control to your screen, double click on the object to open then Object Properties and click on Axis. Change the Data Type of the X Axis to numeric, and set the ranges as shown in the picture below:

Configuring the X Axis for Numeric Data Click Ok on this Window and then, in the Object Properties window, click on the Data Sources button. The following window will display:

Trend Control Object Properties Data Sources We need to create a data source in order to access to the text file. Click on the new button, specify the Data Source Name MyTextFile and then click Create. You should see the following information now:

Creating a New Data Source (Text File)

2214

InduSoft Web Studio

Using an External Text File

IWS Training Guide

On the X Axis field we need to indicate which column in our text file represents the X Axis. In our example we are using column zero, so enter with zero for this field, then click on the button Data Source Settings, the following Window will display:

Specifying the Text File Name and Field Delimiter If you have copied the text file to the application folder, you only have to specify the file name, otherwise, enter with the complete path where the file is located (use the browse button as needed). Click Ok on this window and Ok again to finish the data source configuration and close the Data Source configuration Window. Now we need to define our Y1 and our Y2. They will be represented by points on our Trend Control. Double click on the Trend Control again to access the Object Properties window and then click on Points. Your next step is to define the points according to the following figure:

Configuring the Data Points (Pens) After following these steps, run your application and you should see something similar to the figure below:

InduSoft Web Studio

2215

IWS Training Guide

Using an External Text File

2216

InduSoft Web Studio

Using an External Database

IWS Training Guide

Using an External Database


The Trend Control can generate trend charts from any Relational Database that can be accessed through the ADO.Net technology. This Appendix illustrates how to access a Microsoft Access Database; if you are using another type of database, almost all the definitions will apply, however you will need to configure your connection on a different way. For information on how to configure other databases, please refer to the Appendixes in the Database Interface section of this manual. Suppose that you have an access database at your C drive named mydata.mdb and that you want to generate a chart based on the information in the following table:

Table in a Relational Database The first step is to add the Trend Control to your screen. Now double click on the object to open then Object Properties and click on Data Sources. The following window will display:

Trend Control Object Properties Data Sources

InduSoft Web Studio

2217

IWS Training Guide

Using an External Database

We need to create a data source in order to access to the database. Click on the new button, specify the Data Source Name MyDB and then click Create. You should see the following information now:

Creating a New Data Source (Database) Change the Source Type to Database and specify Time_Stamp in the X Axis field. Then click on the Data Source Settings button, the following window will display:

Database Configuration Window

2218

InduSoft Web Studio

Using an External Database

IWS Training Guide

Uncheck the check box Use application default and click on the browse button connection string. The following window will display:

in order to configure the

Data Link Properties Selecting a DB Provider Select the Microsoft Jet 4.0 OLE DB Provider and click Next. In the following window, you should specify the database path:

Data Link Properties Configuring the DB Connection

InduSoft Web Studio

2219

IWS Training Guide

Using an External Database

Click Ok to finish the Connection String configuration. Now uncheck the option Use default name and select the table from your database as shown below:

Selecting the Database Table Click Ok on this window and Ok again to finish the data source configuration and close the Data Source configuration window. Now we need to define Temperature and Pressure. They will be represented by points on our Trend Control. Double click on the Trend Control again to access the Object Properties window and then click on Points. Your next step is to define the points according to the following figure:

Configuring the Data Points (Pens)

2220

InduSoft Web Studio

Using an External Database

IWS Training Guide

If you run the trend, it will start with the current date/time. In order to see the data in the chart you will have to properly configure the start date/time as shown below:

InduSoft Web Studio

2221

IWS Training Guide

Using an External Database

Notes

2222

InduSoft Web Studio

Chapter 23.

Event Manager

The Event Manager is used to log Events to either the WS proprietary database or to a relational database and is configured through the Event Settings dialog box. The types of events that can be logged include: Security System Events When checked, any Security System event will be logged into the Event Database. Examples include user log on and log offs, password expired, invalid log on attempts, etc. Display Change Events When checked, any Screen being opened or closed will be logged to the Event Database. Recipe Events When checked, any Recipe function (e.g. Recipe Load or Recipe Save) will be logged to the Event Database Report Events When checked, any Report function (printed or saved to a disk) will be logged to the Event Database Custom Messages When checked, custom messages created by the User (via the WS built-in function SendEvent() will be logged to the Event Database. System Warnings When checked, general system warnings will be logged to the Event Database. General System Warnings include: - Division by 0 - Accessing an invalid array index - Errors that occur when sending an alarm email Tag Events When checked, will allow you to log changes to a Tags value. The change in Tag value may or may not be the result of operator input and the logging of the Event is made whether the Tag triggers an Alarm or not.

InduSoft Web Studio

231

IWS Training Guide

Exercise: Configuring Event Retrieval

Exercise: Configuring Event Retrieval


Select the Database tab. Right-click the Event Settings icon, and select Open from the pop-up to open the Event Settings dialog:

Selecting Event Settings

Event Settings Dialog

232

InduSoft Web Studio

Exercise: Configuring Event Retrieval

IWS Training Guide

Configure the parameters on the Event Settings dialog as follows: Enable event logger check-box: Enable (check) this box to enable event-logging. Disable field (optional): Type a tag into this field. If the tag value is other than 0 (0=false), WS automatically disables the Event Logger. Event Database : Used to configure the Event Database (for relational databases) Security System check-box: Enable (check) this box to include security system events in the historic event file. WS logs the following security system events: Log On / Log Off users User created/removed using the CreateUser() or RemoveUser() functions User blocked/unblocked using the BlockUser() or UnblockUser() functions User blocked by the security system after several attempts to enter an invalid password Password expired Password modified Invalid Log On attempt

Display check-box: Enable (check) this box to include screen Open and Close events in the historical event file. Recipe check-box: Enable (check) this box to include recipe load, save, init, and delete events in the historical event file. Report check-box: Enable (check) this box to include reports saved to disk or send to printer events in the historical event file. Custom Messages check-box: Enable (check) this box to include events generated by the SendEvent(strEvent) function in the historical event file. System Warning check-box: Enable (check) this box to include general system warnings (such as Division by zero, Attempted to access invalid array index, and so forth) in the historical event file. WS logs the following system warning events: Errors that occur when sending alarms by email Tag was blocked/unblocked Division by zero Connection/Disconnection of the remote security system

Tags check-box: Enable (check) this box to enable and log tag changes in the historical event file. Configure the tags you want to log in the Tags table as follows: Tag Name column: Type the name of the tag you want to log in the event file. Dead Band column: Type a value for comparing and filtering acceptable changes. For example, if you specify a Dead Band value = 5 for a tag value = 50 and the tag value changes to 52, the system will not register this variation in the event log file, because the variation is less than 5. However, if the tag value change is equal to or greater than 5, the system will save the new value to the history file. Message column: Type a string (message) related to this tag change. You can specify tags in messages using the {tag name} syntax. The Tags parameter can be useful if you want to generate a log file of events that are not necessarily alarm conditions (for example, Motor On, Motor Off, and so forth).

InduSoft Web Studio

233

IWS Training Guide

Exercise: Configuring Event Retrieval

Notes

234

InduSoft Web Studio

Chapter 24.

Grid Object

The Grid Object allows you to view data in a tabular format on a Screen. Data contained in the Grid Object can be read from or written to several sources: Databases Supports relational databases using a built-in interface to ADO.NET providers Class Tags Text File Text files supported include CSV, Tab delimited, or other character delimited files Direct input The Grid Tool is located in the Active Objects toolbar. To insert a Grid Object onto a Screen, click on the Grid tool icon, place your mouse cursor on the Screen, then click and drag (while holding the left mouse button down). When you release the left mouse button, the Grid Object will be displayed on the Screen.

Grid Object To configure the Grid Object, position your mouse on the Grid Object and either double-click the left mouse button, or click the right mouse button, to a access the Object Properties dialog box.

Grid Object: Object Properties dialog box The first step in configuring the Grid Object is to select the Data Source type, using the combo box. The Data Source type options are: Text File Displays data from a Text file, in ASCII or Unicode format Class Tag Displays values from a Class Tag or Array of Class Tags. Each Class Member is a Field (column) of the Grid Object. Every Array index is one row in the Grid Object. Relational Databases Displays data from a relational database, using ADO

InduSoft Web Studio

241

IWS Training Guide

Exercise: Configuring Event Retrieval

Other settings in the Grid Object - Objects Properties Dialog Box are: E-Sign When checked, user will be prompted to enter an electronic signature before entering or modifying data in the Grid Object VK Selects a Virtual Keyboard. Can use the Default specified in the Project Desktop dialog box, or you can specify a specific VB to be used. Security Enter the security access level required for the Object & any Dynamic Property Disable You can enter an expression in this field (i.e. IWS Tag & expression) to disable data input and operation by the user. Highlight Color Specifies a background color for the selected row, during runtime Text Color Selects a color for the Text in the selected row, during runtime Win Color1 Selects a background color for the odd rows Win Color2 Selects a background color for the even rows Hint Displays a Hint when the mouse cursor passes over the Grid Object Settings Runtime

There are four (4) buttons in the middle of the Grid Object - Objects Properties Dialog Box. These are: Fonts When clicked, a Fonts dialog box opens that lets you specify the font settings for Text in the Grid Object Columns When clicked, a Columns dialog box opens that lets configure the Grid columns (e.g. a label, source of the column, type (text, numeric, etc.), column width, column alignment, input enabled/disabled, function key shortcut for sorting on the specified column). This dialog box will change somewhat, based on the Data Source type selected. Data When clicked, a Data dialog box opens that lets you specify the Data Source for the Grid Object. This dialog box will change, based on the Data Source type selected. Advanced When clicked, an Advanced Dialog box appears allowing you to specify advanced settings for the Grid Object.

242

InduSoft Web Studio

Exercise: Configuring Event Retrieval

IWS Training Guide

Columns Dialog
The Columns Dialog Box lets you configure the Grid Columns for the Data Source you have selected. The Columns Dialog Box is slightly different, based on the type of Data Source selected. The different dialog boxes are shown below.

Columns Dialog Box for Text Files

Columns Dialog Box for Class Tags

Columns Dialog Box for Databases Settings for the Columns are: Column The ID number used to define the position of the Column in the table. Note: To insert or delete a row in the Column Dialog Box, click the right mouse button on a field and select Insert Line, Delete Line, Cut, Copy, Paste, or Insert Copied Cells. The ID number will be automatically updated. Label Used to specify a Title for each column, displayed in the first row of the Grid Object.

Notes: A Tag (configured in curly braces) can be used in the Label field to modify during runtime If Label is blank (i.e. ), the width of the column is set to 0 during runtime. This will hide the column

InduSoft Web Studio

243

IWS Training Guide

Exercise: Configuring Event Retrieval

Member (used only for Class Tags) Specifies the Class Member to be used. Field (used only for Databases) Specifies the name of the Field (Column) in the Database that the Grid Object is linked to.

Notes: If the Field is left blank, the Text in the Label Field will be used as the Database Field Name You can configure a SQL Statement in the Field. You can also specify a string tag that contains a SQL Statement. Tags need to be configured between curly braces; e.g. {strTag}

Type A combo box that selects the type of interface that will be used in the column. The options are: Type Description Text Displays alphanumeric values Numeric Displays numeric values Picture Displays a picture from the data source (*.bmp or *.ico format). The picture will be automatically resized. CEView only supports *.ico format pictures. Check box Displays check box interface. If unchecked, value read from the file is 0, Null or False, otherwise the check box will be checked. Time Displays a time value in HH:MM:SS format. Only available when Data Source type is Database. Date Displays a date value in MM/DD/YY format. Only available when Data Source type is Database. Date/Time Displays a date and time value in MM/DD/YY HH:MM:SS format. Only available when Data Source type is Database.

Note: When using a database as the Data Source, be sure the Type for each column matches the type of the Field in the database. Otherwise, data may not be properly displayed. Width Specifies the Column width in pixels Align Aligns data in the Column. Options are Left, Right or Center Input When checked, allows the user to enter data in a Column at runtime.

Note: If the Data Source is a database or file, you will need to specify a Save trigger (e.g. a Tag) to save the changes in the Grid Object to the Data Source. Key Used to specify a shortcut key, or key combination, for sorting values in the Column. Show ID Column If checked, shows the ID (number of the row)

244

InduSoft Web Studio

Exercise: Configuring Event Retrieval

IWS Training Guide

Allow Sorting Columns If checked, allows sorting of Column values at runtime, either using the shortcut Key or clicking on the Label in the first Row Note: This option is disabled if the Show Header option (i.e. show the header row) is not checked. This option is located in the Advanced Dialog Box.

Move Up and Move Down Allows the reordering of display Columns

Note: When the Data Source type is set to Class Tag and the Columns dialog is left blank, the Grid Object displays the values from all Class Members of the Class Tag using the default Column settings: Label Name of Class Member Type Text Width Minimum size to display name of the Class Member Align Center Input Enabled (checked) Key None

InduSoft Web Studio

245

IWS Training Guide

Exercise: Configuring Event Retrieval

Data Dialog
The Data Dialog Box allows you to specify the Data Source for the Grid Object. The Data Dialog Box is different for each type of Data Source. The different dialog boxes are shown below.

Data Source = File Settings File Enter the file name or click the button to browse for the file. If the file is in the Application Folder, the Path can be eliminated. Note: File name can be a string Tag configured between curly braces. E.g. {strTag}

Delimiters. Specifies the delimiter(s) used in the Data Source file.

246

InduSoft Web Studio

Exercise: Configuring Event Retrieval

IWS Training Guide

Data Source = Class Tag Settings Class Tag Enter the name of the main Class Tag (or Array Class Tag) source.

Notes: Specify only the Class Tag name. Do not specify the Class Tag with a Class Member. If a Array Class Tag is used, the default index in the Array is 0. Another index can be specified. Number of Items Specifies the number of Array indexes from an Array Class Tag that will be displayed View Enter an IWS Tag into this field. When the Tag toggles (changes value), a dialog box will open (at runtime) that allows the user to show or hide each column or modify the Column position.

Data Source = Database Settings This option opens the familiar Database Configuration dialog box. See the Chapter on IWS Database Configuration for additional information on how to configure the Database.

Advanced Dialog
When the Advanced button is pressed, an Advanced Dialog Box appears allowing you to specify Advanced settings for the Grid Object.

The Advanced Dialog Box has several settings. These are: User Enable Enter a Tag or numeric value into this field. If True (<>0), the User can select different rows of the Grid Object (by clicking the left mouse button) at runtime, or entering a value in the Row Number field.

InduSoft Web Studio

247

IWS Training Guide

Exercise: Configuring Event Retrieval

Selected Values Enter an Array Tag (and any initial index if other than 0) into this Field. The Array Tag will receive values from each Column of the selected row. If the values of the Array Tag are changed, the cells in the Grid Object will be updated. Row Number Enter a Tag in this field. The Grid Object will return the number of the Row currently selected (at runtime), or the User can enter a positive numeric value to select a Row. Reload Enter a Tag in this field. When the tag toggles, the Grid Object reloads data from the Data Source specified. Condition This field can be used as a data filter expression (e.g. <Column Name> <operator> <value>, or ColumnX > 200) Notes: You can combine multiple conditions in the Condition field, using the same or different Columns. You can use wildcards (* and ?) in the Condition field You can use a string Tag configured between curly braces, {strTag}, to change filtering conditions during runtime. Column Name is the value specified in the Label field for Text File and Class Tag Data Sources Column Name is the value specifed in the Field field for Database Data Sources.

Print Enter a Tag in this field. When the Tag value toggles, the (filtered) data in the Grid Object is sent to the default Printer. Number of Rows Enter a Tag in this field. The Grid Object returns the number of Rows currently available in the Grid Object from the selected Data Source. Save Trigger Enter a Tag in this field. When the Tag value toggles, the data source (Text File or Database) is updated with the current values of the Grid Object. Not used when the data source is a Class Tag (which is automatically updated when a cell in the Grid Object changes value). Insert Trigger Enter a Tag in this field. If the Auto Refresh after Insert Trigger is check box is checked, when the Tag value toggles, the Database Table will be refreshed. A new row is added to the Table and values contained in the Array Tag configured in the Inserted Values field will be automatically inserted. Inserted Values Enter an Array Tag in this field. If the Tag in the Insert Trigger field is toggled, the values contained in the Array Tag will be inserted. Save on Data Change If checked, any change of values in the Grid Object will be updated to the Data Source (Text Files or Database only) during runtime. Not used when the data source is a Class Tag (which is automatically updated when a cell in the Grid Object changes value). Enable Slider/Resize If checked, allows a slider to scroll through the Grid Object table during runtime.

248

InduSoft Web Studio

Exercise: Configuring Event Retrieval

IWS Training Guide

Conditional Check Box If checked, the User cannot uncheck a check box used in the Grid Object during runtime unless all proceeding checkboxes in the same Column are already unchecked.

Notes: This option is useful to make a User follow a pre-defined sequence. This field is not available when the Data Source is a Class Tag.

Show Header When this option is checked, the header of the Grid Object will be shown at runtime. Show Grid Lines When this option is checked, the Grid Lines of the Grid Object will be shown at runtime. Ext. Translation When this option is checked, the text displayed by the Grid Object can be used by the Translation Tool during runtime to switch to a different language at runtime. Disable Tab to navigate through cells When this option is checked, the User cannot navigate through the cells using the Tab key. Only arrow keys can be used. Note: This option is used when the Tab key is used to navigate to other Objects (e.g. Text I/O) on the Screen

Export This interface allows you to export data from the Grid Object to a Class Array Tag, regardless of the Data Source type selected. You must configure the following fields: Class Tag Specifies the name of the Class Array Tag to be used. Each row of the Grid Object will be exported to one array index of the Class Array Tag. The initial array index can be specified, if it is not then a default value of 0 will be used. Trigger Enter a Tag into this field. When the Tag toggles (changes) value, the data in the Grid Object is exported to the Class Array Tag configured in the Class Tag field. Note: The Export feature is a easy and powerful tool to transfer data between a Data Source (e.g. Text File or Database) and an IWS Class Tag. The Grid Object can be hidden (using the visibility field of the Position Dynamic Property or setting the size to 0 using the Size Dynamic Property). Doing this allows you to take advantage of the Data Source to Class Tag Export feature while not occupying Screen space.

InduSoft Web Studio

249

IWS Training Guide

Exercise: Configuring Event Retrieval

2410

InduSoft Web Studio

Example: Using the Grid Object with Excel

IWS Training Guide

Example: Using the Grid Object with Excel


The Grid Object allows a InduSoft Web Studio (IWS) application to read from and write to database files, including an Excel file. The Grid Object is just one method of accessing an Excel file using IWS. While using a Grid Object with Excel is straightforward, it does require some care in properly setting up the database and making sure columns are of the same type. Notes: When using the Grid Object, make sure the Excel file exists in its specified location. rd rd If IWS and a 3 party program both are accessing the Excel database file at the same time and the 3 party program changes a value in the database, the changed cell is not updated in the Grid Object. The Grid Object will no longer update this cell for reading or writing purposes.

Example Database: Production Schedule.xls. This is an Excel database that contains a production build schedule that will be viewed by a Grid Object.

Column 1 [A] Column 2 [B] Column 3 [C] Column 4 [D] Column 5 [E] Column 6 [F] Column 7 [G]

heading: Production Date, format: mm/dd/yy heading Customer, format: text heading Product, format: text heading Order Quantity, format: numeric, no decimals heading Production Start, format: mm/dd/yy hh:mm:ss (custom) heading Quantity Built, format: numeric, no decimals heading Production End, format: mm/dd/yy hh:mm:ss (custom)

InduSoft Web Studio

2411

IWS Training Guide

Example: Using the Grid Object with Excel

The following steps will configure the database from the Grid Object. Step 1 Open the Indusoft Web Studio engineering environment and insert a grid object onto a display screen. First select (click) the Grid Object Tool and then place a Grid Object in the screen display worksheet. Dont worry about the size, it will be adjusted later.

Step 1a: Select Grid Object Tool

Step 1b: Position Grid Object on the screen

Step 2a: Double click the Grid Object.

Step 2 Double click on the Grid Object. In the Object Properties dialog box, select Database as the Data Source. Next, click on the Data button to get the Database Configuration dialog box. Make sure the database is set to primary and the Use application default box is unchecked.

Step 2b: Select Database as the Data Source

Step 2c: Click on Data button to configure the database Step 2d: Make sure the Use application default box is unchecked. Step 2e: Click on the browse button of the connection string

2412

InduSoft Web Studio

Example: Using the Grid Object with Excel

IWS Training Guide

Step 3 Once you click on the browse button of the connection string, you will be need to setup various parameters that define the link between IWS and the database. Note the tabs on top to access various setup parameters. The first step is to define the database Provider for Excel. In this case, Excel uses the Microsoft Jet database engine and OLE-DB is the Data Provider. Select Microsoft Jet 4.0 OLE DB Provider and click next.

Step 3: Select Microsoft Jet 4.0 OLE DB Provider. Then click next.

Step 4b: click on the browse button of the database name.

Step 4a: Define a user name and any password associated with the file. User name Admin with no password is the default.

Step 4 The next step is to define any user name and password associated with the file, then select the file that contains the database by clicking on the browse button. Step 5 Select the Excel file from the appropriate directory.
Step 5: Select your Excel database file from the appropriate directory. Click on the file name then click on Open.

Note Be sure to select All Files in the dropdown list of file types, otherwise only Microsoft Access files (*.MDB) will be shown

InduSoft Web Studio

2413

IWS Training Guide

Example: Using the Grid Object with Excel

After the file has been opened, the filename and path will be in the database name field. The length of this field will depend on the path name. Note Do not click on Test Connection at this time. There is one more step to be completed, then the Test Connection can be used. This can be done after step 6d.

Step 6 Click on the All tab in the Data Link Properties. This dialog box allows users to further define the JetOLE DB properties. The Extended Properties needs to be set to Excel 8.0, which supports the current version of Microsoft Excel 2003.
Step 6a: Click on All tab Step 6b: Click on Extended Properties

Step 6d: Enter Excel 8.0 and click OK

Step 6c: Click on the


Edit Value button

2414

InduSoft Web Studio

Example: Using the Grid Object with Excel

IWS Training Guide

Step 6e: The connection between IWS and the database is now complete. Now, you can either: a) Test the connection by ckicking on the Connection tab, then press the Test Connection button. Then, b) Click OK to finish setting up Data Link properties

Once Step 6e is completed, you have completed the data connection to the database. There is still one more step in the configuration, but the link to the database is complete. At this point, the connection string as shown in the Database Configuration dialog box (see dialog box under Step 2) will look something like this: Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\production schedule.xls; Extended Properties="Excel 8.0" The Data Source defines the path to your Excel database file, so this will vary according to the location of the files in your system. The file name can be defined using an IWS tag (type string) instead of a pre-defined path. This allows the IWS application to specify a file. [Check this, what happens if change] The tag name must be enclosed in braces, i.e. {tag}. The Extended Property value that was set to Excel 8.0 allows access to Excel 2000, 2002 and 2003 files. The default is to have the first row in the Excel spreadsheet as a header row. If you do not want the first row to be a header row, you need to put Excel 8.0;hdr=no into the Extended Properties field. The resultant connection string would appear similar to: Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\production schedule.xls; Extended Properties="Excel 8.0; hdr=no"

Note: The file name or entire path can be predefined or be an IWS tag

InduSoft Web Studio

2415

IWS Training Guide

Example: Using the Grid Object with Excel

Step 7 The final step in setting up the database interface for the Grid Object is to specify the Worksheet inside of the Excel database that is to be used.

Step 7a: Enter the Worksheet name in


the Excel database. Follow the example shown, i.e. the worksheet name is followed by a $, and the name with the $ is enclosed in square brackets. If you do not follow this format, you will get an error when accessing the Excel database.

As mentioned in Step 6, you can used IWS tags (type string) to define the Excel Worksheet. If you plan to do this, be sure to enclose the tag name in curly braces, i.e. {tag}.

Next Steps The next steps involve setting up the Columns and any Advanced Settings. See previous section.

2416

InduSoft Web Studio

Example: Using the Grid Object with Excel

IWS Training Guide

Notes

InduSoft Web Studio

2417

Chapter 25.

VBScript

Visual Basic Script Language (VBScript) is one of Microsofts scripting languages that is commonly associated with Server-side and Client-side web applications. However, Microsoft has opened up VBScript to developers and now VBScript can be found in a variety of applications. InduSoft has standardized on VBScript since it provides a significant subset of Microsoft Visual Basics functionality, and VBScript supports all of Microsofts operating system platforms including Windows CE, unlike VBA (Visual Basic for Applications) which cannot support the Windows CE runtime environment. VBScript is a programming language that is often viewed as a dialect of VBA (Visual Basic for Applications), although it is really its own language. The VBScript language attempts to balance flexibility, capability and ease of use. VBA is a subset of Visual Basic that was developed to automate Microsoft Office applications, whereas VBScript was originally developed to support Server-side and Client-side web applications. Although VBScript and VBA provide many of the same features, there are some differences between them, primarily due to the applications they were each developed to support. Using VBScript With InduSoft HMI/SCADA Applications InduSoft Web Studio (IWS) supports both the IWS Scripting Language (proprietary Scripting Language) using one or more Math worksheets, as well as VBScript (IWS Version 6.1 or later). Developers can use either scripting language or a combination of both. VBScript code is placed in one of several modules, based on the functionality to be performed and the scope of the code and its variables. This subject is covered more completely in the VBScript Configuration and Operation in IWS section. Examples of how VBScript can be used: Execute a logic sequence or routine when opening or closing a screen, or while the screen is open Execute a logic sequence in the background Run a simple VBScipt code segment based on an IWS objects command dynamic Interaction with IWS Tags and control of IWS built-in functions Manipulation of ActiveX Controls and ActiveX Control event handler Simple file I/O (e.g. text files) Database interfaces (e.g. via ADO.NET), especially where use of SQL is required Interface to Windows Management Instrumentation (WMI) and Web Services (via WSDL) Interface to Microsoft Office applications (e.g. Excel, Access, Word) and Microsoft Office components via OLE Automation Run on a Web Thin Client Where you should use IWS instead of VBScript User Interface. IWS does not support Windows Scripting, which typically provides the User Interface for VBScript via Forms. Device I/O (e.g. PLC communications). VBScript does not directly support serial or network communications. However, ActiveX Controls can be used.

IWS implements Visual Basic Script Edition 5.6 or higher, and functions as the host for VBScript. IWS provides an integrated development environment where the HMI/SCADA application developer can take advantage of the functionality and ease of use of VBScript, yet have access to all IWS tags and all built-in functions directly from VBScript. The diagram below illustrates the IWS architecture. Since VBScript is an interpreted language, the VBScript Engine parses the language at runtime and executes commands subject to

InduSoft Web Studio

251

IWS Training Guide

VBScript Limitations in IWS

limitations placed by the VBScript Host. InduSoft allows VBScript code to be located several areas in an IWS application: Global Procedures. This is an area for subroutines and functions that can be called by any other VBScript routine, or by a built-in IWS function (requires IWS Version 6.1 Service Pack 1 or later). Graphic Script. Code in this area gets executed whenever any graphics (screens) are active. Screen Script. This is where code is executed when an individual screen is active. Command Dynamic. When an object has a Command Dynamic, one option is to run VBScript code. ActiveX Events. A VBScript code segment can be run based on an ActiveX event Background Task. VBScript code can be running as a background task. One or more VBScript groups are supported, allowing conditional processing of the various VBScript background tasks. In a Web Thin Client configuration, VBScripts associated with a screen can run either on the workstation runtime display or on a Web Thin Client station running Microsoft Internet Explorer. The VBScript routines that can execute on a Web Thin Client include those located in a Screen Script, a Command Dynamic, and an ActiveX Event. Since VBScript runs on all Microsoft operating system platforms, there are no limitations to VBScript running on any Microsoft compatible platform.

VBScript Limitations in IWS


Microsoft initially developed VBScript to work with websites (web pages). In the web server environment, VBScript was designed to work with the Windows Scripting host and ASP, which provide file access and form generation. On the web client side, VBScript was designed to work with Microsoft Internet Explorer using HTML and DHTML, which provide display generation. So as a result of the initial design goals, VBScript does not have much in the way of built-in language support for Forms, File I/O, Communications or direct Printing control. Additionally, IWS has its own built-in web server and does not use ASP. By using IWS built-in functions, ActiveX controls and Microsoft Office Applications (or components), there are several methods for workarounds to these limitations as well as to extend VBScripts capability. The following are some of VBScripts limitations and workarounds.

Item
Forms

VBScript
Does not support

Workarounds
Use IWS objects for user interface, pass parameters to IWS. Can also use ActiveX Controls. Use Scripting Objects and/or IWS built-in functions. Can also use ActiveX Controls. rd Use IWS built-in functions or 3 party ActiveX controls Use Microsoft Office Applications or IWS built-in functions Use IWS trending, Microsoft Office Applications, rd Microsoft Office Components, or 3 party ActiveX controls Supported in IWS built-in commands (not under Windows CE).

File I/O Communications Printing Charting/Graphing

Limited support directly Does not directly support Does not directly support Does not directly support

DDE

Does not support

252

InduSoft Web Studio

Differences between VBScript and VBA

IWS Training Guide

Differences between VBScript and VBA


Since other HMI/SCADA products support VBA, it might be worth highlighting some of the key differences between VBScript and VBA. For HMI/SCADA applications, these differences are relatively minor. However, VBScript support for the Windows CE operating system is a major differentiator between the two products. For additional details or a complete listing of the differences, please reference the MSDN website at http://msdn.microsoft.com. Key differences between VBScript vs. VBA VBA VBScript Automation of MS Office Automation of Web Services Applications No Yes Stronger Type Declaration. Many Typeless, uses Variant Type. The final data types supported. (e.g. String, data subtype will be determined at Integer, Date, Boolean) runtime based on use. Supports same data subtypes as VBA and VB (e.g. String, Integer, Date, Boolean, etc) Dim Var as Type Dim Var (Cannot specify Type, but it is determined at runtime based on use) Must use separate Class Module Class Block Declaration supported Clipboard Not supported Collection TypeOf Not supported Not supported Expression evaluation supported Not supported Allows interpreted code to be executed on the fly. No Allows creation of regular expressions Several different types Supported but more limited Lower bound can be <>0 Lower bound is 0 Supported Not directly supported but VBScript can use FileSystemObject and can access IWS built-in I/O functions Supported Not supported Supported Not supported Fixed length strings Variable length only Debug, Print, End, Stop Use MsgBox or IWS built-in functions Supported Not supported

Item Primary Purpose Support for Windows CE Data Types

Dimension Statement

Class Block declaration Object Object Manipulation Eval function Execute function RegExp Error Handling Arrays File I/O

DDE Financial functions Strings Debugging Line labels

InduSoft Web Studio

253

IWS Training Guide

VBScript Language Overview

VBScript Language Overview


This section contains a short summary of the VBScript Language. A more complete reference of the VBScript language can be found in VBScript Reference Manual.

VBScript Functionality
VBScript has inherited much of VB & VBAs functionality including support for math operations, string manipulation, arrays, flow control, data conversion, procedures, COM objects, and date/time functions. Since VBScript was initially designed for Web applications, direct support for file I/O and user interface functions was not included. However, in a Windows XP/2000/NT/Server 2003/Vista environment, VBScript can use the FileSystemObject COM object (scrrun.dll) to manipulate local files and folders. VBScript does not support explicitly declared data types. This was eliminated to speed up the runtime performance of the VBScript Scripting Engine. All variables are type Variant and their subtype (e.g. Integer, Real, etc.) is determined at runtime.

VBScript Elements
There are several VBScript elements, but the most important ones are variables, constants and types. A variable is an item holding data that can change during the execution of the VBScript program. A constant is an item that holds data but cannot change during the execution of the VBScript program. The data that variables and constants hold can be classified into types. Note that with IWS, you can check the VBScript syntax for errors by choosing the Check VBScript command (right mouse click when in a VBScript interface). VBScript is always checked when saving the Script interface.

The Check Script function can be invoked following a right mouse click when the cursor is on the VBScript Interface. Note that Comments are in Green, VBScript Functions and KeyWords are in Blue, Variables are in Black

The VBScript elements include: Variables (Type, Declaration, Scope) Constants (Explicit, Implicit) Keywords Errors (Runtime, Syntax) Operators Functions and Procedures Statements Objects and Collections

254

InduSoft Web Studio

Variable Data Types and Subtypes

IWS Training Guide

Variable Data Types and Subtypes


All variables in VBScript are a data type called Variant. This means that you do not (and cannot) explicitly declare the variable type. In fact, with VBScript you do not need the Dim statement to allocate storage for a variable. At runtime, the Parser in the VBScript Scripting Engine determines the Variant data subtype to be used. These correspond to the more traditional classifications of data types (see chart below). Variant data subtypes Subtype Description Either True or False Boolean Byte Contains integer in the range 0 to 255 Currency Floating-point number in the range -922,337,203,685,477.5808 to 922,337,203,685,477.5807 Date(Time) Contains a number that represents a date between January 1, 100 to December 31, 9999 Double Contains a double-precision, floating-point number in the range -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values Empty Uninitialized Variant Error Contains an error number used with runtime errors Integer Contains integer in the range -32,768 to 32,767 Long Contains integer in the range -2,147,483,648 to 2,147,483,647 Null A variant containing no valid data Object Contains an object reference Single Contains a single-precision, floating-point number in the range -3.402823E38 to 1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values String Contains a variable-length string that can be up to approximately 2 billion characters in length. The Parsers choice of data subtype will depend on how the variable is used in a statement or function. Note that a variables subtype can change within a code segment.

Data Subtype Identification


If it is important to determine the Variant data subtype used at runtime, you may use any of the three categories of functions to determine the data subtype: The VarType(variable) function which returns a code based on the Variant data subtype used Various IsXxxx(variable) functions which return boolean values indicating whether the variable is of a specific data subtype. A TypeName(variable) function which returns a string based indicating the data subtype Example: If varType(a) = vbInteger Then Msgbox a is an Integer EndIf

InduSoft Web Studio

255

IWS Training Guide

Data Subtype Conversion

Data Subtype Conversion


VBScript provides several functions that convert a variable from one data subtype to another. Since VBScript uses the Variant data type, these functions are not generally required. However, when passing data between IWS (or CEView) and VBScipt, or calling built-in IWS functions from VBScript where variables need to be put into the proper argument format, these VBScript data subtype conversion functions can be very useful. Example: a = 4.2 b = cInt (a) b is an Integer with a value of 4

Variable Naming Rules & Conventions


VBScript has four primary rules for naming. These are: 1. Variable names must begin with an alpha character (a..z, A...Z) or an underscore character 2. After the first character, the variable name can contain letters, digits and underscores 3. Variable names must be less than 255 characters in length 4. The variable name must be unique in the scope in which they are declared VBScript variable names are not case sensitive. Microsoft recommends following their naming convention for variables, which puts attaches different prefixes to the variable name based on the data subtype.

Variable Scope
Variables have scope which defines a variables visibility or accessibility from one procedure (or VBScript Interface) to another, which is principally determined by where you declare the variable. Generally, when you declare a variable within a procedure, only code within that procedure can access or change the value of that variable. This is called local scope and is for a procedure-level variable. If you declare a variable outside a procedure, you make it recognizable to all the procedures in your Script. This is a Script-level variable, and it has Script-level scope. However, as previously noted, InduSoft enforces certain restrictions on the scope of Variables and Procedures.

256

InduSoft Web Studio

VBScript Constants

IWS Training Guide

VBScript Constants
VBScript supports both explicit and implicit constants. Constants should never be used as variable names. Explicit constants are defined by the programmer. Explicit constants have a defined value which, unlike a variable, is not allowed to change during the life of the script. Implicit constants are pre-defined by VBScript. VBScript implicit constants usually begin with a vb prefix. VBScript implicit constants are available to the VBScript programmer without having to define them. Other objects, such as those used by ADO.NET, also have implicit constants predefined, usually with different prefixes. However, the implicit constants for these objects may not be know to VBScript and if not, will have to be defined as an explicit constant. VBScript defines the following categories of implicit Constants: Intrinsic Constant Category Color Constants Comparison Constants Date and Time Constants Date Format Constants Days of Week Constants New Years Week Constants Error Constants VBScript Runtime Errors VBScript Syntax Errors Intrinsic Constant Category File Attribute Constants File Input/Output Constants MsgBox Constants MsgBox Function Constants SpecialFolder Constants String Constants Tristate Constants VarType Constants Locale ID (LCID)

Declaring VBScript Variables and Constants


VBScript does not require the explicit declaration of scalar variables, i.e. those variables with only one value assigned at any given time. Arrays, Objects (except Err) and Constants must be declared. While it may initially be convenient not to declare variables, any typing (spelling) errors of the variable or constant names may produce unexpected results at runtime.

VBScript Keywords
VBScript has many keywords. Keywords are merely the names or symbols used with built-in VBScript functions. Keywords are reserved, i.e. they may not be used by the programmer as names of variables or constants. VBScript keywords can be grouped into categories which include: Constants & Literals Operators Functions Statements Objects

InduSoft Web Studio

257

IWS Training Guide

Operators

Operators
VBScript defines various operators that perform operations based on the Variant subdata type(s). Arithmetic operators are used to perform operations on two or more numbers.

Arithmetic
Symbol + * / \ ^ MOD Definition Add Subtract Multiply Divide Integer Divide Exponentiation Modulus Division

Comparison
Symbol < <= > >= = <> Definition Less than Less than or equal Greater than Greater than or equal Equal or assignment Not equal

Logical
Symbol AND OR, | XOR Eqv Imp Not Definition And Or Exclusive OR Equivalence Implication NOT

String
Symbol &, + Definition Concatenation

Object
Symbol Is Definition Is (compare)

IWS
Symbol $ Definition Access to IWS Tags and Built-in functions

258

InduSoft Web Studio

Operator Precedence

IWS Training Guide

Operator Precedence
When several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator precedence. Parentheses can be used to override the order of precedence and force some parts of an expression to be evaluated before other parts. Operations within parentheses are always performed before those outside. Within parentheses, however, normal operator precedence is maintained. When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last. Comparison operators all have equal precedence; that is, they are evaluated in the left-to-right order in which they appear. Arithmetic and logical operators are evaluated in the following order of precedence: When multiplication and division occur together in an expression, each operation is evaluated as it occurs from left to right. Likewise, when addition and subtraction occur together in an expression, each operation is evaluated in order of appearance from left to right. The string concatenation operator (&) is not an arithmetic operator, but its precedence does fall in after all arithmetic operators and before all comparison operators. The Is operator is an object reference comparison operator. It does not compare objects or their values; it only checks to determine if two object references refer to the same object. Operator Precedence Arithmetic Negation (-) Exponentiation (^) Multiplication and division (*, /) Integer division (\) Modulus arithmetic (Mod) Addition and subtraction (+, -) String concatenation (&, +)

Comparison Equality (=) Inequality (<>) Less than (<) Greater than (>) Less than or equal to (<=) Greater than or equal to (>=) Is

Logical Not And Or Xor Eqv Imp &

InduSoft Web Studio

259

IWS Training Guide

Functions

Functions
VBScript contains a number of built-in functions (not to be confused with the Function Procedure). These functions may or may not have arguments. These functions are called in a statement and may return a result that can be assigned to a variable. VBScripts functions are grouped as follows: Array Functions Array Functions Array Filter IsArray Join LBound Split UBound Description Returns a variant containing an array Returns a zero-based array that contains a subset of a string array based on a filter criteria Returns a Boolean value that indicates whether a specified variable is an array Returns a string that consists of a number of substrings in an array Returns the smallest subscript for the indicated dimension of an array Returns a zero-based, one-dimensional array that contains a specified number of substrings Returns the largest subscript for the indicated dimension of an array

Data Conversion Functions Function Description Abs Returns the absolute value of a specified number Asc Converts the first letter in a string to its ASCII decimal representation CBool Converts an expression to a variant of subtype Boolean CByte Converts an expression to a variant of subtype Byte CCur Converts an expression to a variant of subtype Currency CDate Converts a valid date and time expression to the variant of subtype Date CDbl Converts an expression to a variant of subtype Double Chr Converts the specified ANSI code to a character CInt Converts an expression to a variant of subtype Integer CLng Converts an expression to a variant of subtype Long CSng Converts an expression to a variant of subtype Single CStr Converts an expression to a variant of subtype String Fix Returns the integer part of a specified number Hex Returns the hexadecimal value of a specified number Int Returns the integer part of a specified number Oct Returns the octal value of a specified number Round Returns a rounded number Sgn Returns the integer portion of a number

2510

InduSoft Web Studio

Functions

IWS Training Guide

Date and Time Functions Function Description CDate Converts a valid date and time expression to the variant of subtype Date Date Returns the current system date DateAdd Returns a date to which a specified time interval has been added DateDiff Returns the number of intervals between two dates DatePart Returns the specified part of a given date DateSerial Returns the date for a specified year, month, and day DateValue Returns a date Day Returns a number that represents the day of the month (between 1 and 31, inclusive) FormatDateTime Returns an expression formatted as a date or time Hour Returns a number that represents the hour of the day (between 0 and 23, inclusive) IsDate Returns a Boolean value that indicates if the evaluated expression can be converted to a date Minute Returns a number that represents the minute of the hour (between 0 and 59, inclusive) Month Returns a number that represents the month of the year (between 1 and 12, inclusive) MonthName Returns the name of a specified month Now Returns the current system date and time Second Returns a number that represents the second of the minute (between 0 and 59, inclusive) Time Returns the current system time Timer Returns the number of seconds since 12:00 AM TimeSerial Returns the time for a specific hour, minute, and second TimeValue Returns a time Weekday Returns a number that represents the day of the week (between 1 and 7, inclusive) WeekdayName Returns the weekday name of a specified day of the week Year Returns a number that represents the year

Expression Functions Expressions Description Eval Evaluates an expression and returns the result RegExp Provides simple regular expression support.

Format Functions Function FormatCurrency FormatDateTime FormatNumber FormatPercent

Description Returns an expression formatted as a currency value Returns an expression formatted as a date or time Returns an expression formatted as a number Returns an expression formatted as a percentage

I/O Functions Input/Output InputBox MsgBox LoadPicture

Description Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns the contents of the text box. Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked. Returns a picture object

InduSoft Web Studio

2511

IWS Training Guide

Functions

Math Functions Function Description Abs Returns the absolute value of a specified number Atn Returns the arctangent of a specified number Cos Returns the cosine of a specified number (angle) Exp Returns e raised to a power Hex Returns the hexadecimal value of a specified number Int Returns the integer part of a specified number Fix Returns the integer part of a specified number Log Returns the natural logarithm of a specified number Oct Returns the octal value of a specified number Randomize Initializes the random-number generator Rnd Returns a random number less than 1 but greater or equal to 0 Sgn Returns an integer that indicates the sign of a specified number Sin Returns the sine of a specified number (angle) Sqr Returns the square root of a specified number Tan Returns the tangent of a specified number (angle)

Miscellaneous Functions Miscellaneous Description GetLocale Returns the current locale ID RGB Returns a whole number representing an RGB color value SetLocale Sets the current locale ID

Script Engine Functions Script Engine ID ScriptEngine ScriptEngineBuildVersion ScriptEngineMajorVersion ScriptEngineMinorVersion

Description Returns a string representing the scripting language in use Returns the build version number of the scripting engine in use Returns the major version number of the scripting engine in use Returns the minor version number of the scripting engine in use

String Functions Function Description InStr Returns the position of the first occurrence of one string within another. The search begins at the first character of the string InStrRev Returns the position of the first occurrence of one string within another. The search begins at the last character of the string LCase Converts a specified string to lowercase Left Returns a specified number of characters from the left side of a string Len Returns the number of characters in a string LTrim Removes spaces on the left side of a string Mid Returns a specified number of characters from a string Replace Replaces a specified part of a string with another string a specified number of times Right Returns a specified number of characters from the right side of a string RTrim Removes spaces on the right side of a string Space Returns a string that consists of a specified number of spaces StrComp Compares two strings and returns a value that represents the result of the comparison String Returns a string that contains a repeating character of a specified length StrReverse Reverses a string Trim Removes spaces on both the left and the right side of a string UCase Converts a specified string to uppercase

2512

InduSoft Web Studio

Functions

IWS Training Guide

Variant Identification Functions Variant Description Function IsArray Returns a Boolean value indicating whether a variable is an array IsDate Returns a Boolean value indicating whether an expression can be converted to a date IsEmpty Returns a Boolean value indicating whether a variable has been initialized. IsNull Returns a Boolean value that indicates whether an expression contains no valid data (Null). IsNumeric Returns a Boolean value indicating whether an expression can be evaluated as a number IsObject Returns a Boolean value indicating whether an expression refers to a valid Automation object. TypeName Returns a string that provides Variant subtype information about a variable VarType Returns a value indicating the subtype of a variable

InduSoft Web Studio

2513

IWS Training Guide

Statements

Statements
VBScript statements are used to perform fundamental operations such as decision making, repetition (looping) and assignments. Statements combined with Operators are the building blocks for more complex code. Multiple statements can appear on the same line as long as they are separated by a colon (:). For purposes of code readability, it is recommended to use one statement per line.

Assignment Statements
Many of VBScripts assignment statements have already been covered. For consistency purposes, they are listed here. Refer to the VBScript Users Manual for a more detailed description of their use. Assignment Statements Statement Description Const Declares constants for use in place of literal values Dim Declares variables and allocates storage space Erase Reinitializes the elements of fixed-size arrays, deallocates dynamic-array storage space. Option Explicit Forces explicit declaration of all variables in the script Private Declares private variables and allocates storage space Public Declares public variables and allocates storage space ReDim Declare dynamic array variables, allocates or reallocates storage space at procedural level

Comment Statements
Comment statements are used to provide documentation comments with the code. Comment Statements Comments Description Rem Includes explanatory remarks in a program Includes explanatory remarks in a program (single quote)

2514

InduSoft Web Studio

Statements

IWS Training Guide

Control Flow Statements


By default, VBScript sequentially moves (flows) through the script from statement to statement. As is typical with virtually all high-level programming languages, control flow statements can alter this flow by branching to other code sections based upon logic conditions, inputs, errors, etc. One of the most commonly used control flow statement is the If..Then..Else statement. This control flow statement takes the following format: {simple format} {block format} If condition Then [statement(s)] [ElseIf condition-n Then [elseifstatement(s)]] . . . [Else [elsestatement(s)]] End If The condition can be a boolean constant or boolean variable, or a numeric or string expression that evaluates to True or False. Refer to the Appendix for a detail description of these functions. Control Flow Statements Function Description DoLoop Repeats a block of statements while a condition is True or until a condition becomes True Execute Executes one or more specified statements Execute Global Executes one or more specified statements in the global namespace of a script Exit Do Exit a Do Loop Function. Transfers control to the statement following the Loop statement. Exit For Exit a For Loop Function (ForNext or For EachNext loop). Transfers control to the statement following the Next statement. For...Next Repeats a group of statements a specified number of times For EachNext Repeats a group of statements for each element in an array or collection IfThenElse Conditionally executes a group of statements, depending on the value of an expression Select Case Executes one of several groups of statements, depending on the value of an expression WhileWend Executes a series of statements as long as a given condition is True WithEnd Executes a series of statements on a single object With If condition Then statement(s) [Else elsestatement(s) ]

InduSoft Web Studio

2515

IWS Training Guide

Statements

Procedure Statements
There are two types of procedure statements; the Sub procedure and the Function procedure. Both of these procedure statements are intended to encapsulate a set of statements that provide functionality that can be repeatedly called, but the difference between the two is how arguments are passed and results returned. The Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub statements) that perform actions but don't return a value as part of the Sub name. A Sub procedure can take arguments (constants, variables, or expressions that are passed by a calling procedure). A resultant value or set of values can be returned through the arguments. If a Sub procedure has no arguments, its Sub statement must include an empty set of parentheses (). The Function procedure is a series of VBScript statements enclosed by the Function and End Function statements. A Function procedure is similar to a Sub procedure, but can also return a value in the Function name. A Function procedure can take arguments (constants, variables, or expressions that are passed to it by a calling procedure). If a Function procedure has no arguments, its Function statement must include an empty set of parentheses. A Function returns a value by assigning a value to its name in one or more statements of the procedure. The return type of a Function is always a Variant. Procedure Statements Function Description Call Transfers control to a Sub or Function procedure End Function Immediately exits a Function procedure End Sub Immediately exits a Sub procedure Exit Function Exit a Function, generally as a result of a condition Exit Sub Exit a Subroutine, generally as a result of a condition Function Declares the name, arguments, and code that form the body of a Function procedure GetRef Associates an event handler with a specific function Sub Declares the name, arguments, and code that form the body of a Sub procedure (Subroutine).

2516

InduSoft Web Studio

VBScript Object Commands

IWS Training Guide

VBScript Object Commands


VBScript includes several Functions and Statements that can be used to access objects, including their methods and properties. There are a large variety of objects available to VBScript, including user-defined objects, intrinsic objects and extrinsic objects. VBScript Object Functions Function Description CreateObject Creates and returns a reference to an Automation object GetObject Returns a reference to an Automation object from a file IsObject Returns a Boolean value indicating whether an expression references a valid Automation object. Object Statements Statement Description Class Declares the name of a class, as well as a definition of the variables, properties, and methods that comprise the class Exit Property Forces an exit from inside a Property Set function. For EachNext Repeats a group of statements for each element in an array or a collection. Declares, in a Class block, the name, arguments, and code that form the body of Property Get a Property procedure that gets (returns) the value of a property Declares, in a Class block, the name, arguments, and code that form the body of Property Let a Property procedure that assigns (sets) the value of a property Property Set Sets a reference to an object Set Assigns an object reference to a variable or property, or associates a procedure reference with an event. Usually used to instantiate an object. Error Handling Statements Statement Description On Error Enables or disables error-handling

Object & Collection Summary Objects & Collections Description The Debug object is an intrinsic global object that can send an output to Debug a script debugger, such as the Microsoft Script Debugger. An associative array that can store any type of data. Data is accessed Dictionary by a key. Drive An object that refers to a specific Drive Drives A collection of Drive objects. Contains information about the last run-time error. Accepts the Raise Err and Clear methods for generating and clearing run-time errors. File An object that refers to a specific File Files A collection of File objects. FileSystemObject An object model used to access the Windows file system Folder An object that refers to a specific Folder Folders A collection of Folder objects. Provides access to the read-only properties of a regular expression Match match. Matches Collection of regular expression Match objects. RegExp Provides simple regular expression support. Submatches A collection of regular expression submatch strings. TextStream An object that refers to a text File

InduSoft Web Studio

2517

IWS Training Guide

VBScript User-Defined Class Objects

VBScript User-Defined Class Objects


To define a user-defined Class Object, you use the Class statement to declare a class. The End Class statement defines the termination of the Class. Together, these statements form a Class construct, or Class block. E.g. Class objName Place the Class variables, Properties and Methods here End Class In this syntax, objName is the name given to the Class Object. The class object name must follow standard VBScript variable naming conventions. Class Objects are usually declared in the variable definition sections. You can have multiple Class blocks in a single VBScript file, but each block must contain the Class End Class statements. Classes cannot be nested. Once you have defined the Class Object, you need to create an instance of the Class, similar to how other objects are created. When the Class Object is instantiated, memory is allocated for the Class Object. The Set statement is used with the New keyword to assign an instance of the class to a variable. With VBScript, this is the only time the New keyword is used (i.e. to instantiate a user-defined Class). E.g. Dim MyObj Set MyObj = New objName The Object name MyObj is the Object variable name, and must follow standard VBScript variable naming conventions. The Object variable name is a reference (address) of the Object stored in memory, it is not the Object itself. Inside the Class block, any Class variables, Properties, Methods and Events can be defined by the developer. The developer does not have to use all of the capabilities of the Class construct, i.e. Classes can be created without Methods or Properties. The design of the Class Object is completely up to the developer. Class variables are created within the Class structure by using the Dim, Public, or Private statements. Variables defined within the Class structure by any of these statements must follow the standard VBScript variable naming conventions. Variables can be simple variables or arrays. E.g. Class className Dim var1, var2 Public var3, var4 Private var5, var6 End Class The choice of the Dim, Public, or Private statements determine whether the variable is accessible outside of the Class Object. Variables are public by default, i.e. they are accessible outside of the Class Object. Both the Dim and the Public statements create public variables, while the Private statement creates variables that are not public. As a general rule, it is good programming practice to make all Class variables private, since the developer will want to tightly control when these variables are changed. VBScript does not support Class-level Constants, i.e. named constants declared at the Class level. You cannot use the Const statement at the Class-level so that a constant can be used throughout a Class, but you can use the Const statement within a Property or Method. However, the constant will only have local scope within the Property or Method. Class Object variables are accessible to VBScript code outside the Class through Class Properties. Class Properties wrap the Private variables of a Class. Inside the Class block, the Properties are defined by Property Get [|Let|Set] End Property statement(s). For VBScript code outside the Class, the Property is accessed by referencing the Object Name.Property. There are different type of Class Properties, depending on whether the Class variable is to be read, written to, or the Class variable is itself a Class Object. These Properties can be declared Public or Private.

2518

InduSoft Web Studio

VBScript User-Defined Class Objects

IWS Training Guide

Property Get The Property Get procedure is used to access (return) private variables inside of the Class structure that are used as a read-only Property, or the read portion of a read-write Property. For VBScript code outside the Class, this type of Class Object Property is generally assigned to a variable or used in a conditional expression. The Property Get procedure returns a value to the calling code, and is general not used with any arguments. [Note: VBScript will let you add arguments to the Property Get procedure, but if you do so you must add the additional argument to the corresponding Property Let or Property Set procedure, since Property Let/Property Set must have one more argument than the corresponding Property Get procedure. It is generally considered bad programming form to have arguments in the Property Get procedure]. Property Let The Property Let procedure is used to access (assign) private variables inside of the Class structure that are used as a write-only Property or are the write portion of a read-write Property. For VBScript code outside of the Class, this type of Class Object Property is usually assigned by a variable or a constant. Property Set The Property Set procedure is exclusively used when the Class Object needs to store Properties that are object-based instead of numeric, date, boolean or string subtype variables. Property Set replaces the Property Let procedure. While Property Set and Property Let are functionally similar, there are two key differences: 1. With the Property Set procedure, in the VBScript code segment (outside the Class block) you must use the syntax Set Object1.Property = Object2 This is because VBScript does not let you use the assignment operator (=) to assign objects without the Set command. 2. The Property Set procedure makes it clear that the Property is an object-based Property Example: Class FileSpec Define a Class block Private master_file Private master_FSO Public Property Let FileName(strName) Define a Public Property to assign the file name master_file = strName End Property Public Property Get FileName Define a Public Property to retrieve a file name FileName = master_file End Property Public Property Set FSO(m_FSO) Define a Public Property for an object Set master_FSO = m_FSO End Property End Class Rem Below is the VBScript code Dim objFSO Declare variables and objects Dim objFilePointer, cur_file Set objFSO = CreateObject(Scripting.FileSystemObject) Instantiate the COM object Set objFilePointer = New FileSpec Instantiate the Class Object objFilePointer.FileName = Myfile.mdb Assigns Myfile.mdb as the file name cur_file = objFilePointer.FileName Retrieves the current file name Myfile.MDB Set objFilePointer.FSO = objFso Assigns an Object to the Property Set objFilePointer = Nothing Keyword Nothing releases the object memory

InduSoft Web Studio

2519

IWS Training Guide

VBScript User-Defined Class Objects

A couple notes on the example above. The CreateObject command is used to instantiate an Object that is known at the system level (e.g. a COM object). Also, so far this example only shows how to assign and retrieve property values. It is generally the Method(s) that control the action an object performs, not the properties. A Property can be made read-only by only providing a Property Get procedure, or by declaring the Property Let procedure as Private instead of Public. A Property can be made write-only by only providing the Property Let procedure, or by declaring the Property Get procedure as Private instead of Public. Class Methods are really just Functions and Subroutines inside of a Class block. These functions and subroutines can be either Private or Public. If they are public, they will be accessible to a VBScript code segment outside of the Class block by referencing the obj.Method. If they are private, they will only be available to code within the Class block.

An example of Class Methods is as follows:


Class FileSpec Private master_file Private master_FSO Private master_file Private Sub Class_Initialize Class Object initialization code code goes here End Sub Private Sub Class_Terminate Class Object termination code code goes here End Sub Public Property Let FileName(strName) Define a Public Property to assign the file name master_file = strName End Property Public Property Get FileName Define a Public Property to retrieve a file name FileName = master_file End Property Public Property Set FSO(m_FSO) Define a Public Property for an object Set master_FSO = m_FSO End Property Public Sub Delete Method to delete the master file master_FSO.DeleteFile (master_file) End Sub End Class Rem Below is the VBScript code Dim objFSO Declare variables and objects Dim objFilePointer, cur_file Set objFSO = CreateObject(Scripting.FileSystemObject) Instantiate the COM object Set objFilePointer = New FileSpec Instantiate the Class Object objFilePointer.FileName = Myfile.mdb Assigns Myfile.mdb as the file name cur_file = objFilePointer.FileName Retrieves the current file name Myfile.MDB Set objFilePointer.FSO = objFSO Assigns an Object to the Property objFilePointer.Delete Executes a Method to delete a file Set objFilePointer = Nothing Keyword Nothing releases the object memory VBScript Class Objects automatically supports two type of Class Events; Class_Initialize and Class_Terminate Events. The code inside the Class_Initialize event executes once when an Object based on the Class is first instantiated. Any code put in this event is optional, and is typically used for initialization. Code inside the Class_Terminate event executes once just before the Object based on the Class is destroyed (i.e. Set to Nothing, or the Object goes out of scope). Usage is as follows: Class FileSpec Private master_file Private master_FSO Private master_file Private Sub Class_Initialize Class Object initialization code

2520

InduSoft Web Studio

VBScript User-Defined Class Objects

IWS Training Guide

code goes here End Sub Private Sub Class_Terminate Class Object termination code code goes here End Sub Public Property Let FileName(strName) Define a Public Property to assign the file name master_file = strName End Property Public Property Get FileName Define a Public Property to retrieve a file name FileName = master_file End Property Public Property Set FSO(m_FSO) Define a Public Property for an object Set master_FSO = m_FSO End Property End Class

InduSoft Web Studio

2521

IWS Training Guide

Example: Using VBScript User-Defined Class Objects

Example: Using VBScript User-Defined Class Objects


The previous section showed how to use User Defined Class Objects to perform certain functions. But you can also use VBScript User-Defined Class Objects to define memory structures similar to IWS Class Objects. For example: Class cTank Public Pressure Public Temperature Public Level Public Contents End Class Dim Tank(), i Const MaxTanks = 3 ReDim Tank( MaxTanks) For i = 1 to MaxTanks Set Tank(i) = New cTank Next tank(1).contents = Fructose tank(2).contents = Water tank(3).contents = Syrup

Notes: The Scope of the VBScript variable is determined according to IWS rules. Put the Class definition in the Variables section. While VBScript variables (including VBScript Class Objects) do not consume IWS tags, they do consume memory. Class Objects are not overly efficient in their memory utilization, which may be an issue with Windows CE-based applications.

2522

InduSoft Web Studio

VBScript Objects and Collections

IWS Training Guide

VBScript Objects and Collections


VBScript has certain Objects and Collections that are inherent with VBScript. These include: Debug Err Object Match Object & Matches Collections Scripting Dictionary Object Scripting FileSystemObject o Drive Object o File Object o FileSystemObject Collections o Folder Object Regular Expression Object & Submatches Collection TextStream Object

VBScript Implicit Objects and Collections


Objects & Collections Class Object Debug Err Match Object Dictionary Matches Collection RegExp Object SubMatches Collection An associative array that can store any type of data. Data is accessed by a key. Description Declares the name of a class, as well as a definition of the variables, properties, and methods that comprise the class The Debug object is an intrinsic global object that can send an output to a script debugger, such as the Microsoft Script Debugger. Contains information about the last run-time error. Accepts the Raise and Clear methods for generating and clearing run-time errors.

Object & Collection Summary Objects & Description Collections Drive An object that refers to a specific Drive Drives A collection of Drive objects. File An object that refers to a specific File Files A collection of File objects. FileSystemObject An object model used to access the Windows file system Folder An object that refers to a specific Folder Folders A collection of Folder objects. Match Provides access to the read-only properties of a regular expression match. Matches Collection of regular expression Match objects. RegExp Provides simple regular expression support. Submatches A collection of regular expression submatch strings. TextStream An object that refers to a text File

InduSoft Web Studio

2523

IWS Training Guide

Err Object
The VBScript Err object contains information about run-time errors. Err Object Properties Properties Description Description The descriptive string associated with an error. HelpContext A context ID for a topic in a Windows help file. HelpFile A fully qualified path to a Windows help file. Number A numeric value identifying an error. Source The name of the object or application that originally generated the error. Err Object Methods Properties Description Clear Clears all property settings. Raise Generates a run-time error. The properties of the Err object are set by the generator of an error-Visual Basic, an Automation object, or the VBScript programmer. The default property of the Err object is Number. Err.Number contains an integer and can be used by an Automation object to return an SCODE. When a run-time error occurs, the properties of the Err object are filled with information that uniquely identifies the error and information that can be used to handle it. To generate a run-time error in your code, use the VBScript Err Object Raise Method. The Err object's properties are reset to zero or zero-length strings ("") after an On Error Resume Next statement. The VBScript Err Object Clear Method can be used to explicitly reset Err. The Err object is an intrinsic object with global scope-there is no need to create an instance of it in your code.

2524

InduSoft Web Studio

IWS Training Guide

Scripting FileSystemObject
The VBScript FileSystemObject object provides access to a computer's file system FileSystemObject Methods Method Description BuildPath Appends a name to an existing path. CopyFile Copies one or more files from one location to another. CopyFolder Recursively copies a folder from one location to another. CreateFolder Creates a folder. CreateTextFile Creates a specified file name and returns a TextStream object. DeleteFile Deletes a folder and its contents. DeleteFolder Deletes a folder and its contents. DriveExists Indicates the existence of a drive. FileExists Indicates the existence of a file. FolderExists Indicates the existence of a folder. GetAbsolutePathName Returns a complete and unambiguous path from a provided path specification. GetBaseName Returns the base name of a path. GetDrive Returns a Drive object corresponding to the drive in a path GetDriveName Returns a string containing the name of the drive for a path. GetExtensionName Returns a string containing the extension for the last component in a path. GetFile Returns a File object corresponding to the file in a path. GetFileName Returns the last component of a path that is not part of the drive specification. GetFolder Returns a Folder object corresponding to the folder in a specified path. GetParentFolderName Returns a string containing the name of the parent folder of the last component in a path. GetSpecialFolder Returns the special folder requested. GetTempName Returns a randomly generated temporary file or folder name. MoveFile Moves one or more files from one location to another. MoveFolder Moves one or more folders from one location to another. OpenTextFile Opens a file and returns a TextStream object FileSystemObject Properties Properties Description Drives A Drives collection of all Drive objects available on the local machine. Collections returned by FileSystemObject method calls reflect the state of the file system when the collection was created. Changes to the file system after creation are not reflected in the collection. If the file system might be changed during the lifetime of the collection object, the method returning the collection should be called again to ensure that the contents are current. Set fs = CreateObject("Scripting.FileSystemObject") Set a = fs.CreateTextFile("c:\testfile.txt", True) a.WriteLine("This is a test.") a.Close In the code shown above, the CreateObject function returns the FileSystemObject (fs). The CreateTextFile method then creates the file as a TextStream object (a) and the VBScript TextStream Object WriteLine Method writes a line of text to the created text file. The VBScript TextStream Object Close Method flushes the buffer and closes the file.

Drive Object The Drive object provides access to the properties of a particular disk drive or network shared drive.

InduSoft Web Studio

2525

IWS Training Guide

Drive Object Properties Properties Description AvailableSpace The amount of space available to a user on the specified drive or network share. DriveLetter The drive letter of a physical local drive or network share DriveType A value indicating the type of a drive. FileSystem The amount of free space available to a user on the drive or network share. FreeSpace The amount of free space available to a user on the drive or network share. IsReady True if the drive is ready, False if not. Path The file system path for a drive. RootFolder A Folder object representing the root folder of a drive. SerialNumber The decimal serial number used to uniquely identify the disk volume. ShareName The network share name of a drive TotalSize The total space, in bytes, of a drive or network share VolumeName The volume name of a drive. The following code illustrates the use of the Drive object to access drive properties: Sub ShowFreeSpace(drvPath) Dim fs, d, s Set fs = CreateObject("Scripting.FileSystemObject") Set d = fs.GetDrive(fs.GetDriveName(drvPath)) s = "Drive " & UCase(drvPath) & " - " s = s & d.VolumeName & vbCrLf s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0) s = s & " Kbytes" Response.Write s End Sub

2526

InduSoft Web Studio

IWS Training Guide

File Object
The File object provides access to all the properties of a file. File Object Methods Properties Copy Delete Move OpenAsTextStream File Object Properties Properties Attributes DateCreated DateLastAccessed DateLastModified Drive Name ParentFolder Path ShortName ShortPath Size Type

Description Copies a file from one location to another. Deletes a file. Moves a file from one location to another. Opens a file and returns a TextStream object.

Description The attributes of a file. The date and time that the file was created. The date and time that the file was last accessed. The date and time that the file was last modified. The drive letter of the drive on which the file resides. The name of the file. The Folder object for the parent of the file. The file system path to the file. The short name used by programs that require 8.3 names. The short path use by programs that require 8.3 names. The size, in bytes, of a file. Information about the type of a file.

The following code illustrates how to obtain a File object and how to view one of its properties. Sub ShowFileInfo(filespec) Dim fs, f, s Set fs = CreateObject("Scripting.FileSystemObject") Set f = fs.GetFile(filespec) s = f.DateCreated Response.Write s End Sub

InduSoft Web Studio

2527

IWS Training Guide

Folder Object The VBScript Folder object provides access to all the properties of a folder.
Folder Object Methods Properties Description Copy Copies a folder from one location to another. Delete Deletes a folder. Move Moves a folder from one location to another. CreatTextFile Creates a file and returns a TextStream object. Folder Object Properties Properties Attributes DateCreated DateLastAccessed DateLastModified Drive Files IsRootFolder Name ParentFolder Path ShortName ShortPath Size SubFolders

Description The attributes of a folder. The date and time a folder was created. The date and time that the folder was last accessed. The date and time that the folder was last modified. The drive letter of the drive on which the folder resides. A Files collection of all File objects in the folder. True if this is the root folder of a drive. The name of the folder. The Folder object for the parent of the folder. The file system path to the folder. The short name used by programs that require 8.3 names. The short path used by programs that require 8.3 names. The size, in bytes, of all files and subfolders contained in a folder A Folders collection containing all the folders in a Folder object

The following code illustrates how to obtain a Folder object and how to return one of its properties: Sub ShowFolderInfo(folderspec) Dim fs, f, s, Set fs = CreateObject("Scripting.FileSystemObject") Set f = fs.GetFolder(folderspec) s = f.DateCreated Response.Write s End Sub

Examples
Const OverWrite = TRUE Const DeleteRdOnly = True SourceFile = C:\data\MyData.MDB SourceFiles = C:\data\*.MDB DestPath = C:\Backup DeleteFile = C:\backup\Mydata.MDB DeleteFiles = C:\backup\*.MDB) Set objFS = CreateObject(Scripting.FileSystemObject) Copy a single file to a new folder, overwrite any existing file in destination folder objFS.CopyFile (SourceFile, DestPath, OverWrite) Copy a set of files to a new folder, overwrite any existing files in destination folder objFS.CopyFile (SourceFiles, DestPath. OverWrite)

2528

InduSoft Web Studio

IWS Training Guide

Delete a file objFS.DeleteFile(DeleteFile) Delete a set of files in a folder objFS.DeleteFile(DeleteFiles, DeleteRdOnly) Move a file to a new folder objFS.MoveFile(SourceFile, DestPath) Move a set of files to a new folder objFS.MoveFile(SourceFiles, DestPath) Rename a file objFS.MoveFile(SourceFile, C:\data\MyData041406.MDB) Verify if a file exists If objFS.FileExists (SourceFile) Then Set objFolder =objFS.GetFile(SourceFile) MsgBox File Exists & objFolder Else MsgBox File does not exist End If

Will display File Exists and Path + File

InduSoft Web Studio

2529

IWS Training Guide

VBScript Drives Collection


Read-only collection of all available drives. Removable-media drives need not have media inserted for them to appear in the Drives collection. Drives Collection Object Properties Properties Description Count Returns the number of items in a collection. Read-only Item Returns an item on the specified key. Read/Write The following code illustrates how to get the Drives collection and iterate the collection using the For Each...Next statement: Sub ShowDriveList Dim fs, d, dc, s, n Set fs = CreateObject("Scripting.FileSystemObject") Set dc = fs.Drives For Each d in dc s = s & d.DriveLetter & " - " If d.DriveType = Remote Then n = d.ShareName Else n = d.VolumeName End If s = s & n & vbCrLf Next Response.Write s End Sub

VBScript Files Collection


Collection of all File objects within a folder. Files Collection Object Properties Properties Description Count Returns the number of items in a collection. Read-only Item Returns an item on the specified key. Read/Write The following code illustrates how to get a Files collection and iterate the collection using the For Each...Next statement: Sub ShowFolderList(folderspec) Dim fs, f, f1, fc, s Set fs = CreateObject("Scripting.FileSystemObject") Set f = fs.GetFolder(folderspec) Set fc = f.Files For Each f1 in fc s = s & f1.name s = s & vbCrLf Next Response.Write s End Sub

2530

InduSoft Web Studio

IWS Training Guide

VBScript Folders Collection


Collection of all Folder objects contained within a Folder object. Folders Collection Methods Properties Description Adds a new Folder to a Folders collection Add Folders Collection Properties Properties Description Count Returns the number of items in a collection. Read-only Item Returns an item on the specified key. Read/Write The following code illustrates how to get a Folders collection and how to iterate the collection using the For Each...Next statement: Sub ShowFolderList(folderspec) Dim fs, f, f1, fc, s Set fs = CreateObject("Scripting.FileSystemObject") Set f = fs.GetFolder(folderspec) Set fc = f.SubFolders For Each f1 in fc s = s & f1.name s = s & vbCrLf Next Response.Write s End Sub

InduSoft Web Studio

2531

IWS Training Guide

TextStream Object
The VBScript TextStream object facilitates sequential access to a file TextStream Object Methods Properties Description Close Closes an open stream. Read Reads a specified number of characters from a stream. ReadAll Reads an entire stream. ReadLine Reads an entire line from a stream. Skip Skips a specified number of characters when reading a stream. SkipLine Skips the next line when reading a stream. Write Writes a specified string to a stream. WriteBlankLines Writes a specified number of newline characters to a stream. WriteLine Writes a specified string and newline character to a stream. TextStream Object Properties Properties Description AtEndOfLine True if the file pointer is before the end-of-line marker. AtEndOfStream True if the file pointer is at the end of the stream Column The column number of the current character in the stream. Line The current line number of the stream. VBScript TextStream Object Description: The VBScript TextStream object Usage: oTextStream.{property | method} Return: Depends on Property or Method used Remarks Example: In the following code, a is the TextStream object returned by the CreateTextFile method on the FileSystemObject: Set fs = CreateObject("Scripting.FileSystemObject") Set a = fs.CreateTextFile("c:\testfile.txt", True) a.WriteLine("This is a test.") a.close

2532

InduSoft Web Studio

COM Objects and Collections

IWS Training Guide

COM Objects and Collections


In addition to user-defined Class Objects and VBScript Objects and Collections, there are many different COM Objects (and Object Collections) and other system objects based on COM technology that are accessible from VBScript. These Objects include: ActiveX Controls inserted on an IWS Screen (via Insert OCX tool) ActiveX Controls instantiated via VBScript ADODB and ADOX Objects and Collections Microsoft Office OLE Automation (Word, Excel, Access, Outlook & Components) WMI WSH WSDL XMLDOM

ActiveX Controls Inserted On An IWS Screen


InduSoft Web Studio (IWS) serves as an ActiveX control container, which is a parent program that supplies the environment for an ActiveX control to run. Through the IWS development interface (insert OCX tool), one or more ActiveX controls can be added to a screen. The OCX (ActiveX Control) must first be registered, if it was not already done so as part of the installation of the ActiveX control. IWS provides a Register Controls tool (under Tools on the toolbar) to allow registration of ActiveX controls, and to verify if a control has already been registered. After the OCX is inserted on the screen, IWS will assign the control a name. This name can be changed in the Object Properties dialog box, accessed by double clicking on the control in the IWS development environment, but the name of the control must be unique from any other control used by the current IWS application. In the Object Properties dialog box, the Configuration button will provide access to the Properties, Methods and Events accessible for this ActiveX control. In the Configuration dialog box, there is a tab for Events, which allow for the execution of a VBScript code segment if an Event is triggered for the ActiveX control. In the Properties and Methods tabs, parameters, triggers, IWS tags, etc. can be tied to the various Properties and Methods.

Microsoft Slider Control 6.0

Configure the Controls Properties, Methods & Events

Select to input VBScript code segments for the ActiveX Control Events

InduSoft Web Studio

2533

IWS Training Guide

COM Objects and Collections

Interaction with the ActiveX control from VBScript is accomplished through VBScript code placed in a Screen Script that is associated with the screen where the ActiveX control is placed. By entering a right mouse click on a blank portion of the screen, and selecting Screen Script, the Screen Script is accessed. For ActiveX Objects placed on the screen, you do not need to instantiate the Object in VBScript, IWS has already taken care of this. You simply need to reference the ActiveX control by its name, found in the Object Properties dialog box. Note: when referring to the name from VBScript, with IWS 6.1 SP1, the ActiveX control name was case sensitive. With SP2, it is no longer case sensitive. From the VBScript screen interface, you can access the ActiveX controls Properties and Methods. Events are not accessible from the VBScript Screen Script interface. The Active Notes: You must use the VBScript Screen Script interface for the screen which contains the ActiveX control in order to access the ActiveX controls Properties and Methods. You cannot access the ActiveX controls Properties and Methods from another Screen Script, or from any other VBScript interface in IWS. From VBScript, you can only access the ActiveX controls Properties and Methods. VBScript code segments for Events that are triggered by the ActiveX control can be entered, but these VBScript code segments must be entered from the Configuration dialog box (i.e. Object Properties Configuration Events). When the ActiveX control is referenced from the VBScript Screen Script interface, the ActiveX controls name is case-sensitive with SP1. This was corrected in SP2. You do not need to instantiate the ActiveX control. IWS has already taken care of this. Simply refer to the ActiveX control name followed by a . and then the Property or Method. In the VBScript Screen Script interface, place the cursor in a code segment area (Subroutine) and press Ctrl Space to invoke IntelliSense to see the VBScript statements and functions, as well as the ActiveX controls available for this Script Interface. Once you enter the ActiveX control object name, when you type a period (.), Intellisense will display a list of available Properties and Methods for the ActiveX control referenced.

ActiveX Controls Instantiated from VBScript


ActiveX controls can be instantiated from VBScript by using the CreateObject and referencing the Program ID (ProgID) of the ActiveX object, although the ActiveX object will not show up on the IWS screen if the script segment is associated with a Screen.

ADODB and ADOX Objects and Collections


ADODB is the database wrapper for ADO.NET, or ActiveX Data Objects for Microsofts .NET Framework. ADO.NET is Microsofts database interface technology that provides an API to database client applications (i.e. IWS and VBScript), supporting a common interface to access and manipulate data contained in a wide variety of database servers from different vendors. From the database client side, there is a level of abstraction provided by the API that enables interaction (e.g. database access and manipulation) to various vendors databases with virtually no code changes, except for the connection string to the database Provider (an object that interacts with the physical database). There are various ADODB Objects and Collections available to the developer. ADOX are Microsofts ActiveX Data Object Extensions for Data Definition Language (database schema creation, modification and deletion) and Security. It is a companion set of Objects to the core ADO.NET objects.

2534

InduSoft Web Studio

COM Objects and Collections

IWS Training Guide

Microsoft Office Automation


VBScript can access the various Microsoft Office Automation COM servers. These include: Microsoft Access (Access.Application) Microsoft Excel (Excel.Application) Microsoft Word (Word.Application) Microsoft Outlook (Outlook.Application) Microsoft Graph Microsoft Excel Chart (Excel.Chart) To instantiate a Excel and a Word Application, for example, we would use the following VBScript statements: Set objXL = CreateObject(Excel.Application) Set objWrd = CreateObject(Word.Application) Once the Microsoft Office COM object is instantiated, the VBScript Programmer can access the various Properties and Methods. Using VBScript, objects can be moved from one Microsoft application to another.

WMI
Windows Management Instrumentation, or WMI, is a set of extensions to the Windows Driver Model that provide an interface from a program (such as VBScript) into various components of the Windows operating system to retrieve information and notification. Using WMI and VBScript, management of Windows-based PCs and Servers can be accomplished either locally or remotely. WMI is based on the Common Information Model (CIM), allowing a uniform methodology of managing various Windows components. WMI is available to all .NET applications and is supported under Windows 2000, XP or Server 2003, but not Windows CE at present. Examples of Microsoft Windows components accessible through WMI include: Control Panel (can manipulate basic system settings and controls) Device Manager (display and control hardware added to the PC, which drivers are used) Event Viewer (view the system event log locally or remotely) RegEdit (Windows Registry Editor) Various applications (Notepad, Command.Com and Cmd.exe) Windows Core Components

Windows Script Host


Windows Script Host, or WSH, is the successor to the Batch File first introduced for DOS. WSH automates system administration tasks, and supports multi-lingual scripting including VBScript. Scripts can be run locally, or on remote computers. There are several WSH objects including: WScript Object (not available from IWS, since IWS is the host) WshShell (allows scripts to work with the Windows Shell e.g. read/write to registry, shortcuts, system administration tasks, running programs) WshNetwork (manages network drives and printers) WshController (runs scripts locally or remotely)

InduSoft Web Studio

2535

IWS Training Guide

COM Objects and Collections

WSDL
Web Services Definition Language, or WSDL, is an XML-based language for describing network services as a set of endpoints operating on messages containing either document-oriented or procedure-oriented information. WSDL is frequently used in conjunction with SOAP (Simple Object Access Protocol, a simple XML-based protocol for applications to exchange information using HTTP). Common examples of WSDL are stock price, news services, weather information, currency conversion, etc. VBScript code in an IWS application can instantiate a SOAP client object through the following statement: Set oSOAP = CreateObject("MSSOAP.SoapClient")

XMLDOM
XMLDOM is the XML Document Object Model that defines a standardized approach for creating, accessing and manipulation XML documents. The DOM structures the XML document as a tree-like structure (the node), with each node having elements, attributes and text. There is a root element, which is the highest level element, and 0 or more child (sibling) nodes. Each node can also have 0 or more child nodes. A VBScript code segment can be created in an IWS application to allow creation, accessing and manipulation of XML Documents. This allows passing of data between IWS and another computer in XML format. Note that in addition to XMLDOM, ADO.NET also supports XML databases.

2536

InduSoft Web Studio

VBScript Configuration and Operation in IWS

IWS Training Guide

VBScript Configuration and Operation in IWS


IWS acts as the host application for the Microsoft VBScript Engine. This means that to write VBScript, you need to be in the IWS development (engineering) environment. It is important to note that there is no one central location where a VBScript interface is located inside an IWS application. The location of the VBScript interface (where the VBScript code gets placed) depends on the function the VBScript code is to perform and the scope of access to its Procedures and Variables. InduSoft has implement VBScript in this manner to simplify its use, and to be consistent with the IWS architecture as well as current licensing methods. VBScript is interpreted code. While it executes fairly efficiently, it is nevertheless interpreted and will never execute as efficiently as compiled code. This should not present any concern for HMI/SCADA applications since IWS is performing the real-time management of the tag database and key functions such as alarming, logging, etc. The interpreted nature of VBScript allows changes to be made quickly to an application. IWS supports dynamic, on-line configuration and this capability is maintained with the addition of VBScript support Developers familiar with IWS know that in the bottom left corner of the development window are tabs that provide access to the Database, Graphics, Tasks, and Communications Workspace folders containing the different application components. The developer will need to navigate among these different folders and application components when using VBScript. VBScript interfaces can be found in 6 different areas: Database Workspace folder Global Procedures Graphics Workspace folder - Graphics Script Graphic Screens Screen Scripts IWS Objects on a Screen Command Dynamic ActiveX Objects on a screen ActiveX Events Tasks Workspace folder Background Startup Script and Background Script Groups

Subfolders and Icons within a Workspace folders

Tabs to access various Workspace folders

InduSoft Web Studio

2537

IWS Training Guide

Global Procedures

The figure below shows the structure of the VBScript interfaces within a typical IWS project (application). Note that there are certain types of VBScript interfaces that have one instance (e.g. Global Procedures, Background Startup Tasks and Graphic Script) while others can have multiple instances (e.g. Background Script Groups, Screen Scripts, Command Dynamic and ActiveX Events).

Global Procedures
Global Procedures are located in the Database Worksheet folder. Global Procedures are shared by both the Graphics Module Scripts (Graphics Script and Screen Scripts) and the Background Task Scripts (Background Startup Script and Background Script Groups). Note that it this is only the Procedures that are shared, not the Variables. Other VBScript interfaces within the Graphic Module or Background Task do not share variables or procedures between them; they are independent of each other.

Global Procedures Subfolder in Database Worksheet folder

VBScript Interface

2538

InduSoft Web Studio

Graphics Script

IWS Training Guide

Notes:
Before executing the application, be sure to save (or close) the Screen after any VBScript is entered. Otherwise the changes might not be updated. This is true for all VBScript interfaces.

Graphics Script
The Graphics Script is located in the Graphics Worksheet folder. Procedures and Variables declared in the Graphics Script interface are available locally but are not accessible by any Screen Script interface, or from any other VBScript interface within IWS. Procedures and Variables declared in a Screen Script interface are not accessible by the Graphics Script. If common Procedure(s) are required, they should be put into the Global Procedures interface. Note that the Graphics Script is scanned (processed) by IWS before the Screen Scripts. The Graphics Script has three different pre-configured subroutines to execute VBScript code. These subroutines execute the VBScript contained in them based on the event state of the Graphics Module. These are: Graphics_OnStart Code contained within this subroutine is automatically executed just once when the Graphics Module is started. This is a good area to initialize variables or execute start-up code. Graphics_WhileRunning Code contained within this subroutine is automatically executed continuously while the Graphics Module is running. The rate at which this subroutine is called depends on the performance of the hardware platform and other tasks running at the time. Graphics_OnEnd Code contained within this subroutine is automatically executed just once when the Graphics Module is closed.

Graphic Script Icon in Graphics Worksheet folder

VBScript Interface

InduSoft Web Studio

2539

IWS Training Guide

Screen Scripts

Notes: Do not change the name of the pre-configured subroutines in the VBScript interface. Otherwise they many not properly execute. The Graphics Script operates for both the Server (the host processor where the IWS application is running) and Web Thin Clients (web browser interface using Microsoft Internet Explorer). For the Server, the Graphics module is the Viewer task (the display on the host processor), while the ISSymbol control is the Graphics module for Web Thin Clients. The operation of the Graphics Script on the Server is described above, and starts when the application is started on the Server, assuming there are one or more screens. But since Web Thin Clients can log on at any time after the Server is started, the functioning of the Graphics Script is different for Web Thin Clients and is independent of the operation of the Graphics Script on the host Server. Web Thin Client operation is as follows: When a Web Thin Client logs on to the Server, following completion of the log on process, the Graphics_OnStart subroutine will be executed for the Web Thin Client. This will occur each time any new Web Thin Client logs on to the Server. Following completion of the execution of the Graphics_OnStart subroutine, the Graphics_WhileRunning subroutine will be executed for as long as the Web Thin Client (browser) hosts the ISSymbol control (i.e. while an active network link exists and the ISSymbol is active in the browser). When the Web Thin Client is shut down or when the ISSymbol control is no longer hosted by the browser, the Graphics_OnEnd subroutine is executed

Screen Scripts
Screen Scripts are associated with individual graphical screens. These screens can be for display on the host Server (where the IWS application is running), for a Web Thin Client, or both. Procedures and Variables declared in a Screen Script VBScript interface are not accessible by any other VBScript interface within IWS. However, the Screen Script interface can access procedures declared in the Global Procedures script interface.

Screen subfolder in Graphics Worksheet folder

VBScript Interface

2540

InduSoft Web Studio

Screen Scripts

IWS Training Guide

There are two methods to access a Screen Script. The first is to select the desired Screen and have it displayed on the active IWS workspace. Then, perform a right mouse click while the cursor is located on the display screen. A pop-up menu will let you select the Screen Script (as shown at the right). When the Screen Script option is selected, the IWS workspace will display the Screen Script VBScript interface. Notice the Screen Script VBScript interface looks very similar to the Graphics Script interface. The differences between the Screen Script and the Graphics Script are: There is only one Graphics Script. The Graphics Script is activated when the Graphics Module starts You can have multiple Screen Scripts. There is one Screen Script available per Screen, but you can have multiple screens. The second method to access a Screen Script is to select the desired Screen and have it displayed on the active IWS workspace. Then from the top toolbar, select View. A pull-down menu (as shown at the right) will have the Screen Script option available. By selecting this option, you will activate the Screen Script VBScript interface. The Screen Script interface has three predefined subroutines. These are: Screen_OnOpen Code contained within this subroutine is automatically executed just once when the Screen is opened. Screen_WhileOpen Code contained within this subroutine is automatically executed continuously while the Screen is open. The rate at which this subroutine is called depends on the performance of the hardware platform and other tasks running at the time. Screen_OnClose Code contained within this subroutine is automatically executed just once when the Screen is closed. Pop-Up Menu

Pull-down Menu

The execution of the Screen Script subroutines on the Server executes independently from the execution on Web Thin Clients.

Notes: Do not change the name of the pre-configured subroutines in the VBScript interface. Otherwise they many not properly execute. Before executing the application, be sure to save (or close) the Screen after any VBScript is entered. Otherwise it might not be updated. This is true for all VBScript interfaces. The Graphic Script is scanned (processed) by IWS before the Screen Scripts are processed.

InduSoft Web Studio

2541

IWS Training Guide

Command Dynamic

Command Dynamic
A Command Dynamic is associated with a specific object on a Screen, and allows one or more actions to take place when an event occurs with the specific object. A typical use is a button (perhaps a rectangle) that is placed on the screen. When an operator selects on the button (via mouse click or pressing a touchscreen over the object), this action is expected to initiate some action. That action may be to set/reset a PLC bit, jump to a different screen, whatever. The Command Dynamic allows the developer to chose what action to take. With Version 6.1, IWS adds new capability to the Command Dynamic interface. In addition to the IWS built-in language command, the Command Dynamic can now execute VBScript code. The steps to access the VBScript interface within a Command Dynamic are: 1. Select the object on the Screen currently opened in the IWS workspace. If the object has a Command Dynamic associated with it, then right click on the object. Otherwise, click on the Command Dynamic icon (right) from the Mode toolbar and then right click on the object. 2. Now, the Object Properties dialog box for the Command Dynamic will open. Click on the Config button in the lower right corner of the dialog box.

3. Select the event condition (e.g. On Down) where your want code to be execute and then select VBScript as the Type. 4. Enter your VBScript code (variable declarations and executable statements). Within the Command Dynamic, you enter VBScript variables and executable statements subject to the following conditions: Any variable declared in this interface will only have a local scope. You cannot implement procedures (i.e. Subroutines or Functions) within this interface. Notwithstanding these restrictions, VBScript code within a Command Dynamic still has access to all Global Procedures. VBScript code within the Command Dynamic interface is executed whenever one or more of the selected event conditions (listed in the Command Dynamic configuration screen) occur for the selected object. The execution of the Command Object script on the Server executes independently from the execution on Web Thin Clients. Notes: Before executing the application, be sure to save (or close) the Screen after any VBScript is entered. Otherwise it might not be updated. This is true for all VBScript interfaces.

2542

InduSoft Web Studio

ActiveX Events

IWS Training Guide

ActiveX Events
IWS is an ActiveX container, supporting ActiveX controls, generally inserted on a given graphical screen. With IWS Version 6.1, there is a VBScript interface to ActiveX Events so that an ActiveX object event can trigger a VBScript code segment. The steps to accessing the VBScript ActiveX Event interface are as follows: 1. Select the ActiveX object on the Screen currently opened in the IWS workspace. Right click on the object to open its Object Properties dialog box. If you need to insert an ActiveX object, select the ActiveX Control icon from the Mode toolbar and then right click on the object In the lower right corner of the ActiveX Object Properties dialog box will be a Configuration button. Click this to open up the Configuration options dialog box.

2. Click on the Events tab (as shown at the right).

3. Click on the button in the Script Column for the event you want to write VBScript for.

This is the scripting interface for ActiveX Events. Be sure VBScript language is selected. You can now insert code that will execute when the selected ActiveX Event is triggered. Within the ActiveX Event interface, you enter VBScript variables and executable statements subject to the following conditions: Any variable declared in this interface will only have a local scope. You cannot implement procedures (i.e. Subroutines or Functions) within this interface. Notwithstanding these restrictions, VBScript code within the ActiveX Event interface still has access to all Global Procedures, as well as any procedures in the Screen Script for the same Screen where the ActiveX object is configured.

InduSoft Web Studio

2543

IWS Training Guide

Background Task Startup Script

VBScript code within the ActiveX Event interface is executed whenever one or more of the selected Event conditions (listed in the Configuration dialog box) occur for the selected ActiveX object. The execution of the script on the Server executes independently from the execution on Web Thin Clients. Notes: Before executing the application, be sure to save (or close) the Screen after any VBScript is entered. Otherwise it might not be updated. This is true for all VBScript interfaces.

Background Task Startup Script


In the Tasks Worksheet folder is the Script subfolder which will contain a default Startup Script icon and any Background Task Script Groups declared. To edit the Background Task Startup Script: 1. Click on the Tasks Worksheet folder 2. Click on the Script subfolder. Any VBScript code placed in this interface will execute when the Background Task module is started, which occurs when the IWS application is started. This code will only execute once, and is meant for initialization purposes. Variables and Procedures declared in the Background Task Startup Script are available to the Background Task Script Group, but are not available to any VBScript interfaces in the Graphic Module. Remember that the Background Task Group Startup Script can access the procedures declared in Global Procedures. Since the Background Task Startup Script has no interaction with a Graphics script, the only Server display I/O functions that can be implemented are MsgBox and InputBox functions. Since the Background Task Startup Script runs on the IWS Server, there is no effect with Web Thin Clients.

2544

InduSoft Web Studio

Background Task Script Groups

IWS Training Guide

Background Task Script Groups


The Background Task Script Groups consist of one or more VBScript interface groups that run in the Background Task. By default, there are no Background Task Script Groups unless added by the developer. These Script Groups will execute in a background as long as their Execution Field is in a TRUE state. Background Task Script Groups have the following limitations: Variables declared in a Background Task Script Group have a local scope for its specific Script Group only. Variables cannot be shared with other Script Groups, nor any other VBScript Interface. Background Task Script Groups cannot declare their own Procedures (Subroutines and Functions). The Execution Field of the Script Group will only support IWS tags or built-in functions. No support for VBScript variables or Procedures is provided in the Execution Field. However, the Background Task Script Groups can do the following: Access Procedures and Variables within the Background Task Startup Script. Access Procedures declared in Global Procedures. To create a new Script Group, right-click on the Script subfolder in the Tasks tab of the Workspace. Select the Insert option from the pop-up menu. Note that the Startup Script is already defined. To open (edit) an existing Script Group, simply click its icon in the Script subfolder of the Tasks workspace tab. The code configured in each Script Group is executed by the Background Task. IWS scans the Script Groups sequentially (based on the number of the group) and executes only the Groups in which the condition configured in the Execution Field of the Script Group is set to or is evaluated to be TRUE (a value different from 0).

When any Script Group is saved during runtime (e.g. from an on-line configuration download), the Startup Script interface will be executed again, and the current value of the local variables contained in any Script Group will be reset, if any exist.

InduSoft Web Studio

2545

IWS Training Guide

Background Task Script Groups

Since the Background Task Script Groups run on the IWS Server, there is no effect with Web Thin Clients.

Notes: The Execution Field of the Script Group only supports syntax as specified by the IWS built-in language. Before executing the application, be sure to save (or close) the Screen after any VBScript is entered. Otherwise it might not be updated. This is true for all VBScript interfaces. If any Script Group is saved during runtime (i.e. on-line configuration), the Startup Script Group will be executed again and the current value of local variables will be reset

2546

InduSoft Web Studio

Scope of VBScript Procedures and Variables

IWS Training Guide

Scope of VBScript Procedures and Variables


The following table summarizes the relationship between the IWS VBScript interface location and its Scope of Variables and Procedures. The table also defines where the Scripts are located
Item Scope of Procedures and Variables
All Procedures are global, Variables are accessible only within Global Procedures (local) Procedures and Variables accessible within Graphics Script interface only. Can Call Global Procedures. Procedures and Variables accessible within Screen where the Script is written. Screen Script procedures accessible to ActiveX Events for ActiveX objects contained in the Screen. Can Call Global Procedures. Variables and Script accessible only in Object where the Script is configured. Can Call Global Procedures. Variables accessible only in Object where the Script is configured. Screen Script Procedures are accessible. Can Call Global Procedures.

Execution

Functionality
Declaration of Procedures (Functions and Subroutines) that are available globally Condition-based execution - Graphics Start - Graphics Open - Graphics Close Graphics Scripts execute before Screen Scripts

Location/Access

Global Procedures

Procedures are accessible to any Script on the host Server

Database Workspace Folder

Graphics Scripts

Executes on host Server and/or Web Thin Client where any screen is displayed.

Graphics Workspace Folder

Screen Scripts

Executes on host Server and/or Web Thin Client where the specific screen is displayed

Condition-based execution - Screen Start - Screen Open - Screen Close

Within the Screen.

Command Dynamic

Executes on host Server and/or Web Thin Client where the screen with the specific Object is displayed

Execution of Script when Object condition is met

Within Object (Command) Properties. The Screen that uses the Object must be open.

ActiveX Events

Executes on host Server and/or Web Thin Client where the screen with the specific Object is displayed

Execution of Script when selected ActiveX Event occurs

Within the ActiveX object. The Screen that uses the Object must be open.

InduSoft Web Studio

2547

IWS Training Guide

Scope of VBScript Procedures and Variables

Item

Scope of Procedures and Variables


Procedures and Variables accessible within the Script Group. Can Call Global Procedures. Accessible within Script Group only. Can Call Global Procedures.

Execution

Functionality
Declaration of Procedures and Variables that are available for Background Scripts Condition-based execution in background mode. Can have multiple Script pages.

Location/Access

Background Startup Script

Executes on Server as a background task

Tasks Workspace Folder

Background Script Groups

Executes on Server as a background task

Tasks Workspace Folder

2548

InduSoft Web Studio

Accessing IWS Tags and IWS Built-in functions

IWS Training Guide

Accessing IWS Tags and IWS Built-in functions


When writing your code in a VBScript interface, you can access any tag from the IWS tags database or any function from the IWS built-in language by applying the "$" prefix to the tag/function name, as in the examples below: CurTime = $Time a = $MyTag $Open("main.scr") Returns the value of the tag Time from the tags database Sets a to the value of the IWS tag MyTag Executes the Open() function to open the "main" screen

IWS tags and built-in functions are accessible from any VBScript code segment, regardless where located. If the IWS function returns a value (e.g. error or status information), this can be assigned to a VBScript variable. IWS tags can be used as arguments in VBScript statements and functions. If an undefined name follows the $, when the programmer does a Check Script function or attempts to Save the script, IWS will ask the programmer if they want to define the IWS tag, and if so, prompt for the tag type. IWS supports the following application tag types: Boolean (a Boolean (True/False) or digital value (0 or 1)) Integer (a 32-bit long-word signed integer type) Real (a real number stored as a double precision word) String (a string of characters of up to 1024 characters that holds letters, numbers, or special characters) Class (a user-defined, compound tag) Array (an array of values from 0 to 16,384) Passing variables between VBScript and IWS is straightforward but there are some conversion considerations that should be noted: IWS Boolean With VBScript, variable can be of the data subtype Boolean. VBScript defines keywords True and False for logical states True and False, respectively. In VBScript, False has a numeric value of 0, while True has a numeric value of -1. This is because Booleans are not actually stored as bits, but as 32-bit signed integers. If all bits are zero, then it is a 0 or logical False. If all bits are set to 1, then it is a signed value of -1 or a logical True. IWS objects that display IWS-defined boolean tags (e.g. Text I/O) will have the boolean values displayed as 0 or 1 (0=False, 1=True), not as False or True. Consider the following VBScript code segment: $MyBool = True Will be displayed as a 1 in an IWS object (*see below) $MyBool = False Will be displayed as a 0 in an IWS object The value for True assumed by Boolean IWS tags depends on the value of the parameter BooleanTrueAboveZero that is located in the [Options] section of the <Application>.APP file. To access this parameter, you need to open the <Application>.APP file with a simple text editor such as Microsoft Notepad. For example: [Options] BooleanTrueAboveZero = 0 IWS Boolean tag set to value 1 (True) when value <> 0 [Options] BooleanTrueAboveZero = 1 IWS Boolean tag set to value 1 (True) only when value > 0

One item to watch for is the boolean NOT operator. With an IWS tag, even though the tag is of type Boolean, it is really stored internally as a 32-bit signed variable. If you NOT a 0, the lower bit is set to one but in reality all the bits are set to 1s, meaning that with a variable that is a signed integer, the NOT of 0 is really -1. For example, a = CBool(Not(0))

InduSoft Web Studio

2549

IWS Training Guide

Accessing IWS Tags and IWS Built-in functions

$c = a

$c (IWS tag c) will display as -1

One programming trick that can be used when attempting to toggle IWS Boolean Tags between 0 and 1 is either: $tag = Abs ($tag=0) Either one of these statements will toggle the tag $tag = $If ($tag=0,1,0) between 0 and 1 IWS Integer All IWS integer tags are stored as 32-bit values. VBScript has 3 different variant subtypes that are of interest. Bytes are 8-bit values that are positive whole numbers ranging from 0 to 255. Integers are 16-bit signed values that range from -32,768 to 32,767. Long Integers are 32-bit values that range from 2,147,483,648 to 2,147,483,647. When storing to an IWS integer tag, the conversion to a 32-bit signed integer type will be automatically made. For example: a = CInt (-30) a is a 16-bit signed integer with a value of -30 $MyInt = a MyInt is a 32-bit signed integer with a value of -30 b = CByte (-30) Generates an error since Bytes are 0 to 255, not negative b = CByte (30) b is a 8-bit unsigned integer with a value of 30 $MyInt = b MyInt is a 32-bt signed integer with a value of 30 When converting from an IWS integer tag to an IWS tag, this is really not a problem since VBScript variables are type variant. For example: $MyInt = 400 Store a value larger than 255 (the Byte limit) a = CByte (10) store as a byte subdata type a = $MyInt a will equal 400. IWS Strings In IWS, strings are up to 1024 in length, while VBScript strings can be virtually unlimited in length (limited by available memory only). During the conversion from a VBScript string variable to an IWS string, any characters beyond the first 1024 will be truncated. For example: a = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 a=a&a&a&a&a&a&a&a&a&a String is 360 characters long a=a&a&a&a String is 1440 characters ling $MyStr = a Store string in IWS string Result is truncated after 1024 characters In most cases, this string length difference is not of material significance. However, certain ActiveX Controls can be used for block transfer of data to real-world devices and strings are ideal for forming variable length data blocks. The string can then be parsed to extract the data of interest.

IWS Classes IWS Classes are simply user-defined compound tags that can be made up of one or more IWS tag type. The IWS Classes and Tags are defined in the Database Worksheet. For example, if we define a IWS Class (under the Classes Folder in the Database worksheet ) called MyClass with the following elements MyClass Item1 Integer Item2 Integer Message String

2550

InduSoft Web Studio

Accessing IWS Tags and IWS Built-in functions

IWS Training Guide

Next, a Class tag is created (in the Application Tags Folder) Cls1 MyClass Finally, in VBScript, we can refer to the elements in the Class tag as follows: $Cls1.Item1 = 10 $Cls1.Item2 = 20 $Cls1.Message = Hello World

IWS Arrays Using the Class example from above, if (in the Application Tags folder) we had declared the variable Cls1 to have a size of 10, this would be an array with 11 elements. [Remember that the count starts at 0, not 1]. In VBScript, we would refer to the elements in the Class array tag as follows: $Cls1[1].Item1 = 10 $Cls1[1].Item2 = 20 $Cls1[1].Message = Hello World We can also use a VBScript variable for the index of the Class array tag. For example: Dim i i=1 $Cls1[i].Item1 = 10 $Cls1[i].Item2 = 20 $Cls1[i].Message = Hello World

Notes: IWS tags can be added through the VBScript interface. Simply type a $ followed by a valid IWS name, and when the Script is Saved, Closed or Check Script function invoked, the programmer will be prompted to create new IWS tag(s). VBScript variables and IWS variables can be passed to each other. Watch for string length differences with IWS (max. 1024 characters) versus VBScript (no limit).

InduSoft Web Studio

2551

IWS Training Guide

Accessing ActiveX Objects from VBScript

Accessing ActiveX Objects from VBScript


Any of the VBScript interfaces relating to a Screen (i.e. Screen Script, Command Dynamic, and/or ActiveX Events) can directly access the Properties and Methods of an ActiveX control (OCX) that is inserted on a screen. Using ActiveX Controls is fairly straight forward. First, the ActiveX controls must be registered (i.e. the Operating System Windows Registry must have an entry and Class ID (CLSID) established for the ActiveX Control). Usually when an ActiveX Control is installed in the PC, the installation program will register the ActiveX Control in the final stage of the installation process. If not, registration can be done with one of two methods: 1. Use the Microsoft RegSvr32 command - Invoke the Microsoft Windows Run command - In the dialog box, type CMD, then OK - Type REGSVR32 C:\<path to OCX control>\<ActiveX Control Name>.OCX, then Enter (Be sure path name is in quotes) - If the ActiveX Control registers properly, you will get a message indicated this - Close the dialog box 2. Use the Register Controls utility provided by IWS (under Tools on the main toolbar) - Click on Tools, then Register Controls - On the dialog box that pops up, click on Register - Use the file navigator to locate the ActiveX Control that you want to register - Click on Open. - Click on Close in the Register Controls dialog box. You can also use the IWS Register Controls utility to verify that the ActiveX Control has been registered. Beware that the registered name and the file name may not be the same, and in many cases they are not. The best way to verify the control is properly registered is to examine the path of the registered Control. When the ActiveX Control has been registered, it can be inserted onto a display screen using either the OCX tool in the IWS toolbar or by using the Insert -> ActiveX Object from the top toolbar. A dialog box will appear with a scrolled list of ActiveX objects that are available. Insert the ActiveX object(s) that are appropriate for the application by clicking on OK. IWS will automatically assign a unique name to the ActiveX control. You can use this name or change it, the only requirement being that it must be unique from other ActiveX controls. Now that an ActiveX Control has been placed on the Screen, any VBScript interface associated with that screen can access the ActiveX Control. These VBScript interfaces are limited to the Screen Script, Command Dynamic for objects located on the same Screen, and ActiveX Event Handler for other ActiveX objects located on the same Screen. For example, Microsoft has an ActiveX scrollbar control called MicrosoftFlatScrollBarControl 6.0 (SP6). Assuming this was inserted for the first time onto a Screen in an IWS application, IWS would likely name this Control MicrosoftFlatScrollbarControl1. For brevity, let us rename this to MFSC1. I could easily click on the ActiveX Control on the screen to access its Property Pages, Properties, Methods and Events. Note that Property Pages and Events are not accessible through the VBScript Interface, although a VBScript Interface is available with the ActiveXs Event Handler. Only an ActiveX Controls Properties and Methods are available from VBScript as implemented in IWS. By clicking on the object to get the Object Properties dialog box

2552

InduSoft Web Studio

Accessing ActiveX Objects from VBScript

IWS Training Guide

ActiveX Control Name established by IWS. You can rename this Control.

Use this interface to tie Properties and Methods to IWS tags.

To access the ActiveX Controls Properties and Methods from VBScript, you simply type the name of the Control, followed by a Period . and then the Property or Method. You will need to reference documentation from the developer of the ActiveX Control to determine which properties are setting (Set) or retrieving (Get), and the functioning of the Methods available. For example, with the Microsoft scroll bar control, we access Properties using the following code: MFSC1.Min = 0 Set the min value of the scroll bar to 0 MFSC1.Max = 100 Set the max value of the scroll bar to 100 $LocTag = MFSC1.Value Get the current location of the scroll bar, pass to IWS tag IWS tools such as Position and Command can be used with ActiveX controls. To enable these tools, insert the ActiveX control on the Screen and then make sure the ActiveX control is selected (highlighted). Then, select the Position or Command tool. For example, with the Position tool, you can control the visibility of the ActiveX Control, or change its location on the screen. Notes: All ActiveX Controls must have a unique name When referencing an ActiveX object name that has been inserted on a screen, note that the reference is case-sensitive from VBScript. Only ActiveX Properties and Methods can be accessed via VBScript. Event handling must be set-up by configuring the object (i.e. right click on the object) ActiveX Controls can only be accessed by VBScript interfaces associated with the Screen which contains the ActiveX Control (i.e. Screen Script, Command Dynamic, ActiveX Event Handler)

InduSoft Web Studio

2553

IWS Training Guide

IntelliSense

IntelliSense
The VBScript Editor provides a useful tool called IntelliSense, a feature first popularized in Microsoft Visual Studio. Intellisense can be thought of providing auto-completion based on the language elements, variables and class members, as well as a convenient listing of available functions. As the developer IntelliSense the dialog box can display the following: VBScript Functions ActiveX Controls, Properties and Methods (the ActiveX Control must be inserted on the Screen where the Screen Script, Command Dynamic or ActiveX Event is used) IWS tags and tag fields. IWS built-in functions As the programmer begins to type and characters are recognized, IntelliSense may turn on. If not, the programmer can activate IntelliSense by pressing the Ctrl key plus the Spacebar (Ctrl + ). By typing a $ at the beginning of a line, this allows access to IWS tags and built-in functions to be referenced. When IntelliSense is activate, a pop-up box will appear. The contents of the pop-up box depend on what the programmer has already typed. Sample IntelliSense pop-up dialogs are shown below:

IntelliSense Dialog for VBScript Functions

IntelliSense Dialog for IWS Functions

IntelliSense Dialog for IWS Tag Fields

IntelliSense uses different Icons to indicate the type of item that is being referenced. Some Icons are used to indicate different items, so it is important to notice what object is being referenced (i.e. is it an IWS tag, ActiveX Control, VBScript function, etc.) IntelliSense Icon Use IWS Boolean Tag IWS Integer Tag IWS Real Tag IWS String Tag IWS Class Tag VBScript Function, built-in IWS function, or ActiveX Control Method ActiveX Control Property, VBScript Constants For many of the functions (both VBScript functions and IWS built-in functions), IntelliSense provide a Parameter Quick Info pop-up dialog. This pop-up dialog may appear once the VBScript or IWS function is entered. An example is:

2554

InduSoft Web Studio

IntelliSense

IWS Training Guide

Notes: Use the Ctrl key plus Spacebar key (Ctrl + ) to activate IntelliSense. Doing this on a blank line will show all available VBScript functions and any ActiveX controls available. Use the Ctrl key plus Spacebar key (Ctrl + ) to auto-complete any VBScript function, IWS tag, IWS tag field, IWS Class or Class Member, IWS built-in function, or ActiveX Control name, Property or Method once enough of the characters have been entered so that the reference is no longer ambiguous. Typing a $ at the beginning of a line will invoke IntelliSense, referencing existing IWS tags and built-in functions Typing the name of an IWS tag, followed by the minus key - plus a greater than arrow key > will open the list of available fields for the IWS tag

InduSoft Web Studio

2555

IWS Training Guide

VBScript with Web Thin Clients

VBScript with Web Thin Clients


In a Web Thin Client environment, the browser serves as the host for both HTML web pages published by the IWS Server, as well as the host for VBScript code segments that are associated with a particular Screen or object on the Screen. Generally, Microsoft Internet Explorer serves as the browser in a Web Thin Client environment. A InduSoft ActiveX Control (ISSymbol) is used to coordinate communications between the IWS Server and a Web Thin Client. In a Windows XP/2000/NT-based Web Thin Client environment, Microsoft Internet Explorer (e.g. Version 6 or later) supports VBScripts and ActiveX by default. In a Windows CE-based Web Thin Client environment, Microsoft Internet Explorer (typically provided with PocketPC products) supports both VBScript and ActiveX, but VBScript support must be enabled in the Windows CE image (part of the Platform Build process, typically done by the hardware supplier). Windows CE systems with Microsoft Pocket Explorer (different that Microsoft Internet Explorer) will not work with VBScript as Pocket Explorer does not support VBScript due to memory limitations. Also remember that any ActiveX controls used on a Windows CE Web Thin Client must be developed to support Windows CE. VBScript Interface Global Procedures Graphics Module Functioning related to a Web Thin Client VBScript Global Procedures are accessible to VBScript code segments that execute on a Web Thin Client Operates on IWS Server PC only. Procedures and Variables not accessible to a Web Thin Client. This VBScript interface (for a Web Page) executes independently from the VBScript Interface for a Screen running on the IWS Server. The Graphics_OnStart() subroutine starts when the Web Thin Client Station is successfully logged in and ISSymbol is hosted on the Web Browser The Graphics_WhileRunning() subroutine executes on the Web Thin Client while the Web Thin Client remains logged in and the ISSymbol Control remain hosted on the Web Browser The Graphics_OnEnd() subroutine is executed once the Web Thin Client logs off or the ISSymbol Control is no longer hosted by the Web Browser This VBScript interface (for a Web Page) executes independently from the VBScript Interface for a Screen running on the IWS Server. This VBScript interface (for a Web Page) executes independently from the VBScript Interface for a Screen running on the IWS Server. Operates on IWS Server PC only. Procedures and Variables not accessible to a Web Thin Client. Operates on IWS Server PC only. Procedures and Variables not accessible to a Web Thin Client.

Screen Scripts

Command Dynamic ActiveX Event Handler Background Task Startup Background Task Scripts

Notes: Under Windows XP/2000/NT, to check or modify Internet Explorers settings for support of VBScript and ActiveX Controls, open Internet Explorer, then click on Tools Internet Options Security Custom Level. All VBScript interfaces unique to the Web Thin Client continue to have access to IWS tags and IWS built-in functions. When using a Windows CE device for the Web Thin Client, be sure ActiveX support and VBScript support is enabled. This is a function of the Windows CE OS image built using Microsoft Platform Builder. When using a Windows CE device for the Web Thin Client, verify that MsgBox and InputBox functions are enabled in the Windows CE OS image if you intent to use them.

2556

InduSoft Web Studio

Exercise: Using VBScript with Screens

IWS Training Guide

Exercise: Using VBScript with Screens


In this exercise, we will create 4 Objects; 3 button objects and a Text I/O object. The buttons will increment, decrement and display the value of Tag v1.

Open the Main.scr Screen Using the Button tool from the Static Object toolbar, add 3 Button Objects. Add the Command Dynamic to each Button Object. Set the following properties to the buttons: Button1: Caption Increment v1 Command Dynamic $v1 = $v1 + 1 (Click on Config, choose VBScript and put in the On Down tab) Button2: Caption Command Dynamic tab) Button3: Caption Command Dynamic Decrement v1 $v1 = $v1 - 1 (Click on Config, choose VBScript and put in the On Down

Display v1 Msgbox v1 = & $v1 (Click on Config, choose VBScript and put in the On Down tab)

Add a Text Object, caption is v1 = ###### Add the Text I/O Dynamic Property to the Text Object. Put v1 in the Tag Expression field. Save and Close the Screen

InduSoft Web Studio

2557

IWS Training Guide

Exercise: Using VBScript & Script Worksheets

Exercise: Using VBScript & Script Worksheets


This Exercise demonstrates a VBScript alternative to a previous Exercise where we used the WS Scripting Language to create a Field Process Simulator. Use the following procedure to configure a Script worksheet: In the Workspace, select the Tasks tab and then right-click on the Script folder. When the pop-up menu displays, select the Insert option:

Opening a Math Worksheet A blank Script worksheet displays:

Blank Script Worksheet The header portion of the worksheet contains the following fields: Description field: Provides space for an optional description of the worksheet. Execution field: Controls the script execution. You can type a full expression here, a simple condition, a tag name, or a value. Whatever it is, the script will execute while it is TRUE. The body section consists of a plain text field into which you can type VBScript. In the Description field, type Field Process Simulator. In the Execution field, type 1. This enables continuous execution of this Math worksheet; the value 1 is the TRUE condition.

2558

InduSoft Web Studio

Exercise: Using VBScript & Script Worksheets

IWS Training Guide

Next, to generate simulated process data that can be used by the various screens, we must set the following variables: Valve status (according to the command given) Temperature, pressure, and level for three tanks Simulated valve status (just transfer the value from the command tags to the status tags). Simulated temperature and pressure properties for each tank (configure these properties using sine and cosine trigonometric functions) Simulated level properties for each tank (remember that both the Fill and Empty valves allow for the same flow). Given this information, complete the body of the Script worksheet as follows:

Completed Script Worksheet

Notes: In the preceding Worksheet, the Script is executed continuously. In a real world application, we strongly recommend that the execution of each Script worksheet be carefully controlled to improve system performance. The Execution Field in the Header can usually be set to any non-zero value to execute the script. Depending on the BooleanTrueAboveZero setting (set in the Application File), this value must either be >0 or non-zero. BE SURE TO ONLY USE EITHER THE MATH WORKSHEET OR THE SCRIPT WORKSHEET, NOT BOTH

InduSoft Web Studio

2559

IWS Training Guide

Exercise: Using VBScript & Script Worksheets

Right click on the Startup Script Folder in the Tasks tab of the Workspace to open the Startup Script Worksheet Enter the following VBScript code.

2560

InduSoft Web Studio

Exercise: Using VBScript

IWS Training Guide

Exercise: Using VBScript


In this Exercise, we will create some examples using VBScript. Open the Scripts.scr Screen In a blank area of the Screen, click the right mouse button. Choose the Screen Script option. Enter the VBScript as shown below:

Save and Close the Scripts Screen Script (v7 should be declared as an integer Tag). Open the Scripts Screen Add a Text Object with the caption v7 = ######################### Add a Text I/O property and type v7 in the Tag/Expression field.

InduSoft Web Studio

2561

IWS Training Guide

Exercise: Using VBScript

Add two button objects to the Screen. One will have the caption Divide by 2 and the other will have the caption Multiply by 2. Add the Command Dynamic to each button object. Select Type as VBScript Add the VBScript to each Command Dynamic as shown:

Close the Object Properties dialog box Save and Close the Screen

Notes: For Background Tasks, the IWS Scripting Language uses Math Worksheets while VBScript uses Script Worksheets The Script Worksheets include a Startup Script, which can be used to run VBScript code one time at startup.

2562

InduSoft Web Studio

Exercise: Using VBScript

IWS Training Guide

Notes

InduSoft Web Studio

2563

Chapter 26.

Databases

Databases store information in one or more tables that can be accessed, updated and queried by an application program, whether the database is in the same PC or a remote PC from the application program. There are different data models for databases, and the choice of database depends upon several factors including: - amount of data to be stored - the type and number of consumers of the database information - security - reliability - type of operations to be performed on the database A database can be defined as a structured collection of records or data stored in a computer so that the records or data can be retrieved in response to queries executed on the database by a program. The records retrieved in response to the query become information that can be used for decision making. There are a number of database models that are used today, although

ISAM File Database


ISAM (Indexed Sequential Access Method) databases are very simple file-based databases. ISAM files have fixed length records, indexes and file system locks (to control access to the database). To read a ISAM file, you open a file that has the table you are interested in, and read through the file sequentially starting with the first record and ending with the last record. The index points to the current record in the file (table). An example of an ISAM file might be a file of comma separated values (CSV), where each record in the file consists of a fixed number of fields.
Index {BOF} = 1 Record 1 Record 2 Record 3 Record 4 Record 5 Record 6 Record 7 Record 8 Index {EOF} = 9 Record 9 Record 1 = 00123, Joe, Sanborn, 382-184-2934, Manufacturing Record 2 = 01469, Kathy, Smith, 256-398-9387, Sales Record 3 = 03953, Kim, Jones, 287-934-9132, Admin Etc.

While ISAM file databases are simple and relatively inexpensive, they have many drawbacks and are only used for very simple applications. Mission critical applications (i.e. high reliability/uptime) generally use Client-Server Relational Database architecture such a Microsoft SQL Server.

InduSoft Web Studio

261

IWS Training Guide

Exercise: Using VBScript

Flat Database
The flat database is another simple data model where all required information is generally contained in one table. This type of database may contain additional tables that are usually unrelated to each other. The difference between the flat database and an ISAM file database is that the flat database can access data items in rows and columns, versus the ISAM file which sequentially accesses records. A flat database consists of a two-dimensional array of data elements. The columns represent values that are of the same data type, each column being a different type of information from another column. The rows are single entries that have columns related to one another. For example, a list of employees might be organized as follows: EmployeeID 00123 01469 03950 First Joe Kathy Kim Last Sanborn Smith Jones SSNum 382-184-2934 256-398-9387 287-934-9132 Department Manufacturing Sales Admin

The flat database model forms the basis for spreadsheets such as Microsoft Excel. Note that Excel, a spreadsheet application, includes limited database functions that can operate over a span of rows and columns. These functions include Average, Count, Max, Min, Sum, Product and Get. Although these database functions operate from within Excel and no external query can be made using these built-in functions, the Microsoft JET database engine supports Excel and will access Excel records to support SQL data access and queries. Using a flat database such as Excel with IWS allows simple storage, retrieval and updating of a simple table of information contained in 2-dimensional format (rows and columns). While this database model is simple, it is inefficient in memory utilization. As the number of entries in the database grows, the database size can quickly grown to a point where the file size and memory requirements become troublesome, not to mention the adverse impact on the time for data retrieval and queries. By comparison, a relational database stores data in multiple tables that have some logical connection to each other. The relational database model is much more efficient in terms of storage, retrieval and queries for larger amounts of storage.

262

InduSoft Web Studio

Exercise: Using VBScript

IWS Training Guide

Relational Database
Relational databases became popular in the 1980s. They were first defined by Dr. E.F. Codd of IBM in the late 1960s in an attempt to improve on the efficiency of the existing flat database model. Codd introduced 12 principles that defined a relational database. However, virtually no product that is marketed as a relational database follows all of his principles so the term relational database is somewhat generically used. Virtually all relational databases use SQL as the query language. Examples of relational databases include Microsoft Access, Microsoft SQL Server, Oracle, MySQL, and Sybase. A relational database allows for the definition of data structures, storage and retrieval operations and integrity constraints. Data is stored in a collection of tables that are organized in rows (records) and columns (fields). Each row in the table contains the same fields.

Each row in any given field (column) is of the same data type. The common data types supported by databases include text, number (integer), and data or datetime. Each database typically supports a variety of data types.
The six key properties of tables in a relational database are as follows: Entries in any given column are single valued Column values are of the same data type Each row is unique Each column has a unique name The sequence of the columns is insignificant The sequence of the rows is insignificant

Each table can have one or more keys which are columns in the table that contains a unique value for each row. These keys match values in columns of other tables, providing access to data that is contained in the selected row. Keys make the relational database work, and provide a controlled level of data redundancy. Each table has one primary key that appears again as the link (foreign key) in another table. Tables are linked together logically by a combination of the table names, the primary key value and the column name. The primary key can be an autonumber field. When columns in two different tables take values from the same set, a join operation can be performed to select related records in the two tables by matching values in those columns. Often, but not always, the columns will have the same name in both tables. For example, an "orders" table might contain customer-ID and product-code pairs, and a "products" table might contain product-code and price pairs so to calculate a given customer's bill you would sum the prices of all products ordered by that customer by joining on the product-code fields of the two tables. This can be extended to joining multiple tables on multiple fields. Because these relationships are only specified at retrieval time, relational databases are classed as dynamic database management system.

InduSoft Web Studio

263

IWS Training Guide

Exercise: Using VBScript

Central to relational databases are the concept of the Normal Form. This refers to the organization of data in the relational database. Normalization is the design process method to structure a relational database to be compliant with the Normal Form. Normalizing a database design leads to optimal database and application performance. Signs of a normalized database A greater number of narrow tables with fewer columns Fast sorting Few indexes per table Few null values, increasing data compactness Signs of a non-normalized database A few tables that are wide (more columns) Slower sortation speeds Several indexes per table Use of null values There are several levels of normalization, although most database designers stop at the 3rd level since it is usually quite efficient.
1 Normal Form (1NF) Reduce tables to the 1NF by: Eliminating duplicate columns from the same table. (i.e. every column must be single-valued) Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key). 2 Normal Form (2NF) Reduce the 1NF tables to 2NF by: Meeting all the requirements of the first normal form. Remove subsets of data that apply to multiple rows of a table and place them in separate tables. Create relationships between these new tables and their predecessors through the use of foreign keys. 3 Normal Form (3NF) Reduce the 2NF tables to 3NF by: Meeting all the requirements of the second normal form. Remove columns that are not dependant upon the primary key A table that is in the 3 normal form is also in the 1 and 2
rd st nd rd nd st

normal form.

264

InduSoft Web Studio

Exercise: Using VBScript

IWS Training Guide

Example of Normalizing a Database


Non-normalized database The data is organized with each record containing a particular Company/Division combination. Note that repeating groups of part and supplier related information occurs.
Suppliers and Parts By Company Division Company Company Company Division Founder Logo Allied Clock and Watch Horace Washington Supplier Country USA USA Mexico Mexico Belgium Belgium USA USA USA Italy Italy Luxembourg Germany Mexico Mexico Supplier Continent N. Amer. N. Amer. N. Amer. N. Amer. Europe Europe N. Amer. N. Amer. N. Amer. Europe Europe Europe Europe N. Amer. N. Amer.

Part Type Spring Pendulum Spring Toothed Wheel Quartz Crystal Tuning Fork Battery Flywheel Axle Axle Mechanical Arm Artificial Brain Artificial Brain Metal Housing Backplate

Supplier Tensile Globodynamics Tensile Globodynamics Pieza de Acero Pieza de Acero Microflux Microflux Dakota Electrics Wheels 4 Less Wheels 4 Less TransEuropa TransEuropa Prometheus Labs Frankenstein Labs Pieza de Acero Pieza de Acero

Sundial

Clocks

Allied Clock and Watch

Horace Washington

Sundial

Watches

Global Robot

Nils Neumann Gearbox

Industrial Robots

Global Robot

Nils Neumann Gearbox

Domestic Robots

InduSoft Web Studio

265

IWS Training Guide

Exercise: Using VBScript

1NF database The 1 Normalized Form eliminates the repeating groups. Now, each group will appear as its own record.
st

Suppliers and Parts By Company Division Company Company Company Founder Logo Allied Clock and Watch Allied Clock and Watch Allied Clock and Watch Allied Clock and Watch Allied Clock and Watch Allied Clock and Watch Allied Clock and Watch Global Robot Global Robot Global Robot Global Robot Global Robot Global Robot Global Robot Global Robot Horace Washington Horace Washington Horace Washington Horace Washington Horace Washington Horace Washington Horace Washington Nils Neumann Nils Neumann Nils Neumann Nils Neumann Nils Neumann Nils Neumann Nils Neumann Nils Neumann Sundial

Division

Part Type

Supplier Tensile Globodynamics Tensile Globodynamics Pieza de Acero Pieza de Acero

Supplier Country USA

Supplier Continent N. Amer.

Clocks

Spring

Sundial Sundial Sundial

Clocks Clocks Clocks

Pendulum Spring Toothed Wheel Quartz Crystal Tuning Fork Battery Flywheel Axle Axle Mechanical Arm Artificial Brain

USA Mexico Mexico

N. Amer. N. Amer. N. Amer.

Sundial

Watches

Microflux

Belgium

Europe

Sundial Sundial Gearbox Gearbox Gearbox Gearbox Gearbox Gearbox Gearbox Gearbox

Watches Watches Industrial Robots Industrial Robots Industrial Robots Industrial Robots Domestic Robots Domestic Robots Domestic Robots Domestic Robots

Microflux Dakota Electrics Wheels 4 Less Wheels 4 Less TransEuropa TransEuropa Prometheus Labs

Belgium USA USA USA Italy Italy Luxembourg Germany Mexico Mexico

Europe N. Amer. N. Amer. N. Amer. Europe Europe Europe Europe N. Amer. N. Amer.

Artificial Brain Frankenstein Labs Metal Housing Backplate Pieza de Acero Pieza de Acero

266

InduSoft Web Studio

Exercise: Using VBScript

IWS Training Guide

2NF database The 2 Normalized Form eliminates the repeating Company Founder and Company Logo details (and Supplier Countries and Continents for a given Supplier) by splitting this information into separate tables.
Suppliers and Parts By Company Division Company Allied Clock and Watch Allied Clock and Watch Allied Clock and Watch Allied Clock and Watch Allied Clock and Watch Allied Clock and Watch Allied Clock and Watch Global Robot Global Robot Global Robot Global Robot Global Robot Global Robot Global Robot Global Robot Companies Company Allied Clock and Watch Global Robot Company Founder Horace Washington Nils Neumann Company Logo Sundial Gearbox Division Clocks Clocks Clocks Clocks Watches Watches Watches Industrial Robots Industrial Robots Industrial Robots Industrial Robots Domestic Robots Domestic Robots Domestic Robots Domestic Robots Part Type Spring Pendulum Spring Toothed Wheel Quartz Crystal Tuning Fork Battery Flywheel Axle Axle Supplier Tensile Globodynamics Tensile Globodynamics Pieza de Acero Pieza de Acero Microflux Microflux Dakota Electrics Wheels 4 Less Wheels 4 Less TransEuropa
nd

Mechanical Arm TransEuropa Artificial Brain Artificial Brain Metal Housing Backplate Prometheus Labs Frankenstein Labs Pieza de Acero Pieza de Acero

Suppliers
Supplier Tensile Globodynamics Pieza de Acero Microflux Dakota Electrics Wheels 4 Less TransEuropa Prometheus Labs Frankenstein Labs Supplier Country USA Mexico Belgium USA USA Italy Luxembourg Germany Supplier Continent N. Amer. N. Amer. Europe N. Amer. N. Amer. Europe Europe Europe

InduSoft Web Studio

267

IWS Training Guide

Exercise: Using VBScript

3NF database The 3 Normalized Form eliminates the repeating Supplier Continent for a given Supplier Country by creating a separate table relating the Supplier Country to Supplier Continent.
Suppliers and Parts By Company Division Company Division Part Type Allied Clock and Watch Clocks Allied Clock and Watch Clocks Allied Clock and Watch Clocks Allied Clock and Watch Clocks Allied Clock and Watch Watches Allied Clock and Watch Watches Allied Clock and Watch Watches Global Robot Global Robot Global Robot Global Robot Global Robot Global Robot Global Robot Global Robot Companies Company Company Founder Company Logo Spring Pendulum Spring Supplier Tensile Globodynamics Tensile Globodynamics Pieza de Acero
rd

Toothed Wheel Pieza de Acero Quartz Crystal Tuning Fork Battery Microflux Microflux Dakota Electrics Wheels 4 Less Wheels 4 Less TransEuropa

Industrial Robots Flywheel Industrial Robots Axle Industrial Robots Axle

Industrial Robots Mechanical Arm TransEuropa Domestic Robots Artificial Brain Domestic Robots Artificial Brain Domestic Robots Metal Housing Domestic Robots Backplate Prometheus Labs Frankenstein Labs Pieza de Acero Pieza de Acero

Allied Clock and Watch Horace Washington Sundial Global Robot Nils Neumann Gearbox

Countries Country USA Mexico Belgium Italy Continent N. Amer. N. Amer. Europe Europe

Suppliers Countries Supplier Supplier Country

Tensile Globodynamics USA Pieza de Acero Microflux Dakota Electrics Wheels 4 Less TransEuropa Prometheus Labs Frankenstein Labs Mexico Belgium USA USA Italy Luxembourg Germany

Luxembourg Europe

Source: Wikipedia

268

InduSoft Web Studio

Exercise: Using VBScript

IWS Training Guide

The 5 Rules of Data Normalization

InduSoft Web Studio

269

IWS Training Guide

Exercise: Using VBScript

Estimating the size of a database (SQL Server 2000) http://msdn2.microsoft.com/en-us/library/aa933054(SQL.80).aspx

Types of Relational Databases


The flat database

2610

InduSoft Web Studio

Exercise: Using VBScript

IWS Training Guide

InduSoft Web Studio

2611

IWS Training Guide

Exercise: Using VBScript

2612

InduSoft Web Studio

Exercise: Using VBScript

IWS Training Guide

Source: www.marcrettig.com

InduSoft Web Studio

2613

Chapter 27.

Configuring the Database

The following information pertains to the initial configuration of various databases for use with IWS. However, the user should consult the respective database documentation for updated information

Microsoft Excel
The following information can be used to configure Microsoft Excel to support an IWS application:

Configuring Excel for use with IWS built-in Alarm, Event, Trend, and Grid Objects
For use with the IWS Alarm, Event, Trend and Grid Objects, you must have a pre-existing Excel file (*.xls). Excel (the application) need not be present on the same PC as the IWS runtime. The Alarm, Event and Trend Objects should be configured to automatically create their own Table (i.e. Worksheet) using the default table name (e.g. Trend001 for the first Trend Worksheet). The Grid Object can be used to display an existing Excel Table (Worksheet), so in this case the Excel Worksheet must be defined and populated with some data. The Grid Object can be used to change or add to this data. When specifying an Excel Worksheet, be sure to enclose the Worksheet name in square brackets and put a $ character following the Excel Worksheet name. Also be sure to disable the Primary Key when using Excel, Excel does not support Primary Keys (E.g. when configuring the default database, in the Default Database Configuration dialog box, click on the Advanced button and check the Disable Primary Keys checkbox. As an alternative to the above, in a script worksheet you can either: 1) Use a file command (IWS built-in file function or VBScript FileSystemObject) to copy and rename an existing (blank) Excel file for use with the IWS application. 2) Use Microsoft Office Automation to create an Excel file, define the Worksheets and populate the Worksheet with any necessary data. Note that this option required Microsoft Excel (the application) to be present on the same PC as the IWS application. 3) Using VBScript, use ADOX with the Microsoft Jet 4.0 ADO OLE-DB Provider to create a new instance of an Excel file, create one or more Tables (Worksheets) and define the Column data type.

Example of how to specify an Excel Worksheet

InduSoft Web Studio

271

IWS Training Guide

Configuring Excel for use with VBScript


Depending on how VBScript is going to use an Excel Worksheet, the Excel file or Worksheet does not need to pre-exist prior to running the VBScript application. To read existing data for an IWS application configuration, obviously an Excel Worksheet needs to pre-exist. But if an Excel Worksheet is to be used to store data from an IWS VBScript application, there are a few options: 1) Use Excel (the application) to create an empty Excel file with the Worksheets you need. Copy this file into your IWS application folder. 2) Use a file command (IWS built-in file function or VBScript FileSystemObject) to copy and rename an existing blank Excel file for use with the IWS application. 3) From VBScript, use ADOX with the Microsoft Jet 4.0 ADO OLE-DB Provider to create a new instance of an Excel file, create one or more Tables (Worksheets) and define the Column data type. 4) If you have an existing blank Excel file on your IWS runtime PC (e.g. in your application folder), you can use the SQL statement Create Table to create a table (Worksheet) and columns. E.g. Dim oConn, strConn, myFile Set oConn = CreateObject("ADODB.Connection") myFile = $GetAppPath() & "test.xls" strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & myfile &_ ";Extended Properties=""Excel 8.0;HDR=Yes""" mySQL = "Create Table MyTable " &_ "(LastName varchar, FirstName varchar, Address varchar, Age Int)" With oConn .Open strConn .execute mySQL End With oConn.close Set oConn=Nothing Note: The SQL Query is dependant on your ADO.NET Provider. Microsoft Excel may not be the best choice for real-time data storage. It only allows for single access and if there are frequent reads & writes, the Database may need compaction. When accessing an Excel file, in the SQL command you refer to a specific worksheet by the following syntax: [worksheetname$] When accessing an Excel spreadsheet with no Headers, be sure to do the following - Make sure the Connection string has HDR=No in the Extended Properties field. - In your SQL command (and Recordset Object), your refer to each column as Fx, where x is the column number (e.g. F1 for the first column, F2 for the second, etc.)

More information on using Jet SQL can be found at


http://msdn2.microsoft.com/en-us/library/aa140011(office.10).aspx

272

InduSoft Web Studio

IWS Training Guide

Microsoft Access
The following information can be used to configure Microsoft Access to support an IWS application:

Configuring Access for use with IWS built-in Alarm, Event, Trend, and Grid Objects
For use with the IWS Alarm, Event, Trend and Grid Objects, you must have a pre-existing Access Database (*.mdb file). Access (the application) need not be present on the same PC as the IWS runtime. The Alarm, Event and Trend Objects should be configured to automatically create their own Table using the default table name (e.g. Trend001 for the first Trend Worksheet). The Grid Object can be used to display an existing Access Table, so in this case the Access table must be defined and populated with some data. The Table Name can be obtained from the Database or specified manually using the Table name. The Grid Object can be used to change or add to this data. Unlike Microsoft Excel, Access support Primary Keys so Primary Keys should be enabled. As an alternative to the above, in a startup script you can either: 1) Use a file command (IWS built-in file function or VBScript FileSystemObject) to copy and rename an existing Access Database for use with the IWS application. 2) Use Microsoft Office Automation to create an Access Database, define the Database and populate the Worksheet with any necessary data. Note that this option required Microsoft Access (the application) to be present on the same PC as the IWS application. 3) Using VBScript, use ADOX with the Microsoft Jet 4.0 ADO OLE-DB Provider to create a new instance of an Access Database, create one or more Tables and define the Column data type.

Example of how to specify an Access Table

InduSoft Web Studio

273

IWS Training Guide

Configuring Access for use with VBScript


Depending on how VBScript is going to use an Access Table, the Access Table (*.mdb file) does not need to pre-exist prior to running the VBScript application. To read existing data for an IWS application configuration, obviously an Access Database and Table needs to pre-exist. But if an Access Database is to be used to store data from an IWS VBScript application, there are a few options: 1) Use Access (the application) to create an empty Access Database with the Table(s) you need. Copy this file into your IWS application folder. 2) Use a file command (IWS built-in file function or VBScript FileSystemObject) to copy and rename an existing blank Access database (*.mdb file) for use with the IWS application. 3) From VBScript, use ADOX with the Microsoft Jet 4.0 ADO OLE-DB Provider to create a new instance of an Access Database, create one or more Tables and define the Column data type. 4) If you have an existing blank Access file on your IWS runtime PC (e.g. in your application folder), you can use the SQL statement Create Table to create a table and columns. E.g. VBScript creating an Access Database with no Primary Key Dim strConn, myPath, oDB, Catalog Set Catalog = CreateObject("ADOX.Catalog") Set oDB = CreateObject("ADODB.Connection") myPath =$GetAppPath() & "test1.mdb" strConn="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & myPath & ";" Catalog.Create strConn 'Create new database Set Catalog = Nothing With oDB 'Connect to database and insert a new table .Open strConn .Execute "CREATE TABLE myTable &_ ([Name] text(50) WITH Compression, " &_ "[Address] text(150) WITH Compression, " & _ "[City] text(50) WITH Compression, " & _ "[State] text(2) WITH Compression, " & _ "[Zip] text(6) WITH Compression, " & _ "[Account] decimal(6))" End With Set oDB = Nothing VBScript creating an Access Database with a Primary Key Dim strConn, myPath, oDB, Catalog Set Catalog = CreateObject("ADOX.Catalog") Set oDB = CreateObject("ADODB.Connection") myPath =$GetAppPath() & "test1.mdb" strConn="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & myPath & ";" Catalog.Create strConn 'Create new database Set Catalog = Nothing With oDB 'Connect to database and insert a new table .Open strConn .Execute "CREATE TABLE myTable " &_ "([employeeName] char(15) Not Null, " &_ "[street] char(15), " &_ "[city] char(10), " &_ "primary key (employeeName));" End With

274

InduSoft Web Studio

IWS Training Guide

Note: The SQL Query is dependant on your ADO.NET Provider. Microsoft Access may not be the best choice for real-time data storage. While it allows for multiple user access, if there are frequent reads & writes the Database may need periodic compaction. When accessing an Access database, in the SQL command you refer to a specific Table by its name

More information on Microsoft Jet SQL can be found at


http://msdn2.microsoft.com/en-us/library/bb245488.aspx http://msdn2.microsoft.com/en-us/library/aa140011(office.10).aspx

InduSoft Web Studio

275

IWS Training Guide

Microsoft SQL Server 2005


SQL Server 2005 Types
Microsoft offers several versions of SQL Server 2005. These versions include: - Enterprise Edition (for high-end Enterprises) - Standard Edition (for Small to Medium-size organizations) - Workgroup Edition (for Small organizations ) - Express Edition (upgraded version of MSDE, for local database use) - Compact Edition (for light-weight mobile, embedded or desktop platform applications) The Enterprise Edition and Standard Edition support advanced features such as Database Mirroring and Failover Clustering. The Workgroup, Standard and Enterprise Editions include Business Intelligence (BI) Tools, as well as multiple CPUs with no limit on the Database size. Limitations of Express Edition and Compact Edition are: Feature # of CPUs RAM Database Size T-SQL Support Platforms .NET Framework Install Size Disk Install Size RAM Cost Express Edition Compact Edition 1 1 1 GB max 4 GB max 4 GB max Yes Subset XP, 2000, Server 2003, Vista XP, 2000, Server 2003, Vista, CE 2.0 2.0 197MB 1.8 MB 1.7 MB $0 $0

Downloading SQL Server 2005 Express Edition or Compact Edition


This section covers the installation and use of Microsoft SQL Server 2005 Express Edition or Compact Edition. These versions of Microsoft SQL Server 2005 are robust and reliable for use with many industrial applications and are available at no cost from Microsoft. The SQL Server 2005 Express Edition can be downloaded from Microsofts web site at: http://msdn.microsoft.com/vstudio/express/sql/download/ The SQL Server 2005 Compact Edition can be downloaded from Microsofts web site at: http://www.microsoft.com/sql/editions/compact/downloads.mspx Be sure to download SQL Server 2005 Management Studio Express which can be used for Database configuration. SQL Server 2005 Management Studio can be used with both SQL Server 2005 Express Edition and SQL Server 2005 Compact Edition. http://msdn.microsoft.com/vstudio/express/sql/download/

276

InduSoft Web Studio

IWS Training Guide

MySQL 5.0
The MySQL 5.0 database has become popular since it is open source software and is available at no cost under a GNU General Public License (GPL). It is widely used in Web-based applications and several industrial applications. From the MySQL web site (www.mysql.org), you can download the MySQL Database Server, an ODBC Driver and a MySQL Database Management tool. Presently, the MySQL website does not include an rd ADO.NET Provider for MySQL. 3 Party MySQL ADO.NET (OLE-DB) Providers are available from companies such as Cherry Hill Software (www.cherryhillsoftware.com), or you can use MyOLEDB (and ADO.NET OLE-DB Provider for MySQL **not officially supported by MySQL) found at http://sourceforge.net/projects/myoledb/.

Downloading MySQL 5.0


The MySQL 5.0 database can be downloaded from http://dev.mysql.com/downloads/mysql/5.0.html#win32 The MySQL ODBC 3.51 driver (Connector) can be downloaded from http://dev.mysql.com/downloads/connector/odbc/3.51.html The MySQL Administrator (GUI Tool) can be downloaded from http://dev.mysql.com/downloads/gui-tools/5.0.html The MyOLEDB ADO.NET OLE-DB Provider v3.9.6 can be downloaded from http://sourceforge.net/project/showfiles.php?group_id=148466

InduSoft Web Studio

277

IWS Training Guide

Oracle
The current version of Oracle is 10g Release 2, designed for Grid Computing. Previous versions wer 8i and 9i. Oracle 11g is announced but not yet available. Oracle 10g Release 2 Types
Oracle offers several versions of Oracle 10g. These versions include: - Enterprise Edition (large enterprises) - Standard Edition (medium sized business environments) - Standard Edition One (small to medium enterprise environments) - Express Edition (entry-level, small footprint database) The Express Edition is free to develop, deploy and distribute. Stores up to 4GB of user data, 1GB of RAM and supports 1 CPU. The Oracle Database 10g Release 2 Express Edition for Windows is located at: http://www.oracle.com/technology/software/products/database/xe/htdocs/102xewinsoft.html Download the Oracle Database 10g for Express Edition (Universal or Wester European Edition) OracleXE.exe or OracleXEUniv.exe Download the Oracle Database 10g Express Client OracleXEClient.exe http://www.oracle.com/technology/products/database/application_express/html/3.0.1_and_xe.html

278

InduSoft Web Studio

IWS Training Guide

PostgreSQL
PostgreSQL is another open-source database program. The main website is found at www.postgresql.org. This software is released under a BSD-style license compared to a GNU license commonly used for other open-sourced databases. The SQL language for PostgreSQL is called PL/pgSQL and closely resembles Oracles PL/SQL. Notes about PostgreSQL There is a FAQ listed at http://www.postgresql.org/docs/faqs.FAQ_windows.html Encoding Set to UTF-8 (UniCode). Works correctly for 8.2 PostgreSQL uses double quotes around strings Online documentation is at http://www.postgresql.org/docs/8.2/interactive/index.html Download the PostgreSQL 8.2.4.1 Database Program:
Go to http://www.postgresql.org/download/ Go to http://www.postgresql.org/ftp/binary/v8.2.4/win32/ , download the file postgresql-8.2.4-1.zip. Extract and install it. Must edit the pg_hba.conf file in the data directory to allow other host addresses other than local host to access the database. Then, need to restart PostgreSQL OLE-DB Provider http://pgfoundry.org/projects/oledb// click on PgOleDb v1.0.0.20 Follow the installation directions (install into C:/Windows and run REGSVR32). Also see http://www.mono-project.com/PostgreSQL When setting up the default database Data Source Database Server Name, or IP Address of your PC (or 127.0.0.1) Location Name of your database User Name The User Name you established when installing PostgreSQL Password The Password you established when installing PostgreSQL

InduSoft Web Studio

279

Chapter 28.

SQL The Language of Databases

Structured Query Language (SQL) is a standard computer language used to access and manipulate relational databases such as Microsoft Access, Microsoft SQL Server, Oracle, MySQL, etc. SQL is a declarative language (i.e. sequence of commands for the computer to perform), whereas languages such as C or Basic are imperative languages (i.e. a set of statements that change a program state). Although SQL is an ANSI standard language (ANSI SQL-92, SQL:1999, SQL:2003, SQL:2006) and a set of ISO standards, database manufacturers often provide proprietary extensions to the SQL language that are incompatible among different databases. So it is best to check the database documentation to determine the SQL commands that are supported. However, all databases support standard SQL keywords that allow: - running queries on the database, retrieving a set of records (a recordset) from the database - inserting new records into the database - deleting records from the database - updating records in the database The SQL Language is broken into three (3) groups of statements, each performing different types of functions. These are: 1. SQL Schema Statements This category of statements form the Data Definition Language (DDL) part of SQL. The DDL is used to manage the Data Objects that contain the data. Schema means a plan or model to the database. Example DDL statements include: Category Statements Function Schema CREATE TABLE Creates a table Schema DROP TABLE Deletes a table Schema ALTER TABLE Alter (change) a Table Schema CREATE INDEX Creates an Index (search key) Schema DROP INDEX Deletes an Index (search key) In an IWS application using the Alarm, Event, or Trend Objects, the built-in ADO.NET will use DDL statements to create the Tables required to store data, although an existing database must be created separately. 2. SQL Data Statements This category of statements form the Data Manipulation Language (DML) part of SQL. The DML is used to manage data within the database. For example, DML is used to extract, add, modify and delete information contained in the relational database tables. DML statements have no effect on the structure of the database. Example DML statements include: Category Data Data Data Data Statements SELECT INSERT DELETE UPDATE Function Extracts date from a database table Inserts date into a database table Deletes data from a database table Updates data in a database table

In an IWS application using the Alarm, Event, or Trend Objects, the built-in ADO.NET will use DML statements to retrieve, add and/or remove data from Tables. 3. SQL Transaction Statements The Transaction statements are generally used to perform actions on the database. These statements are often dependent on the database. Category Transaction Statements COMMIT Function Makes data modifications part of the database

InduSoft Web Studio

281

IWS Training Guide

SQL Nomenclature

SQL Nomenclature
The semicolon can be used to separate multiple SQL statements in databases that allow more than one SQL statement in a call to the database server. Some databases force you to put a semicolon at the end of a statement. This is not required for Microsoft Access or Microsoft SQL Server. The asterisk is used to select all Single quotes are used for text values, i.e. strings (most databases will support double quotes as well). Numeric values should not be enclosed in quotes Comments can be added to a SQL statement by using a double-dash (--), curly brackets (braces) or Cstyle /* comment */ (supports multi-line comments).

SQL Coding Conventions


As with any programming language, following standard coding conventions makes the code more readable to other users, as well as to you. With SQL, there are a few simple coding conventions: Use uppercase for all SQL Keywords If you must break a line of SQL code, do so at a major section of the SQL statement Example: Well-formatted SQL Code CREATE TABLE tblCustomers (CustomerID INTEGER NOT NULL, [Last Name] TEXT(50) NOT NULL, [First Name] TEXT(50) NOT NULL, Phone TEXT(10), Email TEXT(50)) Example: Poorly formatted SQL Code CREATE TABLE tblCustomers (CustomerID INTEGER NOT NULL, [Last Name] TEXT(50) NOT NULL, [First Name] TEXT(50) NOT NULL, Phone TEXT(10), Email TEXT(50))

282

InduSoft Web Studio

SQL Language Derivatives

IWS Training Guide

SQL Language Derivatives


Microsoft JET SQL The Microsoft JET Database Engine supports several Microsoft products including Access and Excel. The JET (Joint Engine Technology) 4.0 Engine supports Microsoft Access 2000, 2002 and 2003, as well as Excel and Delimited Text files. Microsoft Transact-SQL MySQL Oracle PL/SQL Postgres PL.pgSQL

Notes: When used with IWS, SQL Statements are typically enclosed in quotation marks and used with the Connection Object, Command Object or Recordset Object.

InduSoft Web Studio

283

IWS Training Guide

SQL Operators

SQL Operators
The ANI SQL-92 standard supports a number of basic operators. In addition, many relational databases support additional operators that are extensions to the ANSI-92 standard.

Arithmetic Operators
Arithmetic operators perform mathematical operations on two expressions of any of the data types of the numeric data type category. The plus (+) and minus (-) can also be used to perform arithmetic operations on datetime and smalldatetime values.
Operator Function Description

+ * / %

Add Subtract Multiply Divide Modulo

Adds two numbers Subtract one number from the other Multiply two numbers together Divide one number by the other Returns the integer remainder of a division. For example, 12 % 5 = 2 because the remainder of 12 divided by 5 is 2.

Assignment Operator
The assignment operator is used to set a SQL variable (with a proceeding @) to a value returned by an expression. It can also be used to establish the relationship between a column heading and the expression defining the values for the column.
Operator Function Description

Assignment

Can be used to assign a value (or result of an expression) to a variable, can also establish a relationship between a column heading and the expression defining the values for the column.

284

InduSoft Web Studio

SQL Operators

IWS Training Guide

Bitwise Operators
Bitwise operators perform bit manipulations between two expressions of any of the data types of the integer data type category.
Operator Function Description

&
| ^

Bitwise AND Bitwise OR Bitwise Exclusive OR

Bitwise AND (two operands). Bitwise OR (two operands). Bitwise exclusive OR (two operands).

The operands for bitwise operators can be any of the data types of the integer or binary string data type categories (except for the image data type), with the exception that both operands cannot be any of the data types of the binary string data type category. The table shows the supported operand data types.
Left operand binary bit int smallint tinyint varbinary Right operand int, smallint, or tinyint int, smallint, tinyint, or bit int, smallint, tinyint, binary, or varbinary int, smallint, tinyint, binary, or varbinary int, smallint, tinyint, binary, or varbinary int, smallint, or tinyint

Comparison Operators
Comparison operators test whether or not two expressions are the same. Comparison operators can be used on all expressions except expressions of the text, ntext, or image data types.
Operator Description

= > < >= <= <> != !< !>

Equal to Greater than Less than Greater than or equal to Less than or equal to Not equal to Not equal to (not SQL-92 standard) Not less than (not SQL-92 standard) Not greater than (not SQL-92 standard)

The result of a comparison operator has the Boolean data type, which has three values: TRUE, FALSE, and UNKNOWN. Expressions that return a Boolean data type are known as Boolean expressions. Unlike other SQL Server data types, a Boolean data type cannot be specified as the data type of a table column or variable, and cannot be returned in a result set.

InduSoft Web Studio

285

IWS Training Guide

SQL Operators

Null Handling
It should be noted that ANSI SQL-92 says that NULLS are unknown values. When SET ANSI_NULLS is ON (default setting), any comparison to a NULL is to fail (i.e. return False). E.g. NULL = NULL returns False NULL <> NULL returns False When SET ANSI_NULLS is OFF, the same rules apply, except that the statement: NULL = NULL returns True Use SQL statements such as Where ColumnName IS NULL But avoid using SQL statements such as Where ColumnName = Null Boolean Expressions Expressions with Boolean data types are used in the WHERE clause to filter the rows that qualify for the search conditions and in control-of-flow language statements such as IF and WHILE.

286

InduSoft Web Studio

SQL Operators

IWS Training Guide

Logical Operators
Logical operators test for the truth of some condition. Logical operators, like comparison operators, return a Boolean data type with a value of TRUE or FALSE.
Operator Description

ALL AND ANY

TRUE if all of a set of comparisons are TRUE. TRUE if both Boolean expressions are TRUE. TRUE if any one of a set of comparisons are TRUE.

BETWEEN TRUE if the operand is within a range. EXISTS IN LIKE NOT OR SOME TRUE if a subquery contains any rows. TRUE if the operand is equal to one of a list of expressions. TRUE if the operand matches a pattern. Reverses the value of any other Boolean operator. TRUE if either Boolean expression is TRUE. TRUE if some of a set of comparisons are TRUE.

Unary Operators
Unary operators perform an operation on only one expression of any of the data types of the numeric data type category.
Operator Function Description

+ ~

Positive Negative Bitwise NOT

Numeric value is positive. Numeric value is negative. Returns the ones complement of the number.

The + (Positive) and - (Negative) operators can be used on any expression of any of the data types of the numeric data type category. The ~ (Bitwise NOT) operator can be used only on expressions of any of the data types of the integer data type category.

String Concatenation Operator


The string concatenation operator allows string concatenation with the addition sign (+), which is also known as the string concatenation operator. All other string manipulation is handled through string functions such as SUBSTRING. By default, an empty string is interpreted as an empty string in INSERT or assignment statements on data of the varchar data type. In concatenating data of the varchar, char, or text data types, the empty string is interpreted as an empty string. For example, 'abc' + '' + 'def' is stored as 'abcdef'. However, if the sp_dbcmptlevel compatibility level setting is 65, empty constants are treated as a single blank character and 'abc' + '' + 'def' is stored as 'abc def'. When two character strings are concatenated, the collation of the result expression is set following the rules of collation precedence.

InduSoft Web Studio

287

IWS Training Guide

SQL Operators

Operator Precedence
When a complex expression has multiple operators, operator precedence determines the sequence in which the operations are performed. The order of execution can significantly affect the resulting value. Operators have these precedence levels. An operator on higher levels is evaluated before an operator on a lower level: + (Positive), - (Negative), ~ (Bitwise NOT) * (Multiply), / (Division), % (Modulo) + (Add), (+ Concatenate), - (Subtract), & (Bitwise AND) =, >, <, >=, <=, <>, !=, !>, !< (Comparison operators) ^ (Bitwise Exclusive OR), | (Bitwise OR) NOT AND ALL, ANY, BETWEEN, IN, LIKE, OR, SOME = (Assignment) When two operators in an expression have the same operator precedence level, they are evaluated left to right based on their position in the expression

288

InduSoft Web Studio

SQL Operators

IWS Training Guide

SQL Functions
An SQL function is a special type of command in the SQL language used to return a single value. There can be one or more input parameters, or there can be no input parameters that are required. These Functions are typically used with a DML Query Statement.

Aggregate Functions
Function AVG (column) COUNT(*) COUNT (column) COUNT (DISTINCT column) MIN(column n) MAX(column ) SUM(column) Usage Computes the average value of a column by the column Counts all rows in the specified table or view Counts the rows defined by the column Counts the number of distinct values of the column Finds the minimum value in a column from the column Finds the maximum value in a column from the column Computes the sum of column values from the column

Notes: The Functions AVG & SUM are not supported by all databases, but are supported by Microsoft Access, Microsoft SQL Server, Oracle, MySQL and PostgreSQL

Scalar Functions
Function UCASE(c) LCASE(c) MID(c,start[,end]) LEN(c) INSTR(c,char) LEFT(c,number_of_char) RIGHT(c,number_of_char) ROUND(c,decimals) MOD(x,y) NOW() FORMAT(c,format) DATEDIFF(d,date1,date2) Usage Converts a field to upper case Converts a field to lower case Extract characters from a text field Returns the length of a text field Returns the numeric position of a named character within a text field Return the left part of a text field requested Return the right part of a text field requested Rounds a numeric field to the number of decimals specified Returns the remainder of a division operation Returns the current system date Changes the way a field is displayed Used to perform date calculations

InduSoft Web Studio

289

IWS Training Guide

SQL Operators

DatePart() Function
The following syntax is used for the DatePart() SELECT DATEPART(Part, dateVariable) E.g. SELECT DATEPART(month, 2007-08-05) Part Year Quarter Month Dayofyear Day Week Weekday Hour Minute Second Millisecond Description returns a 4 digit year returns a value 1-4 representing the year's quarter returns the numeric equivalent month (1-12) returns the day of the year (1-365) returns the day of the month (1-31) returns the number of the week (1-53) returns the number of the day of the week (1-7) returns the number of hours for a given time returns the number of minutes from a given time returns the number of seconds in a given time returns the number of milliseconds in a given time {returns August} Abbreviation(s) yy,yyyy qq,q mm,m dy,y dd,d wk,ww dw hh mi,n ss,s ms

2810

InduSoft Web Studio

SQL Operators

IWS Training Guide

System Values
Function CURRENT_DATE CURRENT_TIME Usage Identifies the current date Identifies the current time

CURRENT_TIMESTAMP Identifies the current date and time CURRENT_USER SESSION_USER SYSTEM_USER Identifies the active database user as identified by the Database Server Identifies the currently active Authorization ID, if it differs from the user Identifies the currently active user within the host operating system

Notes: Every SQL database has its own version of date functions.

Common (but non-ANSI-92 Standard) Functions Function ABS(x) SIGN(x) MOD(x,y) FLOOR(x) CEILING(x) or CEIL(x) POWER(x,y) ROUND(x,d) SQRT(x) Usage Returns the absolute value of x Returns the sign of input x as -1, 0, or 1 (negative, zero, or positive respectively) Modulo - returns the integer remainder of x divided by y (same as x%y) Returns the largest integer value that is less than or equal to x Returns the smallest integer value that is greater than or equal to x Returns the value of x raised to the power of y Returns the value of x rounded to the number of decimal places specified by the value d Returns the square-root value of x

InduSoft Web Studio

2811

IWS Training Guide

SQL DataTypes

SQL DataTypes
SQL recognizes different types of data that generally fall into one of three groupings; numeric, character strings and other. The specific data types depends on the database used. For example, Microsoft SQL Server 2005 uses the following data types: Numeric
Category Data Type Description

Integer Integer Integer Integer Real Real decimal and numeric decimal and numeric bit Binary Strings Binary Strings Image

BIGINT INT SMALLINT TINYINT FLOAT REAL DECIMAL

Integer (whole number) data from -2^63 (-9,223,372,036,854,775,808) through 2^63-1 (9,223,372,036,854,775,807). Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647). Integer data from -2^15 (-32,768) through 2^15 - 1 (32,767). Integer data from 0 through 255. Floating precision number data with the following valid values: -1.79E + 308 through -2.23E - 308, 0 and 2.23E + 308 through 1.79E + 308. Floating precision number data with the following valid values: -3.40E + 38 through -1.18E - 38, 0 and 1.18E - 38 through 3.40E + 38. Fixed precision and scale numeric data from -10^38 +1 through 10^38 1

NUMERIC

Functionally equivalent to decimal.

BIT BINARY VARBINARY IMAGE

Integer data with either a 1 or 0 value. Fixed-length binary data with a maximum length of 8,000 bytes. Variable-length binary data with a maximum length of 8,000 bytes. Variable-length binary data with a maximum length of 2^31 - 1 (2,147,483,647) bytes. Monetary data values from -2^63 (-922,337,203,685,477.5808) through 2^63 - 1 (+922,337,203,685,477.5807), with accuracy to a ten-thousandth of a monetary unit. Monetary data values from -214,748.3648 through +214,748.3647, with accuracy to a ten-thousandth of a monetary unit. Date and time data from January 1, 1753, through December 31, 9999, with an accuracy of three-hundredths of a second, or 3.33 milliseconds.

money and MONEY smallmoney money and SMALLMONEY smallmoney


Date & Time Date & Time TimeStamp

DATETIME

SMALLDATETIME Date and time data from January 1, 1900, through June 6, 2079, with an accuracy of one minute. TIMESTAMP A database-wide unique number that gets updated every time a row gets updated.

2812

InduSoft Web Studio

SQL DataTypes

IWS Training Guide

Character Strings
Category Characters Characters Characters Unicode Unicode Data Type Description

CHAR VARCHAR TEXT NCHAR

Fixed-length non-Unicode character data with a maximum length of 8,000 characters. Variable-length non-Unicode data with a maximum of 8,000 characters. Variable-length non-Unicode data with a maximum length of 2^31 - 1 (2,147,483,647) characters. Fixed-length Unicode data with a maximum length of 4,000 characters.

NVARCHAR Variable-length Unicode data with a maximum length of 4,000 characters. sysname is a system-supplied user-defined data type that is functionally equivalent to nvarchar(128) and is used to reference database object names NTEXT Variable-length Unicode data with a maximum length of 2^30 - 1 (1,073,741,823) characters.

Unicode

Other
Category Data Type Cursor Misc. Table Unique Identifier Description

CURSOR SQL_VARIANT TABLE

A reference to a cursor. A data type that stores values of various SQL Server-supported data types, except text, ntext, timestamp, and sql_variant. A special data type used to store a result set for later processing .

UNIQUEIDENTIFIER A globally unique identifier (GUID). XML

Notes: The dataType of a field (column) is generally defined when the column is created in the table When the table is created, you often have the choice of allowing or disallowing NULL values. A NULL value means that nothing exists in the table field.

InduSoft Web Studio

2813

IWS Training Guide

Constraints and Keys

Constraints and Keys


Databases usually support multiple Constraint types, generally used to ensure the database integrity by also used for Query optimization. Domain Constraints apply to one or more columns (e.g. ensuring the data entered into the column conforms to the specified data type and any rules), while Entity Constraints apply to individual rows. One type of Constraint that we will use is a Primary Key Constraint. A Primary Key is a unique identifier of a row, its value must be unique to each row and cannot contain a NULL value. Primary Keys are the most important of all Keys and all Constraints. A table can have only one Primary Key. Primary Keys can be created as part of the Column definition in the CREATE TABLE statement or in the ALTER TABLE statement. The use of integer values as a Primary Key is highly recommended, as is the use of a Primary Key in every Table this is what makes a relational database work. A Foreign Key is used to ensure data integrity within a column, as well as create a relationship to another table. To use a Foreign key, you must define the table which the Foreign Key references, and the column in the referenced table.

Examples of creating Keys are:

Creating a Primary Key when creating a Table USE myDB CREATE TABLE EmployeeData (EmployeeID INT NOT NULL PRIMARY KEY, First VARCHAR(15), Last VARCHAR(20), Age int, City VARCHAR(20), State VARCHAR(20)) Creating a Primary Key when the Table already exists USE myDB ALTER TABLE Customers ADD CONSTRAINT CustomerID PRIMARY KEY (CustomerID) Creating a Foreign Key when creating the Table USE myDB CREATE TABLE Orders (OrderID INT NOT NULL PRIMARY KEY, CustomerID int FOREIGN KEY REFERENCES Customers (CustomerID), OrderDate smallDateTime NOT NULL, Item VARCHAR(20) ) Creating a Foreign Key when the Table already exists USE myDB ALTER TABLE Orders ADD CONSTRAINT CustomerID FOREIGN KEY (CustomerID) REFERENCES Customers (CustomerID)

2814

InduSoft Web Studio

DDL Schema Statements

IWS Training Guide

DDL Schema Statements


The DDL allows the user to define new tables, as well as columns and indexes to be used in the tables. Certain Database Engines support Database creation and deletion as well.

CREATE DATABASE
The CREATE DATABASE statement is used to create a new database in the Database Server. The syntax of this command is: CREATE DATABASE database_name

DELETE DATABASE
The DELETE DATABASE statement is used to delete an existing database in the Database Server. The syntax of this command is: DROP DATABASE database_name

Notes: Not all Database Servers support the CREATE DATABASE and DELETE DATABASE statements. Check with your database server documentation. Once you use the CREATE DATABASE statement, you must also use the CREATE TABLE statement.

InduSoft Web Studio

2815

IWS Training Guide

DDL Schema Statements

CREATE TABLE Statement


The CREATE TABLE statement is used to create a new table in the database. The basic form of the CREATE TABLE statement is CREATE TABLE tableName (columnName1 dataType [constraint], columnName2 dataType [constraint], columnName3 dataType [constraint], .......) [ ] = optional The datatype must correspond to the datatypes supported by the database you are using. Constraints are optional, and include: NULL Indicates the column value can be a null NOT NULL Indicates the column value cannot be a null PRIMARY KEY Unique identifier for each row. Must be a unique, non-Null value FOREIGN KEY Adds a foreign key constraint For example, suppose we wanted to create the table as shown below. Table: EmployeeInfo First Last John Smith Suzanne Collins Randall Carson Bill Gross Joanne Thomas Maryanne Lewis Walter Williams Karl Walters Erica Edwards Elroy Clinger Ginger Rogers ID 64230 62175 60748 52786 50768 68200 65891 68985 59732 69394 69710 Age 45 35 40 55 48 24 35 30 48 26 22 City Ann Arbor Dexter Ann Arbor Jackson Ann Arbor Plymouth Ann Arbor Sylvania Toledo Chelsea Ann Arbor State Michigan Michigan Michigan Michigan Michigan Michigan Michigan Ohio Ohio Michigan Michigan

The SQL code for creating this table is: CREATE TABLE EmployeeInfo (First VARCHAR(15), Last VARCHAR(20), ID NUMBER(5), Age NUMBER(3), City VARCHAR(20), State VARCHAR(20))

2816

InduSoft Web Studio

DDL Schema Statements

IWS Training Guide

Other examples of the CREATE TABLE statement include: CREATE TABLE tblCustomers (CustomerID INTEGER, [Customer Name] TEXT(50), Phone TEXT(10), Email TEXT(50))

CREATE TABLE tblCustomers (CustomerID INTEGER NOT NULL, [Customer Name] TEXT(50) NOT NULL, Phone TEXT(10), Email TEXT(50))

CREATE TABLE weekly_payroll (employee_id VARCHAR(10) PRIMARY KEY, total_hours INT NULL, hourly_rate MONEY NOT NULL,);

InduSoft Web Studio

2817

IWS Training Guide

DDL Schema Statements

TRUNCATE TABLE Statement


The TRUNCATE TABLE statement is used to get rid of all of the data in a table. However, this statement does not eliminate the table itself. The basic form of the TRUNCATE TABLE statement is: TRUNCATE TABLE tableName

2818

InduSoft Web Studio

DDL Schema Statements

IWS Training Guide

DROP TABLE Statement


The DROP TABLE statement is used to delete all rows in the database and the table definition from the database. The basic form of the DROP TABLE statement is DROP TABLE tableName

An example of the DROP TABLE statement is: DROP TABLE EmployeeInfo This will delete all records in the EmployeeInfo table and delete the table itself.

InduSoft Web Studio

2819

IWS Training Guide

DDL Schema Statements

ALTER TABLE Statement


The ALTER TABLE statement can be used to add and drop columns from a table, or to change the name or data type of a column. Adding a column ALTER TABLE tableName ADD columnName dataType For example: ALTER TABLE tblCustomers ADD CustomerCity VARCHAR(20) ALTER TABLE orders ADD order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL

Adding a unique column ALTER TABLE tableName ADD UNIQUE columnName dataType For example: ALTER TABLE tblCustomers ADD UNIQUE CustomerCity VARCHAR(20) Add a Constraint ALTER TABLE tableName ADD CONSTRAINT columnName DEFAULT defaultValue

Dropping a column ALTER TABLE tableName DROP columnName For example: ALTER TABLE tblCustomers DROP CustomerCity

Changing a column ALTER TABLE tableName CHANGE CHANGE columnName columnName1 dataType For example: ALTER TABLE tblCustomers CHANGE CustomerCity VARHAR(20) ALTER TABLE tblCustomers CHANGE CustomerCity City VARCHAR(20) NOT NULL AUTO_INCREMENT

Notes: Microsoft SQL Server supports the ALTER COLUMN clause instead of the CHANGE clause

2820

InduSoft Web Studio

DDL Schema Statements

IWS Training Guide

CREATE INDEX
An index can be used with an existing table to locate rows quickly and efficiently during queries. You can create an index on one or more columns in a table. Each index has its own name. There are two types of indexes; a Simple Index and a Unique Index. A simple index will allow duplicate index values, while a Unique Index will not. Unique Index CREATE UNIQUE INDEX indexName ON tableName (columnName) Simple Index CREATE INDEX indexName ON tableName (columnName)

DROP INDEX
The DROP INDEX statement is used to delete an existing Index in a table. The format of the DROP INDEX statement varies by the particular database used. DROP INDEX indexName ON tableName DROP INDEX tableName.indexName DROP INDEX indexName ALTER TABLE tableName DROP INDEX indexName For JET SQL (Access, Excel) For Microsoft SQL Server For Oracle For MySQL

Notes: Check your database documentation for the proper format of the DROP INDEX and CREATE INDEX statements. The DROP INDEX statement may not apply to indexes created by defining a PRIMARY KEY

InduSoft Web Studio

2821

IWS Training Guide

DML Query Statements

DML Query Statements


Queries are loosely defined as a set of SQL commands that perform a function against the database, generally returning a set of records (a Recordset) from the database or moving data to the database. To illustrate the operation of these queries, the following tables will be used Table: EmployeeInfo First Last John Smith Suzanne Collins Randall Carson Bill Gross Joanne Thomas Maryanne Lewis Walter Williams Karl Walters Erica Edwards Elroy Clinger Ginger Rogers Table: Orders CustomerID 0981 1035 0976 1985 0758 ID 64230 62175 60748 52786 50768 68200 65891 68985 59732 69394 69710 Age 45 35 40 55 48 24 35 30 48 26 22 City Ann Arbor Dexter Ann Arbor Jackson Ann Arbor Plymouth Ann Arbor Sylvania Toledo Chelsea Ann Arbor State Michigan Michigan Michigan Michigan Michigan Michigan Michigan Ohio Ohio Michigan Michigan

OrderDate 25-Aug-2007 16-Mar-2007 15-Jul-2007 08-Aug-2007 13-Jun-2007

Item Mug Stein Bottle Jar Lid

Qty 10 5 18 16 45

Price 40.80 120.80 36.00 48.32 4.50

Table: Customers CustomerID First 0758 Barry 0981 Jim 0976 Janis 1985 Elroy 0823 Claudio 1035 Donald 0911 Roberto 1022 Julia 0998 George 1164 Eddie 1511 Ginger

Last Piper Weber Cunningham Klinger Sanchez Graham Mendoza Mitchell Walker Schultz Dalton

City Phoenix Milwaukee Eugene Pittsburgh Cleveland Austin Chicago Fort Collins Tampa Atlanta Green Bay

State Arizona Wisconsin Oregon Pennsylvania Ohio Texas Illinois Colorado Florida Georgia Wisconsin

2822

InduSoft Web Studio

DML Query Statements

IWS Training Guide

SELECT Statement
The SELECT statement is probably the most commonly used DML Query statement and is used to query the database and return one or more records into a result set, typically stored in a ADO Recordset when using IWS. There are several forms of the SELECT statement but the basic form of the SELECT statement is SELECT [ALL | DISTINCT] column1 [, column2, .] FROM table1 [, table2,] [WHERE columnName OPERATOR value [AND|OR columnName Operator value]] [GROUP BY columnList] [HAVING conditions] [ORDER BY columnList [ASC | DESC]] [[LEFT | RIGHT | FULL] [OUTER | INNER] JOIN] [LIMIT value [OFFSET value]] [ ] = optional parameters or arguments The ALL and DISTINCT keywords are used to select all (ALL) records (the default) or only unique (DISTINCT) records from the specified table. Use of the DISTINCT keyword will cause all duplicate records to be ignore in the search result. This SELECT statement will return a set of records from the specified table that contains data from the columns specified. Instead of specifying a column name, you can use the asterick * character to select all columns. For example, the SELECT statement can be used as follows: SELECT First, Last FROM EmployeeInfo This will return the following set of records John Suzanne Randall Bill Joanne Maryanne Walter Karl Erica Elroy Ginger Smith Collins Carson Gross Thomas Lewis Williams Walters Edwards Clinger Rogers

In addition, there are a number of optional clauses that can be used to narrow the returned recordset to only the records of interest. These clauses include:

InduSoft Web Studio

2823

IWS Training Guide

DML Query Statements

A. WHERE clause
The WHERE clause specifies the data values or rows that will be returned based on the criteria specified following in the WHERE clause. The syntax of the SELECT statement when using the WHERE clause is: SELECT column1 [, column2, .] FROM tableName WHERE columnName OPERATOR value [AND|OR columnName Operator value] Conditional Operator selections in the WHERE clause are: = Equal > Greater than < Less than >= Greater than or equal <= Less than or equal <> Not equal to != Not equal to LIKE Pattern Matching Use of the AND | OR allows two or more conditions to be used in a WHERE clause. The LIKE pattern matching operator allows you to retrieve selected rows that match a string or match a portion of a string. The percent sign % can be used as a wild card character to allow a match to any possible combination of character(s) before or after the character(s) specified. This example uses the SELECT statement with the WHERE clause to find employees in a City: SELECT * FROM EmployeeInfo WHERE City=Ann Arbor This will return the following set of records John Randall Joanne Walter Ginger Smith Carson Thomas Williams Rogers 64230 60748 50768 65891 69710 45 40 48 35 22 Ann Arbor Ann Arbor Ann Arbor Ann Arbor Ann Arbor Michigan Michigan Michigan Michigan Michigan

This example uses the SELECT statement with the WHERE clause to find employees older than 45: SELECT * FROM EmployeeInfo WHERE Age >=45 This will return the following set of records John Bill Joanne Erica Smith Gross Thomas Edwards 64230 52786 50768 59732 45 55 48 48 Ann Arbor Jackson Ann Arbor Toledo Michigan Michigan Michigan Ohio

This example finds employees in a City older than 25 and sorts by the employee first name: SELECT * FROM EmployeeInfo WHERE City=Ann Arbor AND Age > 25 ORDER BY First ASC

2824

InduSoft Web Studio

DML Query Statements

IWS Training Guide

This will return the following set of records Joanne John Randall Walter Thomas Smith Carson Williams 50768 64230 60748 65891 48 45 40 35 Ann Arbor Ann Arbor Ann Arbor Ann Arbor Michigan Michigan Michigan Michigan

This example is a slight modification of the previous example, showing only the columns of interest: SELECT First, Last, City, State FROM EmployeeInfo WHERE (City=Ann Arbor) AND (Age > 25) ORDER BY First ASC This will return the following set of records Joanne John Randall Walter Thomas Smith Carson Williams Ann Arbor Ann Arbor Ann Arbor Ann Arbor Michigan Michigan Michigan Michigan

Notes: You can use parentheses around the conditional expressions to make them easier to read, but they are not required.

This example returns a sorted list, first by state in ascending order, then by city in ascending order. SELECT * FROM EmployeeInfo ORDER BY State ASC, City ASC This will return the following set of records John Randall Joanne Walter Ginger Elroy Suzanne Bill Maryanne Karl Erica Smith Carson Thomas Williams Rogers Clinger Collins Gross Lewis Walters Edwards 64230 60748 50768 65891 69710 69394 62175 52786 68200 68985 59732 45 40 48 35 22 26 35 55 24 30 48 Ann Arbor Ann Arbor Ann Arbor Ann Arbor Ann Arbor Chelsea Dexter Jackson Plymouth Sylvania Toledo Michigan Michigan Michigan Michigan Michigan Michigan Michigan Michigan Michigan Ohio Ohio

This example returns a set of records where the first name starts with a J SELECT First, Last FROM EmployeeInfo WHERE First LIKE =J% This will return the following set of records John Joanne Smith Thomas

InduSoft Web Studio

2825

IWS Training Guide

DML Query Statements

Notes: Depending on your database server, various wildcard characters may be available for use with the LIKE clause: Wildcard _ (underscore) % [ ] [^] Description Matches any single character Matches a string of one or more characters Matches any single character withing the specified range (e.g. [a-f] ) Matches any single character not in the specified range (e.g. [^a-f])

2826

InduSoft Web Studio

DML Query Statements

IWS Training Guide

B. WHERE clause with BETWEEN conditional operator The WHERE clause can use the conditional operator BETWEEN or NOT BETWEEN to test if a column value is between a range of values. The syntax of the SELECT statement when using the WHERE clause with the BETWEEN conditional operator is: SELECT column1 [, column2, .] FROM tableName WHERE column3 BETWEEN value1 AND value2 For example, SELECT First, Last, City, State FROM EmployeeInfo WHERE Age BETWEEN 30 AND 50 ORDER BY State ASC, City ASC This will return the following set of records John Randall Joanne Walter Suzanne Bill Karl Erica Smith Carson Thomas Williams Collins Gross Walters Edwards 64230 60748 50768 65891 62175 52786 68985 59732 45 40 48 35 35 55 30 48 Ann Arbor Ann Arbor Ann Arbor Ann Arbor Dexter Jackson Sylvania Toledo Michigan Michigan Michigan Michigan Michigan Michigan Ohio Ohio

InduSoft Web Studio

2827

IWS Training Guide

DML Query Statements

B. WHERE clause with IN


The WHERE clause can use the conditional operator IN or NOT IN to test if a column value is in a membership. The syntax of the SELECT statement when using the WHERE clause with the IN conditional operator is: SELECT column1 [, column2, .] FROM tableName WHERE column3 IN (lisfOfValues) For example, SELECT * FROM EmployeeInfo WHERE City IN (Ann Arbor, Dexter) This will return the following set of records John Suzanne Randall Joanne Walter Ginger Smith Collins Carson Thomas Williams Rogers 64230 62175 60748 50768 65891 69710 45 35 40 48 35 22 Ann Arbor Dexter Ann Arbor Ann Arbor Ann Arbor Ann Arbor Michigan Michigan Michigan Michigan Michigan Michigan

2828

InduSoft Web Studio

DML Query Statements

IWS Training Guide

C. AS clause The AS clause can be used as an alias for either a column or a table. The syntax for using the AS clause is: SELECT column {example using a column alias} AS columnAlias FROM tableName SELECT column FROM tableName AS tableAlias {example using a table alias}

InduSoft Web Studio

2829

IWS Training Guide

DML Query Statements

D. CASE clause The CASE clause is part of T-SQL and other databases SQL language. The CASE clause can be used with the SELECT statement. The syntax of the SELECT statement when using the CASE clause is: SELECT column1, . CASE expression WHEN value1 THEN result1 WHEN value2 THEN result2 ELSE elseResult END FROM tableName Alternatively, you can use the following syntax: SELECT column1, . CASE WHEN booleanExpression1 THEN result1 WHEN booleanExpression2 THEN result2 ELSE elseResult END FROM tableName For example, suppose we want to determine the tax code to be used based on the state the employee lives in. E.g. if the employee lives in Michigan, their tax code is M-1099, while in Ohio is O-1099. The SQL code would be: SELECT * (CASE WHEN State = Michigan THEN M-1099 WHEN State = Ohio THEN O-1099 END) AS TaxCode FROM EmployeeInfo The result would be as shown below. Note that the output column is named TaxCode and is part of the resulting recordset, but is not part of the database table at this point. First John Suzanne Randall Bill Joanne Maryanne Walter Karl Erica Elroy Ginger Last Smith Collins Carson Gross Thomas Lewis Williams Walters Edwards Clinger Rogers ID 64230 62175 60748 52786 50768 68200 65891 68985 59732 69394 69710 Age 45 35 40 55 48 24 35 30 48 26 22 City Ann Arbor Dexter Ann Arbor Jackson Ann Arbor Plymouth Ann Arbor Sylvania Toledo Chelsea Ann Arbor State Michigan Michigan Michigan Michigan Michigan Michigan Michigan Ohio Ohio Michigan Michigan TaxCode M-1099 M-1099 M-1099 M-1099 M-1099 M-1099 M-1099 O-1099 O-1099 M-1099 M-1099

Alternatively, the SQL code could be written as follows:: SELECT * TaxCode = CASE WHEN State = Michigan THEN M-1099 WHEN State = Ohio THEN O-1099 END FROM EmployeeInfo

2830

InduSoft Web Studio

DML Query Statements

IWS Training Guide

E. GROUP BY clause The GROUP BY clause is used to gather all rows that contain data in the specified column(s) and will allow SQL aggregate functions to be performed on the specified columns. The syntax of the SELECT statement when using the GROUP BY clause is: SELECT column1, Function (column2), Function (column3) FROM tableName GROUP BY column1 [HAVING Function (column2) condition value] [ORDER BY columnList [ASC | DESC]] The following example will determine the oldest employee in each city SELECT MAX(Age), City FROM employeeInfo GROUP BY City ORDER BY City The result is 48 26 35 55 24 30 48 Ann Arbor Chelsea Dexter Jackson Plymouth Sylvania Toledo

The following example will select by City the total number of employees per city and the maximum age SELECT City, COUNT(City), MAX(Age) FROM employeeinfo GROUP BY City ORDER BY City The result is Ann Arbor Chelsea Dexter Jackson Plymouth Sylvania Toledo 5 1 1 1 1 1 1 48 26 35 55 24 30 48

The following example uses the optional HAVING Function clause SELECT City, COUNT(City), MAX(Age) FROM employeeinfo GROUP BY City HAVING MAX(Age) > 40 ORDER BY City The result is Ann Arbor Jackson 5 1 48 55

InduSoft Web Studio

2831

IWS Training Guide

DML Query Statements

F. INTO clause The INTO clause is used to create backup copies of table. The syntax of the SELECT statement when using the INTO clause is: SELECT column1 [, column2, .] INTO newTableName FROM tableName Notes: You can use the asterick character (*) as a wildcard to select all columns.

2832

InduSoft Web Studio

DML Query Statements

IWS Training Guide

G. Using the SELECT statement with SQL Functions The SELECT statement can also be used with the SQL Aggregate Functions. Some examples are: SELECT AVG(Age) FROM EmployeeInfo {returns single value average age of employees from table}

SELECT AVG(Age) {returns average age of employees who live in Ann Arbor} FROM EmployeeInfo WHERE City = Ann Arbor SELECT COUNT(*) FROM EmployeeInfo SELECT COUNT(City) FROM EmployeeInfo {returns number of employee records}

{returns number of employee records that have a City value}

SELECT DATE(CURRENT_TIMESTAMP) SELECT TIME(CURRENT_TIMESTAMP)

{returns the date} {returns the time} {returns a numeric value 1-7} {returns a numeric value 1-31} {returns a numeric value 1-365} {returns month name Jan-Dec} {returns name of day Sunday-Saturday} {returns number of week 1-53} {returns August}

SELECT DAYOFWEEK(CURRENT_TIMESTAMP) SELECT DAYOFMONTH(CURRENT_TIMESTAMP) SELECT DAYOFYEAR(CURRENT_TIMESTAMP) SELECT MONTHNAME(CURRENT_TIMESTAMP) SELECT DAYNAME(CURRENT_TIMESTAMP) SELECT DAYNAME(CURRENT_TIMESTAMP) SELECT MONTHNAME(2007-08-05)

InduSoft Web Studio

2833

IWS Training Guide

DML Query Statements

H. JOIN Clause
Table joins make relational databases work, linking together two or more tables in a SELECT statement to obtain a single query result set. In the SELECT statement, you must specify the tables to be used and the primary key to be used to link the tables together. The syntax of the JOIN clause is: SELECT column1 [, column2, .] FROM table1 INNER JOIN table2 ON table1.keyField OPERATOR table2.keyField The syntax shown above is compliant with ANSI SQL-92. However, most databases support the alternative format: SELECT column1 [, column2, .] FROM table1, table2, . WHERE columnName OPERATOR value The benefits of database normalization were discussed in the Database chapter. These benefits include the reduction of repeating data. The linkage of the normalized tables in accomplished through the Join. Consider the headers in our sample tables Orders and Customers. The CustomerID primary key is what is used to link these tables together. Table: Orders CustomerID OrderDate Item Qty Price

Table: Customers CustomerID First Last City State

For example, if you wanted to obtain the records that indicate the customers name and what items they purchased, you could use the following SQL statement: SELECT Customers.First, Customers.Last, Orders.Item FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID The result will be: First Barry Jim Janis Elroy Donald Last Piper Weber Cunningham Klinger Graham Item Lid Mug Bottle Jar Stein

This type of a join is called an Inner Join and is the most common type of a Join. The result of executing this code will be a set of records that show the customer first name, last name and the item(s) ordered by the customer. The alternative form of the Inner Join clause for this example is: SELECT Customers.First, Customers.Last, Orders.Item FROM Customers, Orders WHERE Customers.CustomerID = Orders.CustomerID

2834

InduSoft Web Studio

DML Query Statements

IWS Training Guide

If you wanted to find out the names of the customers who ordered a particular product, for instance a Stein, you could accomplish this through the following SQL code: SELECT Customers.First, Customers.Last, Orders.Item FROM Customers, Orders WHERE Customers.CustomerID = Orders.CustomerID AND orders.item = Stein In addition to the INNER JOIN, the other types of Joins available are a LEFT JOIN and a RIGHT JOIN. The LEFT JOIN returns alls rows to the left of the conditional (i.e. the first table) even if there is no right column (i.e. the second table) to match. An example of a LEFT JOIN is: SELECT Customers.First, Customers.Last, Orders.Item FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID The result is: First Barry Jim Janis Elroy Claudio Donald Roberto Julia George Eddie Ginger Last Piper Weber Cunningham Klinger Sanchez Graham Mendoza Mitchell Walker Schultz Dalton Item Lid Mug Bottle Jar NULL Stein NULL NULL NULL NULL NULL

The RIGHTJOIN returns alls rows to the right of the conditional (i.e. the second table) even if there is no left column match (i.e. from the first table). SELECT Customers.First, Customers.Last, Orders.Item FROM Customers RIGHT JOIN Orders ON Customers.CustomerID = Orders.CustomerID The result is First Jim Donald Janis Elroy Barry Last Weber Graham Cunningham Klinger Piper Item Mug Stein Bottle Jar Lid

Notes: The column name should contain the table name followed by a period followed by the column name. While this syntax (of including the table name followed by a period) is not necessarily required, it is a good idea to use this syntax so that column names do not get confused. Types of Joins are Inner Join, Outer Join, Left Join and Right Join The Join Query does not alter either data table, it simply combines the data from each table into one result recordset that can be viewed or manipulated.

InduSoft Web Studio

2835

IWS Training Guide

DML Query Statements

I. Union Clause
The UNION clause places to separate queries together to form one result recordset. The two tables must have columns (those with the same column name) that have the same data type. The form of the UNION clause is: SQL Statement 1 UNION SQL Statement 2 For example, suppose we have our table of Employees broken into two separate tables, one for each plant: Table: Plant1EmployeeInfo First Last John Smith Suzanne Collins Randall Carson Bill Gross Joanne Thomas Table: Plant2EmployeeInfo First Maryanne Walter Karl Erica Elroy Ginger Last Lewis Williams Walters Edwards Clinger Rogers ID 68200 65891 68985 59732 69394 69710 Age 24 35 30 48 26 22 City Plymouth Ann Arbor Sylvania Toledo Chelsea Ann Arbor State Michigan Michigan Ohio Ohio Michigan Michigan ID 64230 62175 60748 52786 50768 Age 45 35 40 55 48 City Ann Arbor Dexter Ann Arbor Jackson Ann Arbor State Michigan Michigan Michigan Michigan Michigan

By using the UNION clause, we can get a list employees from both plants returned in one result set (Recordset). With the UNION clause, these will automatically be distinct values. SELECT First, Last FROM Plant1EmployeeInfo UNION SELECT First, Last FROM Plant2EmployeeInfo The result set will be: John Suzanne Randall Bill Joanne Maryanne Walter Karl Erica Elroy Ginger Smith Collins Carson Gross Thomas Lewis Williams Walters Edwards Clinger Rogers

You can also use the UNION ALL clause but by doing so, you will select all values, even if they are not distinct.

2836

InduSoft Web Studio

DML Query Statements

IWS Training Guide

INSERT Statement
The INSERT statement is used to insert (add) a row of data into the table. The basic form of the INSERT statement is INSERT INTO tableName (firstColumn, .., lastColumn) VALUES (firstValue, .., lastValue) For example, if we wanted to insert a new record into the INSERT INTO EmployeeInfo (First, Last, ID, Age, City, State) VALUES (Kim, Fitzgerald, 69459, 35, Ann Arbor, Michigan) The result would be: John Suzanne Randall Bill Joanne Maryanne Walter Karl Erica Elroy Ginger Kim Smith Collins Carson Gross Thomas Lewis Williams Walters Edwards Clinger Rogers Fitzgerald 64230 62175 60748 52786 50768 68200 65891 68985 59732 69394 69710 69459 45 35 40 55 48 24 35 30 48 26 22 35 Ann Arbor Dexter Ann Arbor Jackson Ann Arbor Plymouth Ann Arbor Sylvania Toledo Chelsea Ann Arbor Ann Arbor Michigan Michigan Michigan Michigan Michigan Michigan Michigan Ohio Ohio Michigan Michigan Michigan

Notes: All strings should be enclosed between single quotes: string

InduSoft Web Studio

2837

IWS Training Guide

DML Query Statements

UPDATE Statement
The UPDATE statement is used to update (change) a record or set of records to match the specified criteria. The basic form of the UPDATE statement is UPDATE tableName SET columnName = newValue [,columnName2 = newValue2, ..] WHERE columnName OPERATOR value [and|or columnName Operator value] [ ] = optional

For example, if we wanted to update a record in the EmployeeInfo table UPDATE EmployeeInfo SET Age = Age+1 WHERE First=John AND Last=Smith John Suzanne Randall Bill Joanne Maryanne Walter Karl Erica Elroy Ginger Smith Collins Carson Gross Thomas Lewis Williams Walters Edwards Clinger Rogers 64230 62175 60748 52786 50768 68200 65891 68985 59732 69394 69710 46 35 40 55 48 24 35 30 48 26 22 Ann Arbor Dexter Ann Arbor Jackson Ann Arbor Plymouth Ann Arbor Sylvania Toledo Chelsea Ann Arbor Michigan Michigan Michigan Michigan Michigan Michigan Michigan Ohio Ohio Michigan Michigan

This example shows updating multiple columns in a record. UPDATE EmployeeInfo SET City=Maumee, State=Ohio WHERE First=John AND Last=Smith John Suzanne Randall Bill Joanne Maryanne Walter Karl Erica Elroy Ginger Smith Collins Carson Gross Thomas Lewis Williams Walters Edwards Clinger Rogers 64230 62175 60748 52786 50768 68200 65891 68985 59732 69394 69710 45 35 40 55 48 24 35 30 48 26 22 Maumee Dexter Ann Arbor Jackson Ann Arbor Plymouth Ann Arbor Sylvania Toledo Chelsea Ann Arbor Ohio Michigan Michigan Michigan Michigan Michigan Michigan Ohio Ohio Michigan Michigan

Notes: To update a DateTime field, you can use the following syntax: Update tableName Set Date = 2007-08-02 12:30:00 Where Name=Joe Frederick

2838

InduSoft Web Studio

DML Query Statements

IWS Training Guide

The CASE clause can also be used with the UPDATE statement. In a previous example using the SELECT statement with the CASE clause, we looked at the employee state and created a result column indicating the tax code form to be used. Note that this result field was in the returned recordset, it was not updated in the database. If we wanted to perform a similar operation but update the database with the result, we could create a column named TaxForm that would initially be set to NULL (i.e. no valid value assigned).

First John Suzanne Randall Bill Joanne Maryanne Walter Karl Erica Elroy Ginger

Last Smith Collins Carson Gross Thomas Lewis Williams Walters Edwards Clinger Rogers

ID 64230 62175 60748 52786 50768 68200 65891 68985 59732 69394 69710

Age 45 35 40 55 48 24 35 30 48 26 22

City Ann Arbor Dexter Ann Arbor Jackson Ann Arbor Plymouth Ann Arbor Sylvania Toledo Chelsea Ann Arbor

State Michigan Michigan Michigan Michigan Michigan Michigan Michigan Ohio Ohio Michigan Michigan

TaxForm NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL

Then, we would execute the following SQL code: UPDATE EmployeeInfo SET TaxForm = Case WHEN State = Michigan THEN M-1099 WHEN State = Ohio THEN O-1099 END The result would be that the database would be updated to the following values in the EmployeeInfo table: First John Suzanne Randall Bill Joanne Maryanne Walter Karl Erica Elroy Ginger Last Smith Collins Carson Gross Thomas Lewis Williams Walters Edwards Clinger Rogers ID 64230 62175 60748 52786 50768 68200 65891 68985 59732 69394 69710 Age 45 35 40 55 48 24 35 30 48 26 22 City Ann Arbor Dexter Ann Arbor Jackson Ann Arbor Plymouth Ann Arbor Sylvania Toledo Chelsea Ann Arbor State Michigan Michigan Michigan Michigan Michigan Michigan Michigan Ohio Ohio Michigan Michigan TaxForm M-1099 M-1099 M-1099 M-1099 M-1099 M-1099 M-1099 O-1099 O-1099 M-1099 M-1099

Here is another example of the Update Statement: UPDATE EmployeeInfo SET Age = 55, date = "2007-08-02 16:21:00" WHERE First = Joan AND Last=Smith

InduSoft Web Studio

2839

IWS Training Guide

DML Query Statements

DELETE Statement
The DELETE statement is used to delete a record or set of records from the table where certain criteria are met. The basic form of the DELETE statement is DELETE FROM tableName [WHERE columnName OPERATOR value [and|or columnName Operator value]] [ ] = optional

Note that the DELETE FROM tableName form of this statement without any criteria will delete the entire table. For example, if we wanted to delete an employee from the EmployeeInfo table DELETE FROM EmployeeInfo WHERE First=John AND Last=Smith

Suzanne Randall Bill Joanne Maryanne Walter Karl Erica Elroy Ginger

Collins Carson Gross Thomas Lewis Williams Walters Edwards Clinger Rogers

62175 60748 52786 50768 68200 65891 68985 59732 69394 69710

35 40 55 48 24 35 30 48 26 22

Dexter Ann Arbor Jackson Ann Arbor Plymouth Ann Arbor Sylvania Toledo Chelsea Ann Arbor

Michigan Michigan Michigan Michigan Michigan Michigan Ohio Ohio Michigan Michigan

Notes: When the DELETE FROM statement is used without any criteria, it will delete the entire table E.g. DELETE FROM tableName

2840

InduSoft Web Studio

JET SQL

IWS Training Guide

JET SQL
Microsoft created a version of SQL designed to support Microsoft Access and Excel. It is implemented as part of an OLE-DB Provider. JET is different that other versions of SQL. It cannot create a database and it cannot manage database security. When using JET SQL with ADO, you can use ADOX (ADO Extensions) to create an Excel file (and spreadsheet), or an Access database. Use with Microsoft Excel When using JET SQL with an Excel spreadsheet, you need be sure to enclose the Worksheet name in square brackets, followed by a $. Some examples are: SELECT * FROM [Sheet1$] SELECT * FROM [MyNamedRange] SELECT * FROM [Sheet1$A1:B10] INSERT INTO [Sheet1$] (F1, F2) VALUES (111, ABC) CREATE TABLE Sheet1 (F1 char(255), F2 char(255)) Creating a Primary Key Excel does not support a Primary Key. To create a Primary Key in Access, you can use the following example: CREATE TABLE Orders (OrderID INTEGER CONSTRAINT PK_OrderID PRIMARY KEY, CustomerID INTEGER NOT NULL CONSTRAINT FK_CustomerID REFERENCES Customers (CustomerID), Item VarChar(20), OrderDate DATETIME, Amount CURRENCY) More on Microsoft Jet http://en.wikipedia.org/wiki/Microsoft_Jet (see section on locking) http://support.microsoft.com/default.aspx/kb/275561/en http://support.microsoft.com/default.aspx/kb/288631 Compaction

InduSoft Web Studio

2841

IWS Training Guide

Transact-SQL

Transact-SQL
Microsoft provides a proprietary extension to the SQL language called Transact-SQL, abbreviated as T-SQL. TSQL is implemented in Microsofts SQL Server. A complete overview of T-SQL is beyond the scope of these materials. Additional information on T-SQL can be found on the Microsoft MSDN website.

T-SQL Functions (subset) Function Create Database Create Table Create User Create Index Drop Database Drop Table If <condition> Then <statement> If <condition> Then <statement> Else <statement. Description Creates a new database and the files used to store the database. Creates a new Table Creates a new User Creates a Column Index Removes a database Removes a Table Conditional processing Conditional process

Example VBScript to create a blank database using T-SQL Dim oConn Set oConn=CreateObject("ADODB.Connection") strProv="Provider=SQLOLEDB.1; Integrated Security=SSPI; &_ Data Source=john-3a54d3da82\sqlexpress" oConn.Open strProv oConn.Execute "Create Database myNewDB"

Notes: T-SQL is a set of proprietary extensions for Microsoft SQL Server You can use T-SQL to create a new Catalog or delete a Catalog from VBScript More information on T-SQL can be found at http://msdn2.microsoft.com/en-us/library/ms178613.aspx

For more information on T-SQL http://www.devguru.com/technologies/t-sql/home.asp

2842

InduSoft Web Studio

Examples using a SQL Query with IWS Tags

IWS Training Guide

Examples using a SQL Query with IWS Tags


Command Object with Execute using IWS Tags & VBScript variables with SQL Dim oConn, oCmd, strSql Set oConn = CreateObject(ADODB.Connection) Set oCmd = CreateObject(ADODB.Command) oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & $GetAppPath()& "myDB.mdb" StrSql = $ID_Insert & ", '" & $Name_Insert & "', '"& $Address_Insert & "'" cmd.CommandText = "INSERT into Table1 (ID, Name, Address) values ("&StrSql&")" Set oRs=cmd.Execute The VBScript variable needs to be enclosed in the following order: - a single quote - a double quote - an ampersand - the VBScript variable - an ampersand - a double quotation - a single quotation In addition, parentheses or additional double quotes may be required, depending on how the SQL string is built. The following is another sample application: The following just instantiates the objects and opens them Set con = CreateObject("ADODB.Connection") Set cmd = CreateObject("ADODB.Command") strPathToMDB = "C:\Demo.MDB" strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & strPathToMDB & ";" con.Open strConn cmd.ActiveConnection = con The following code inserts a new record into the table with data from the variable MyStr MyStr = Hello strSQL = "Insert Into Table(Column) Values('"&MyStr&"')" cmd.CommandText = strSQL cmd.execute

Note: The SQL Query syntax is dependant on your database server. When accessing an Excel file, in the SQL command you refer to a specific worksheet by the following syntax: [worksheetname$] When accessing an Excel spreadsheet with no Headers, be sure to do the following - Make sure the Connection string has HDR=No in the Extended Properties field. - In your SQL command (and Recordset Object), your refer to each column as Fx, where x is the column number (e.g. F1 for the first column, F2 for the second, etc.)

InduSoft Web Studio

2843

IWS Training Guide

Examples using a SQL Query with IWS Tags

Review Questions
1. What does SQL stand for? 2. Which relational database support SQL? 3. Which SQL statement is used to extract from a database a. EXTRACT b. SELECT c. OPEN

d. GET 4. Which SQL statement is used to save changes to the database a. UPDATE b. SAVE AS c. SAVE

d. MODIFY 5. Which SQL statement is used to delete data from a database a. DELETE b. REMOVE c. COLLAPSE

6. Which SQL statement inserts data into a database a. ADD NEW b. ADD RECORD c. INSERT INTO

d. INSERT NEW 7. How do you select the column FirstName from a table named Employees a. SELECT FirstName FROM Employees b. SELECT Employees.FirstName c. EXTRACT FirstName FROM Employees

8. How do you select all columns from a table named Employees? a. SELECT *.Employees b. SELECT Employees c. SELECT [all] FROM Employees

d. SELECT * FROM Employees 9. How do you select all records from a table Employees where the First name is George and the City is Ann Arbor? a. SELECT FirstName=George, City=Ann Abor From Employees b. SELECT * FROM Employees WHERE FirstName LIKE George AND City LIKE Ann Arbor c. SELECT * FROM Employees WHERE FirstName=George AND City=Ann Arbor

2844

InduSoft Web Studio

Examples using a SQL Query with IWS Tags

IWS Training Guide

10. How do you sort the returned records from the Employees Table sorted by the last name in ascending order? a. SELECT * FROM Employees SORT LastName ASC b. SELECT * FROM Employees ORDER LastName ASC c. SELECT * FROM Employees SORT BY LastName ASC

d. SELECT * FROM Employees ORDER BY LastName ASC 11. How do you change an employees last name from Smith to Jones where the first name is Kim and EmployeeID = 987 in the Table Employees? a. UPDATE EMPLOYEES SET LastName=Jones WHERE LastName=Smith b. UPDATE EMPLOYEES SET LastName=Smith INTO LastName=Jones c. MODIFY EMPLOYEES SET LastName=Jones WHERE LastName=Smith

d. MODIFY EMPLOYEES SET LastName=Jones INTO LastName=Jones 12. How do you return the total number of records in the Employees table a. SELECT COLUMNS() FROM Employees b. SELECT COUNT (*) FROM Employees c. SELECT COUNT() FROM Employees

d. SELECT COLUMNS(*) FROM Employees

InduSoft Web Studio

2845

Chapter 29.

Accessing Databases with VBScript

InduSoft Web Studio (IWS) supports ADO.NET (ActiveX for Data Objects for the .NET Framework) used for accessing data sources such as relational databases. ADO.NET allows for the access of data in a consistent, uniform manner regardless of the source of the data. This means that you can develop an application that can easily migrate from one database to another, or be developed prior to the selection of the database. The only database specific requirement is the definition of a connection string, identical to the connection string that is built by the IWS Database configuration wizard. To implement ADO.NET, one or more ADO.NET Managed Providers are required. These Providers are either included as part of the operating system installation (Microsoft includes several ADO.NET Providers), included rd with the Database, or come from a 3 party vendor. The ADO.NET Managed Data Provider provides the interface between the database engine and an IWS application. The IWS Application issues ADO.NET commands or SQL queries, and the Provider responds to those commands or SQL queries. Results of a SQL query are generally returned in Recordsets, which are a collection of records (i.e. rows of data that meet the SQL query criteria). Recordsets are disjoint data; i.e. the Recordset is resident in local memory where the IWS application is run. When an IWS application manipulates a Recordset, it is manipulating the records contained in local memory, not in the Database. To return Records back to the Database, a SQL Update command must be issued to store the Records (i.e. the Recordset) back into the Table in the Database.
.NET Data Provider
Connection Transaction DataAdapter SelectCommand InsertCommand UpdateCommand DeleteCommand DataReader

DataSet DataTableCollection DataTable


DataRowCollection DataColumnCollection ConstraintCollection

Command Parameters

DataRelationCollection

IWS Application Database

Data Provider Functions Connects to Database Executes commands on database Retrieves/updates results

Data Provider Functions Client-side memory resident representation of database result set Consistent interface model

Most ADO.NET providers support ADO, a subset of ADO.NET that uses Microsoft COM technology. VBScript supports ADO, but since VBScript is not a .NET language, VBScript cannot support ADO.NET. Notes: Applications using ADO require an ADO or ADO.NET Provider. Microsoft includes several with the rd .NET framework. Other 3 party ADO Providers are available. ADO.NET is automatically installed with IIS (e.g. with Windows XP Pro) Recordsets are disjoint data. The Recordset is usually the result of a SQL query, and is stored in local memory. You need to issue a SQL Update Command to write the Recordset to the Database Table.

InduSoft Web Studio

291

IWS Training Guide

ADO Overview

ADO Overview
ADO (ActiveX for Data Objects) is a Microsoft technology based on COM (Component Object Model) objects that is used as an API (Applications Programming Interface) between an application (e.g. IWS running VBScript) and the database. ADO connects to an ADO ODBC or ADO OLE-DB Provider to access data from the database, and because ADO has a common API, it removes the dependencies on the particular database used. This makes it much easier for the developer to support multiple databases as well as switch between databases. ADO is a successor technology to DAO (Data Access Objects). The ADO model includes a number of high-level objects, and are described below. Although ADO defines an object hierarchy, most ADO Objects (except for Error, Field and Property) can be created (instantiated) on their own. This gives you flexibility when defining the programmable objects, and allows you to accomplish the same task through different means. For example, a SQL Execute Method can be used with either the Connection or Command objects.

A chart explaining the function of each of these Objects is below. The high-level steps involved in reading from, querying and writing to a database are: 1. Create a Connection to the data source (database) 2. Open the database connection 3. Create an ADO Recordset 4. Extract data from the database using an SQL string, placing the matching records into a Recordset 5. Manipulate the Recordset 6. Update the database (if required) 7. Close the Recordset Object 8. Close the Connection Object These steps are general in nature, and additional steps may be added or removed, based on your specific database access requirements.

292

InduSoft Web Studio

ADO Overview

IWS Training Guide

ADO Object Connection Command Recordset Record Stream Errors Error Parameters Parameter Properties Property Fields Field

ProgID ADODB.Connection ADODB.Command ADODB.Recordset ADODB.Record ADODB.Stream ADOB.Error

Description Used to establish connections between IWS and the database server Used to execute commands (e.g. SQL) on the database. Used to store, view and manipulate results of a query. Also used to store and manipulate created records. A Record is the equivalent of a row of data Manipulates a stream of binary or text data. E.g. text files A collection of Error Objects An Error Object containing the details of a Data Provider error A collection of Parameter Objects A Parameter Object for the specified Object (e.g. a SQL Command, Connection String) A collection of Property Objects A Data Provider-specific configuration value or returned value A collection of Field Objects Allows you to access each Field (column) in a Recordset Object

ADO can be used with ODBC (using a DSN, or Data Source Name) with the Microsoft ADO.NET Provider for ODBC Drivers, or with a DSN-less connection using the ADO.NET Provider for OLE-DB. ADO (ADODB) is supported on Windows 2000/XP/Server 2003 platforms while a slightly less powerful versions called ADOCE is used for Windows CE platforms. Microsoft also developed ADOX (or ADO Extensions for Database Definition Language (Schema) and Security). ADOXCE is ADOX for Windows CE-based platforms. ADOX is primarily used to create new tables in a database. Notes: Not all ADO.NET Providers support ADO. You may need to use ADO OLE-DB or ADO ODBC Providers. The ADODB Class Library is used for Windows XP/2000/Server 2003-based systems The ADOCE Class Library is used for Windows CE-based systems ADO simplifies the interface to databases

InduSoft Web Studio

293

IWS Training Guide

Relational Databases supported by ADO

Relational Databases supported by ADO


With ADO, you can access virtually any relational database using the Microsoft ADO ODBC Provider (using a DSN) and most databases using the Microsoft ADO OLE-DB Provider or a vendor supplied ADO OLE-DB Provider (or ADO.NET provider). Supported databases include: Microsoft SQL Server 2005 (Enterprise Edition, Standard Edition, Workgroup Edition, Express Edition, Compact Edition) Microsoft SQL 2000 MSDE Oracle 8i/9i/10g MySQL 5 Sybase DB2 PostgreSQL SQL Lite Microsoft Access Microsoft Excel* Delimited Text Files*

* Technically not a relational database, but with the ADO OLE-DB Provider you can access data from these data sources using the ADO interface.

Notes: Microsoft provides ADO.NET Providers for all Microsoft databases including SQL Server, Access, Excel and Text Files Microsoft provides an ADO.NET ODBC Provider that can be used to connect (via ODBC) to most databases using an ODBC Driver supplied by the database supplier When possible, use an ADO OLE-DB Provider instead of an ADO ODBC Provider. It will give better performance.

294

InduSoft Web Studio

Database Terminology

IWS Training Guide

Database Terminology
The general terminology for databases is as follows: Database Server Catalog Catalog Groups Users Tables Colums Keys Records

Database Server The Database Server handles all queries to the database. There is commonly a Database Management tool that lets you create or delete Catalogs, Tables within a Catalog and define structure of the Table. Microsoft SQL Server is an example of a Database Server. Catalog The Catalog is a database that contains one or more Tables. The Database Management tool can create a new Catalog. Groups A logical organization of users that have access to the Database Users The person who has permission to access the database Table A table is a named data object consisting of a defined set of columns that can be used to store data in a structured manner, or to contain a key used to index rows in the Table, and some number of unordered rows (records). Column A vertical component of a Table that contains a common set of information. Each columns can consist of different data type. Key(s) A column or set of columns used to index information in the table. Records A horizontal component of a Table that consists of a sequence of values, one for each column in the Table.

InduSoft Web Studio

295

IWS Training Guide

Data Type Mapping

Data Type Mapping


While we just got done saying that ADO provides a common interface to databases, you must still consider that each database supports its own set of data types. The following Data Type Map represents a the data types supported by SQL Server, Oracle and Access. Consult your database documentation for more details of the data types supported. ADO Data Type Enum adBigInt adBinary adBoolean adBSTR adChapter adChar adCurrency ADO Data Type Enum Value 20 128 11 8 136 129 6 char money smallmoney X 8 4 0 0 Char SQL Server bigint
9

Size 8 50 8 1 2

Access

Oracle

binary timestamp bit

Raw

YesNo

Currency DateTime
2

adDate adDBDate adDBFileTime adDBTime adDBTimeStamp adDecimal adDouble adEmpty adError adFileTime adGUID adIDispatch adInteger adIUnknown

7 133 137 134 135 14 5 0 10 64 72 9 3 13 identity int


4

datetime smalldatetime

8 4 0

DateTime

Date Decimal
7

float

8 0

Float Double

uniqueidentifier

16 ReplicationID

2,3

4 4

AutoNumber Long Integer

Int

296

InduSoft Web Studio

Data Type Mapping

IWS Training Guide

ADO Data Type Enum adBigInt adBinary adBoolean adBSTR adChapter adChar adCurrency

ADO Data Type Enum Value 20 128 11 8 136 129 6

SQL Server bigint


9

Size 8 50 8 1 2

Access

Oracle

binary timestamp bit

Raw

YesNo

char money smallmoney

X 8 4 0 2147483647 OLEObject

Char

Currency Long Raw 8 Blob Long 8 Clob


7 7

adLongVarBinary

205

image

adLongVarChar

201

text

2147483647

Memo 1, 2 Hyperlink Memo 3 Hyperlink


3

1, 2

adLongVarWChar

203

ntext

1073741823

NClob

adNumeric

131

decimal numeric

9 Decimal
3

Decimal Integer Number SmallInt

adPropVariant adSingle

138 4 real 4 Single

adSmallInt adTinyInt adUnsignedBigInt adUnsignedInt adUnsignedSmallIn t adUnsignedTinyInt adUserDefined adVarBinary

2 16 21 19 18

smallInt

2 Integer

17 132 204

tinyInt

1 Byte

varbinary

50

InduSoft Web Studio

297

IWS Training Guide

Data Type Mapping

ADO Data Type Enum adBigInt adBinary adBoolean adBSTR adChapter adChar adCurrency

ADO Data Type Enum Value 20 128 11 8 136 129 6

SQL Server bigint


9

Size 8 50 8 1 2

Access

Oracle

binary timestamp bit

Raw

YesNo

char money smallmoney

X 8 4 0

Char

Currency ReplicationID
1

adVarChar adVariant adVarNumeric adVarWChar adWChar

200 12 139 202 130

varchar sql_variant
9

X Text 8016

1, 2

VarChar VarChar2

nvarchar nchar
5

X Text X

NVarChar2

1 - ODBC Driver (3.51.171300): Microsoft Access Driver (*.mdb), Access 97 (3.5 format) 2 - OLE DB Provider: Microsoft.Jet.OLEDB.3.51, Access 97 (3.5 format) 3 - OLE DB Provider: Microsoft.Jet.OLEDB.4.0 , Access 2000 (4.0 format) 4 - OLE DB Provider: SQLOLEDB, SQL Server 6.5 5 - OLE DB Provider: SQLOLEDB, SQL Server 7.0 + 6 - The VB Decimal data type can only be used within a Variant, that is, you cannot declare a VB variable to be of type Decimal. 7 - Oracle 8.0.x Note: DECIMAL and INT are synonyms for NUMBER and NUMBER(10) respectively. 8 - Oracle 8.1.x 9 - OLE DB Provider: SQLOLEDB, SQL Server 2000 + 10 - SQL Server .NET Data Provider (via System.Data.SqlTypes) Source: www.carlprothman.net

298

InduSoft Web Studio

The ADO Connection Object

IWS Training Guide

The ADO Connection Object


The Connection Object is used to establish a virtual connection between an IWS application and a specific Database. The Database can use a DSN (Data Source Name) connection type, typically used to connect to a database using ODBC, or use a DSN-less database connection. Notes: A DSN, or Data Source Name, is a data structure used to define a connection to a specific database. The DSN defines the Database name, directory, database driver, User ID, password and other information. DSNs are defined in Windows XP by going to the Start Control Panel Administrative Tools Data Sources. You will generally use a System DSN.

The Connection Object has a number of Properties, Methods, Events and returned Object Collections associated with it. There are more items than can be realistically covered in these materials, however we will cover the key items in each group. For further information, consult Microsofts MSDN website. Connection Object Properties Property Provider Connection Description The Name of the Data Provider used for the connection. A string containing the information for the current connection. This string can contain the definition of the Data Provider, Data Source, User ID, Password, File Name, Remote Provider and Remote Server. Indicates where the cursor for the current connection should be created, on the Client (adUseClient), or on the Server (adUseServer). Default is the Server. Defines the levels of permission for the connection allowed by the Provider. Mode may be able to instruct the Provider to not allow any additional connections until your connection is closed. An integer value indicating whether the Connection Object is opened (adStateOpen) or closed (adStateClosed)

Cursor Location

Mode

State

Connection Object Methods Method Open Close Execute Cancel OpenSchema Connection Object Events Event Disconnect ExecuteComplete Connection Complete Description This event is fired when the Connection Object is set to Nothing and the Connection is disconnected. This event is fired after a call to the Execute Method of a Connection Object This event is fired when a Connection Object is successfully instantiated. Description Explicitly opens a connection to a Data Provider Close the current Connection Executes a SQL query (the SQL is sent as a parameter) Cancels execution of a pending (asynchronous) Execute or Open method call. Obtains information on the database structure from the Data Provider.

InduSoft Web Studio

299

IWS Training Guide

The ADO Connection Object

Connection Object Collections Collection Errors Description A collection of current Error Objects generated by the last execution performed by the Data Provider. The collection is empty if there are no errors. A collection of Data Provider-specific Properties for the Connection Object. If the Data Provider does not support any custom Properties, the collection is empty.

Properties

There are 3 steps to using a Connection Object. These are: Instantiantiating the Connection Object (i.e. create an instance of) through use of the VBScript CreateObject statement. Define the Connection String or set the Connection Object parameters Execute one or more Connection Object commands The Connection Object can use any valid VBScript name, although by convention you may want to use a small o as a prefix (to indicate an Object), or name the Connection Object as con or something of the sort.

2910

InduSoft Web Studio

The ADO Connection Object

IWS Training Guide

Example ADO Connection Strings and use of the Connection Object


A. Text Files
Example: Jet OLE-DB Provider connecting to a CSV File with Header Dim oConn, connStr Set oConn = CreateObject(ADODB.Connection) connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source= & $GetAppPath() & _ "Extended Properties=""text; HDR=Yes;FMT=CSVDelimited""" oConn.Open connStr Example: Jet OLE-DB Provider connecting to a TAB Delimited File with No Header Dim oConn, connStr Set oConn = CreateObject(ADODB.Connection) connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source= & $GetAppPath() & _ "Extended Properties=""text; HDR=No;FMT=TABDelimited""" oConn.Open connStr Notes: Text files are, of course, not a relational database. However, with the Microsoft Jet 4.0 Provider, you can read text files into an ADO recordset object Delimiter options are: CSVDelimited Comma separated variables TabDelimited Tab separated variables Delimited(x) x = delimited character FixedLength Fixed length fields The choice of delimiters depends on the Provider (Jet or ODBC) If the text file does not contain a header row, then use the field number in parenthesis following the recordset object, e.g. oRS (0) Notice the file name is not in the connection string, only the folder. The file name will be used in the Recordset Open Method to open the file of interest.

B. Microsoft Excel Worksheets


Example: Connecting to Microsoft Excel via ODBC (System DSN is myXL) Dim oConn Set oConn = CreateObject(ADODB.Connection) oConn.Open myXL

Example: Connecting to Microsoft Excel via ODBC (System DSN is myXL) Dim oConn Set oConn = CreateObject(ADODB.Connection) oConn.Open (DSN=myXL;) Notes: The previous two examples use the Microsoft OLE-DB Provider for ODBC Drivers ADO will assume the first row in the Excel file will contain the column headings Excel does not support multi-user concurrent access.

InduSoft Web Studio

2911

IWS Training Guide

The ADO Connection Object

Example: Connecting to Microsoft Excel (DSN-less) using the JET 4.0 OLEDB Provider with Headers Dim oConn, connStr Set oConn = CreateObject(ADODB.Connection) connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source= & $GetAppPath() & myFile.xls; & _ "Extended Properties=""Excel 8.0; HDR=Yes""" oConn.Open connStr Example: Connecting to Microsoft Excel (DSN-less) using the JET 4.0 OLEDB Provider with no Headers Dim oConn, connStr Set oConn = CreateObject(ADODB.Connection) connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source= & $GetAppPath() & myFile.xls; & _ "Extended Properties=""Excel 8.0; HDR=No""" oConn.Open connStr

Notes: The Microsoft OLE-DB Jet 4.0 Provider is used to connect to Microsoft Access, Excel and Text files. It is used to interact with files created using Microsoft Office 2000, 2002, XP, 2003 and later products. The Microsoft OLE-DB Jet 3.51 Provider is used for Microsoft Office 97 products More Microsoft OLE-DB Jet Properties are defined at http://msdn2.microsoft.com/en-us/library/aa140022(office.10).aspx, and http://msdn2.microsoft.com/en-us/library/aa139977(office.10).aspx

C. Microsoft Access Database


Example: Connecting to MS Access Database via ODBC (System DSN is myDB) Dim oConn Set oConn = CreateObject(ADODB.Connection) oConn.Open (DSN=myDB;) Example: Connecting to Microsoft Access Database via ODBC with User Name & Password Dim oConn Set oConn = CreateObject(ADODB.Connection) oConn.Open (DSN=myDB; "username","password") Example: Connecting to Microsoft Access (DSN-less) using Connection Object Properties Dim oConn Set oConn = CreateObject(ADODB.Connection) oConn.Provider = Microsoft.Jet.OLEDB.4.0 oConn.Properties (Data Source).value= $GetAppPath() & myDB.mdb oConn.Open Example: Connecting to Microsoft Access (DSN-less) using a Connection String Property Dim oConn, connStr Set oConn = CreateObject(ADODB.Connection) connStr ="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & $GetAppPath()& "myDB.mdb" oConn.ConnectionString = connStr oConn.Open

2912

InduSoft Web Studio

The ADO Connection Object

IWS Training Guide

Example: Connecting to Microsoft Access Exclusively Dim oConn, connStr Const adModeShareExclusive = &HC Set oConn = CreateObject(ADODB.Connection) connStr ="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & $GetAppPath() & "myDB.mdb" oConn.Mode = adModeShareExclusive oConn.Open connStr Example: Connecting to Microsoft Access that has a Database Password Dim oConn Set oConn = CreateObject(ADODB.Connection) oConn.Provider = Microsoft.Jet.OLEDB.4.0 oConn.ConnectionString = Data Source=" & $GetAppPath() & "myDB.mdb" oConn.Properties(Jet OLEDB:Database Password)=MyDBPassword oConn.Open Example: Connecting to Microsoft Access using a User ID & Password Dim oConn Set oConn = CreateObject(ADODB.Connection) oConn.Provider = Microsoft.Jet.OLEDB.4.0 oConn.ConnectionString = Data Source=" & $GetAppPath() & "myDB.mdb" oConn.Open ,,userID, Password Example: Connecting to Microsoft Access using a User ID & Password Dim oConn Set oConn = CreateObject(ADODB.Connection) oConn.Provider = Microsoft.Jet.OLEDB.4.0 oConn.ConnectionString = Data Source=" & $GetAppPath() & "myDB.mdb;" &_ User ID= & userID & ;Password= & password oConn.Open Example: Connecting to Microsoft Access (DSN-less) using Connection Object Parameters Dim oConn Set oConn = CreateObject(ADODB.Connection) oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & $GetAppPath() & "myDB.mdb" Example: Connecting to Microsoft Access (DSN-less) on a Remote Machine Dim oConn, connStr Set oConn = CreateObject(ADODB.Connection) connStr ="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=\\myServer\myShare\myPath\myDB.mdb" oConn.ConnectionString = connStr oConn.Open Example: Connecting to Microsoft Access (DSN-less) on a Remote Machine Dim oConn, connStr Set oConn = CreateObject(ADODB.Connection) connStr ="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=\\152.10.101.24\myShare\myPath\myDB.mdb" oConn.ConnectionString = connStr oConn.Open

InduSoft Web Studio

2913

IWS Training Guide

The ADO Connection Object

D. Microsoft SQL Server Database


Example: Connecting to Microsoft SQL Server Express (on local PC) with a trusted connection Dim oConn, connStr Set oConn = CreateObject(ADODB.Connection) connStr = "Provider=SQLOLEDB.1;" & "Data Source=user\sqlexpress;" &_ Initial Catalog=MyDB; & Integrated Security=SSPI oConn.Open connStr Example: Connecting to Microsoft SQL Server (on local PC) with standard security Dim oConn, connStr Set oConn = CreateObject(ADODB.Connection) connStr = "Provider=SQLOLEDB.1;" & "Data Source=myServer;" &_ Initial Catalog=MyDB; & User ID=UserID; & Password=myPassword; oConn.Open connStr Example: Connecting to Microsoft SQL Server (on local PC) with standard security Dim oConn, connStr connStr = "Provider=SQLOLEDB.1;" & "Data Source=(local);" & Initial Catalog=MyDatabaseName; &_ "User Id=myUsername;" & "Password=myPassword" oConn.Open connStr Example: Connecting to an Microsoft SQL Server Database prompting for UserName & Password Dim oConn Const adPromptAlways=1 Set oConn = CreateObject(ADODB.Connection) oConn.Provider = sqloledb oConn.Properties (Prompt)= adPromptAlways oConn.Open "Data Source=myServerName;" & Initial Catalog=MyDatabaseName Example: Connecting to Microsoft SQL Server on a Remote PC Dim oConn, connStr Set oConn = CreateObject(ADODB.Connection) connStr = "Provider=SQLOLEDB.1; Data Source=192.168.23.200;Initial Catalog=MyDB; &_ Integrated Security=SSPI oConn.Open connStr Example: Connecting to an Microsoft SQL Server Database on a Remote PC (using an IP address) Dim oConn, connStr Set oConn = CreateObject(ADODB.Connection) connStr = "Provider=sqloledb;" & Network Library=DBMSSOCN; &_ "Data Source=xxx.xxx.xxx.xxx, 1433; & Initial Catalog=MyDatabaseName; &_ "User Id=myUsername;" & "Password=myPassword" oConn.Open connStr where: xxx.xxx.xxx.xxx is the IP address where SQL Server is found 1444 is the default port number for SQL Server You can also add Encrypt=yes to enable encryption

2914

InduSoft Web Studio

The ADO Connection Object

IWS Training Guide

E. Microsoft SQL Server 2000 CE Database


Dim oConn, strConn, dbName Set oConn = CreateObject("ADOCE.Connection.3.1") dbName = $GetAppPath() & "myDB1.SDF" strConn = "Provider=Microsoft.SQLServer.OLEDB.CE.2.0;Data Source=" & dbName oConn.Open strConn Note: SQL Server 2000 CE does not support remote database, only local databases

F. Microsoft SQL Server 2005 Compact Edition for Windows CE


Dim oConn Set conn = CreateObject("ADOCE.connection.3.1") oConn.Open "Provider=Microsoft.SQLSERVER.MOBILE.OLEDB.3.0; Data Source = \HardDisk\MyDB.sdf"

G. Oracle Database (9i/10g)


Example: Connecting to an Oracle Database using an OLEDB Provider (from Microsoft) Dim oConn, connStr Set oConn = CreateObject(ADODB.Connection) connStr = "Provider=msdaora;" & "Data Source=myOracleDB;" & "User Id=myUsername;" & _ "Password=myPassword" oConn.Open connStr Example: Connecting to an Oracle Database using an OLEDB Provider (from Oracle) Dim oConn, connStr Set oConn = CreateObject(ADODB.Connection) connStr = "Provider=OraOLEDB.Oracle.1; Data Source=myDB;User Id=MyID; &_ Password=myPassword" oConn.Open connStr

H. MySQL 5.0 Database


Example: Connecting to a MySQL Database using an OLEDB Provider Dim oConn, connStr Set oConn = CreateObject(ADODB.Connection) connStr = "Provider=MySQLProv; Data Source=myDB;" & "User Id=myUsername;" & _ "Password=myPassword" oConn.Open connStr Example: Connecting to a Remote MySQL Database using an OLEDB Provider Dim oConn, connStr Set oConn = CreateObject(ADODB.Connection) connStr = "Provider=MySQLProv; Data Source=myDB; Location=192.168.23.200" oConn.Open connStr Note: In addition to VBScript variables, IWS tags can be used in the connection string. E.g. provide the file name. Additional connection strings can be found at: www.connectionstrings.com www.carlprothman.net www.sqlstrings.com

InduSoft Web Studio

2915

IWS Training Guide

The ADO Command Object

The ADO Command Object


The Command Object is used to execute a single query against a database. Queries can create, add, retrieve, delete or update records in the database. If the query returns any data, the data will return records in a Recordset Object The Command Object has a number of Properties, Methods, Events and returned Object Collections associated with it. There are more items than can be realistically covered in these materials, however we will cover the key items in each group. For further information, consult Microsofts MSDN website. Command Object Properties Property CommandText CommandTimeout Description A string containing the text of a command you wish to execute against the database An integer value representing the number of seconds ADO should wait for the results of the Command Objects execution before raising an error. The default value is 30 seconds. The type of command that is executed using the Command Object An integer value indicating whether the Connection Object is opened (adStateOpen) or closed (adStateClosed)

CommandType State

Command Object Methods Method Cancel Execute CreateParameter Description Cancel the execution of a Method Executes the Query, SQL Statement or Procedure in the Command Text Property Creates a new Parameter Object for the Command Objects Parameters Collection

Command Object Collections Collection Parameters Properties Description Contains all of the instantiated Parameter Objects that contain parameters for the current Command Object Data Provider-specific properties for the Command Object. If the Data Provider does not support any custom Properties, the Collection is empty.

2916

InduSoft Web Studio

The ADO Command Object

IWS Training Guide

Example using Command Object with Execute and Parameters Dim oConn, oCmd, oRS Set oConn = CreateObject(ADODB.Connection) Set oCmd = CreateObject(ADODB.Command) Set oRS = CreateObject(ADODB.Recordset) oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & $GetAppPath()& "myDB.mdb" Set oRs = oCmd.Execute (Select * From Table1)

Example using Command Object with Execute and Properties Dim oConn, oCmd, oRS Set oConn = CreateObject(ADODB.Connection) Set oCmd = CreateObject(ADODB.Command) Set oRS = CreateObject(ADODB.Recordset) oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & $GetAppPath()& "myDB.mdb" oCmd.CommandText = Select * From Table1" Set oRs = oCmd.Execute Example using Command Object with Execute using IWS Tags & VBScript variables in SQL Dim oConn, oCmd, strSql Set oConn = CreateObject(ADODB.Connection) Set oCmd = CreateObject(ADODB.Command) oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & $GetAppPath()& "myDB.mdb" StrSql = $ID_Insert & ", ' " & $Name_Insert & " ', ' "& $Address_Insert & " ' " cmd.CommandText = "INSERT into Table1 (ID, Name, Address) values (" & StrSql & ")" Set oRs=cmd.Execute Notes: One of the primary purposes of the Command Object is to execute SQL commands using the Execute Method. The Execute Method is also available with the Connection Object and the Recordset Object, although the Command Object is more flexible since it can define, add and remove query parameters.

InduSoft Web Studio

2917

IWS Training Guide

The ADO RecordSet Object

The ADO RecordSet Object


The Recordset Object is the most important Object in ADO. It is used to store records returned from a query (or Table) and contains a cursor into those records. A Recordset Object consists of Records (rows) and Fields (columns). An open Connection Object can support multiple Recordsets. Recordsets can also be created without a Connection Object. Recordset Object Properties Property AbsolutePosition ActiveConnection BOF CursorType DataSource EOF Locktype MaxRecords Description The ordinal number of the current Record in the Recordset Indicates to which Connection Object the Recordset object belongs to Indicates whether the current Record pointer is pointing to the beginning of the Recordset. Boolean read-only value. Specifies the type of cursor ADO will use for the underlying Data Provider. Default is adOpenForwardOnly. Can be used to specify an Object containing data that will be represented as a Recordset Object. Indicates whether the current Record pointer is pointing to the end of the Recordset. Boolean read-only value. Reflects the current locking scheme placed in the Records during editing (ReadOnly, Pessimistic, Optimistic, or BatchOptimistic) Sets or retrieves the maximum number of Records returned in a Recordset by a specific query. If a value of 0, there is no maximum. Can only read when the Recordset is open Returns the number of records in a Recordset. Can only be used with adOpenStatic or adOpenKeyset type cursors. Cannot be used (will return -1) with adOpenDynamic or adOpenForwardOnly. Specifies the name of one or more Fields in the Records in the Recordset Object that will be used to sort the data. Sets or returns the source for the Recordset An integer value indicating whether the Recordset Object is opened (adStateOpen) or closed (adStateClosed)

RecordCount

Sort Source State

2918

InduSoft Web Studio

The ADO RecordSet Object

IWS Training Guide

Recordset Object Methods Method AddNew Cancel CancelUpdate Clone Close Delete Find GetRows GetString Move Description Adds a new record to the recordset and to the underlying data if the recordset is updateable Cancels the execution of a pending (asynchronous) Recordset Open operation Cancels the update to the current record Creates a duplicate of the current Recordset Closes the current Recordset Deletes the current Record or group of Records from the Recordset and the underlying data (if the cursor type of the recordset supports updating) Searches for Records in the Current Recordset Object that match the search criteria Retrieves multiple records from a Recordset into an Array Retrieves a Recordset as a string Moves the current record pointer to a certain number of positions forward or backward from the current Record. The Recordset must support the forward and backward movement. Moves the Record pointer to the first Record in the Recordset Moves the Record pointer to the last Record in the Recordset Moves the Record pointer to the next Record in the Recordset Moves the Record pointer to the previous Record in the Recordset Opens a Recordset Repopulates the current Recordset by rerunning the Query Saves the current Recordset to a file Searches the current Index in a Recordset to locate a specific value Saves changes the current record into the Database

MoveFirst MoveLast MoveNext MovePrevious Open Requery Save Seek Update

Recordset Object Collections Collection Fields Errors Properties Description Contains each Field Object, corresponding to each column of data in the Recordset Contains all the Error Objects created in response to a Provider error Contains Data Provider-specific Properties for the Recordset Object. If the Data Provider does not support any custom Properties, the Collection is empty.

InduSoft Web Studio

2919

IWS Training Guide

The ADO RecordSet Object

Fields Collection Object


A Recordset object has a Fields Collection Object made up of Field objects. Each Field object corresponds to a column (Field) in the Recordset. You can populate the Fields collection before opening the Recordset by calling the Refresh method on the collection. Fields Collection Properties Property Count Item Description Indicates the number of Objects in the Collection Indicates a specific member of a Collection, by Name or ordinal number

Fields Collection Methods Method Append Delete Refresh Update Description Appends a Field Object to a Fields Collection. Can create a new Field Object before it is appended to the Collection. Deletes a Field Object from the Fields Collection Updates the Field Objects in the Fields Collection Saves any changes you make to the Fields Collection of a Recordset Object (since calling AddNew or changing a field value).

Field Object
The Field Object represents a column of Data in the Recordset. Fields Collection Properties Property Name Value DefinedSize NumericScale Type Description Sets or Returns a string value that indicates the Name of the Object Indicates the value assigned to the Field. Sets and Returns a Long value that is the maximum length in characters of the data value(s). Default is 0 (no limit) Used when the Type Property is set to adNumeric or adDecimal. Defines the scale of data values. Byte value. Default is 0. Indicates the operational data type of the Field. E.g. adNumeric, adSingle

2920

InduSoft Web Studio

The ADO RecordSet Object

IWS Training Guide

Recordset Cursor Types


There are four different cursor types defined in ADO: Dynamic cursor (adOpenDynamic) Allows you to view additions, changes, and deletions by other users; allows all types of movement through the Recordset that doesn't rely on bookmarks; and allows bookmarks if the provider supports them. Keyset cursor (adOpenKeyset) Behaves like a dynamic cursor, except that it prevents you from seeing records that other users add, and prevents access to records that other users delete. Data changes by other users will still be visible. It always supports bookmarks and therefore allows all types of movement through the Recordset. Static cursor (adOpenStatic) Provides a static copy of a set of records for you to use to find data or generate reports; always allows bookmarks and therefore allows all types of movement through the Recordset. Additions, changes, or deletions by other users will not be visible. This is the only type of cursor allowed when you open a client-side Recordset object.

Forward-only cursor (adForwardOnly) Allows you to only scroll forward through the Recordset. Additions, changes, or deletions by other users will not be visible. This improves performance in situations where you need to make only a single pass through a Recordset. The CursorType Property can be set prior to opening the Recordset to choose the cursor type, or pass a CursorType argument with using the Open method. Some providers don't support all cursor types. Check the documentation for the provider. If you don't specify a cursor type, ADO opens a forward-only cursor by default.

Recordset Cursor Location


The CursorLocation property defines where the recordset is created when it's opened on the client or the server. In and IWS application, leave this parameter set to Server.

LockType
The LockType property tells the Provider what type of locks should be placed on records during editing. Locking can prevent one user from reading data that is being changed by another user, and it can prevent a user from changing data that is about to be changed by another user. Modifying a record in an Access database locks some neighboring records. This is because Access uses, so called, page locking strategy. This means that if a user is editing a record, some other user won't be allowed to modify that record, or even to modify the next few records after or before it. LockReadOnly (adLockReadOnly) Read only locking simply does not allow data editing. This lock is useful in conditions where your application must temporarily prevent data changes, but still can allow unrestricted reading. Read only locking with CursorType set to ctForwardOnly is ideal for reporting purposes. LockOptimistic (adLockOptimistic) Optimistic locking locks the record only when it's physically updated. This type of locking is useful in conditions where there is only a small chance that a second user may update a row in the interval between when a cursor is opened and the row is finally updated. The current values in the row are compared with the values retrieved when the row was last fetched. LockPessimistic (adLockPessimistic) Pessimistic locking locks each record while it's being edited. This option tells ADO to get an exclusive lock on the row when the user makes any change to any column in the record. The ADOExpress

InduSoft Web Studio

2921

IWS Training Guide

The ADO RecordSet Object

components don't directly support pessimistic record locking because ADO itself does not have any way to arbitrarily lock a given record and still support navigating to other records. LockBatchOptimistic (adLockBatchOptimistic) BatchOptimistic locking is used with disconnected recordsets. These recordsets are updated locally and all modifications are sent back to the database in a batch.

2922

InduSoft Web Studio

The ADO RecordSet Object

IWS Training Guide

Using the Recordset Object


The following are examples using the Recordset Object:

A. Using the Recordset Object with Text Files


Example : Reading data from a text file (CSV delimited) with Headers Dim oConn, connStr, oRS, strSQL, msg Set oConn = CreateObject(ADODB.Connection) Set oRS = CreateObject(ADODB.Recordset) connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source= & $GetAppPath() & _ "Extended Properties=""text; HDR=Yes;FMT=CSVDelimited""" oConn.Open connStr strSQL = "Select * FROM myFile.csv" Set oRS = oConn.Execute(strSQL) msg = Do Until oRS.EOF msg = msg & V1= & oRS.Fields.Item(V1) & V2= & oRS.Fields.Item(V2) & VbCrLf oRS.MoveNext Loop Msgbox msg oRS.close oConn.close Set oRS = Nothing Set oConn = Nothing Example : Reading data from a text file (CSV delimited) with Headers Dim oConn, oDB, oRS, strConn, strSQL, strRec, Path Const adOpenStatic = 3 Const adLockOptimistic = 3 Const adCmdText = &H0001 Set oConn = CreateObject("ADODB.Connection") Set oRS = CreateObject("ADODB.Recordset") Path = "C:\myData\" strConn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Path &_ ";Extended Properties='text;HDR=No;FMT=CSVDelimited'" oConn.Open strConn strSql = "Select * FROM test.txt" 'strSql = "Select * FROM MovimentoOperativos.txt" oRS.open strSql, oConn, adOpenStatic, adLockOptimistic, adCmdText recStr = "" Do Until oRS.EOF recStr = recStr & " Col1= " & oRS (0) recStr = recStr & " Col2= " & oRS (1) & vbCrLf oRS.Movenext Loop MsgBox recStr oRS.close oConn.close Set oRS = Nothing Set oConn = Nothing Note: If the Text file contains no header row, use oRS(n) to access the an item from the record (n=item # in the record, starting with 0). InduSoft Web Studio 2923

IWS Training Guide

The ADO RecordSet Object

B. Using the Recordset Object with Microsoft Excel Worksheets


Example : Reading data from an Excel file with a header row Dim oConn, strConn, oRS, myFile, msg Set oConn = CreateObject(ADODB.Connection) Set oRS = CreateObject(ADODB.Recordset) myFile = C:\test\myDB.xls strConn = Provider=Microsoft.Jet.OLEDB.4.0; & Data Source= & myfile & ; &_ Extended Properties = Excel 8.0; HDR=Yes oConn.open = strConn Set oRS = oConn.Execute (SELECT * FROM [Alarm$]) msg = While Not rs.EOF msg = msg & Alarm = & oRS(time) & reason= & oRS(reason) & VbCrLf oRS.MoveNext Wend Msgbox msg oRS.close oConn.close Set oRS = Nothing Set oConn = Nothing

Example : Reading data from an Excel file with no header row Dim oConn, strConn, oRS, myFile, strSQL, msg, temp, loopCtr Set oConn = CreateObject(ADODB.Connection) Set oRS = CreateObject(ADODB.Recordset) myFile = C:\test\myDB.xls strConn = Provider=Microsoft.Jet.OLEDB.4.0; & Data Source= & myfile & ; &_ Extended Properties = Excel 8.0; HDR=No oConn.open = strConn temp = $myVal strSQL = SELECT * FROM [Alarm$] WHERE (F6=Hi Alarm) AND (F7 IS NULL) AND (F8=&temp) Set oRS = oConn.Execute (strSQL) Msg = loopCtr = 0 While Not rs.EOF msg= msg & Alarm = & oRS(F4) & reason= & oRS(F5) & VbCrLf loopCtr = loopCtr + 1 oRS.MoveNext Wend Msgbox Total of & loopCtr & records & VbCrLf & msg oRS.close oConn.close Set oRS = Nothing Set oConn = Nothing

2924

InduSoft Web Studio

The ADO RecordSet Object

IWS Training Guide

Example : Writing data to a cell in an Excel file with no header row Dim oConn, connStr, oRS, myFile, strSQL, msg, temp, loopCtr, temp, newVal Set oConn = CreateObject(ADODB.Connection) Set oRS = CreateObject(ADODB.Recordset) myFile = C:\test\myDB.xls connStr = Provider=Microsoft.Jet.OLEDB.4.0; & Data Source= & myfile & ; &_ Extended Properties = Excel 8.0; HDR=No oConn.open = strConn temp = $mySearchData newVal = $myNewVal strSQL = "Select * From [Alarm$] Where F5='"&temp&"' " oRS.Open strSQL, oDB, adOpenKeySet, adLockOptimistic oConn.BeginTrans oRS.update "F8", newVal oConn.CommitTrans oRS.close oConn.close Set oRS = Nothing Set oConn = Nothing Notes: The Excel Worksheet name syntax in the SQL statement opening the recordset must be as follows: [Worksheet$] If the Excel file contains no header row, use Fx as the column designator (e.g. F1, F5, etc.) If looking for an cell that is empty in a SQL Query, use the SQL command IS NULL If using a VBScript variable an an SQL argument, it must be enclosed in a single quote , followed by a double quote , then an & symbol, the VBScript variable, a double quote, then a single quote.

InduSoft Web Studio

2925

IWS Training Guide

The ADO RecordSet Object

C. Using the Recordset Object with Microsoft Access


Example Program to print Fields of a MS Access Table using the Field Object and Field Collection Dim con, fld, flds, rs Dim strConn Dim i, totCount, myStr Set con = CreateObject("ADODB.Connection") Set rs = CreateObject("ADODB.Recordset") con.Provider = "Microsoft.Jet.OLEDB.4.0" con.Properties("Data Source").value = $GetAppPath()& "MachineInfo.mdb" con.Open Set rs = con.Execute ("Select * From Table1") Set flds = rs.Fields totCount = flds.Count MsgBox "Count = " & totcount myStr = "" For Each fld In Flds myStr = myStr & "Name = " & fld.Name & " Type = " & fld.Type & " Value = " & fld.Value & vbCrLf Next MsgBox "total fields = " & totCount & vbCrLf & myStr rs.close con.close Set rs = Nothing Set con = Nothing Example Reading data from an ADO DB and saving into an IWS Class Array Dim oConn, oDB, oRS, strSQL, DBRowCount Set odb = CreateObject ("ADODB.Connection") Set oRS= CreateObject (ADODB.Recordset) strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & $GetAppPath() & MyDB.mdb" oDB.open strConn strSQL = "Select * From Table1" Set oRS = oDB.Execute (strSQL) DbRowCount = -1 While Not oRS.EOF DbRowCount = DbRowCount + 1 $ProdStat[DbRowCount].Time= CStr(oRS("Time")) $ProdStat[DbRowCount].Total = CInt(oRS ("Total")) $ProdStat[DbRowCount].Good = CInt(oRS ("Good")) $ProdStat[DbRowCount].Marginal = CInt(oRS ("Marginal")) $ProdStat[DbRowCount].Bad = CInt(oRS ("Bad")) oRS.MoveNext Wend oDB.close Set oDB = Nothing

2926

InduSoft Web Studio

The ADO RecordSet Object

IWS Training Guide

D. Using the Recordset Object with Oracle


Example Program to write data into an Oracle Database Dim strConn, strSQL, oDB, oRS Dim msg, m, LoopCounter, myTemp Const adOpenKeySet=1 Const adLockOptimistic=3 strConn=Provider=OraOLEDB.Oracle.1;Data Source=MyDB; User ID=MyID;Password=MyPW; Set oDB=CreateObject(ADODB.Connection) Set oRS=CreateObject(ADODB.Recordset) oDB.open strConn strSQL = Select * FROM myTable oRS.open strSQL, oDB, adOpenKeySet, adLockOptimistic Append data at end of file While Not oRS.eof oRS.movenext Wend oRS.addnew myTemp=Date & & Time oRS(read_date)=Cstr(myTemp) oRS(quantity) = $myQuantity oRS(tank_number)= Cstr($tankLabel) oDB.BeginTrans oRS.update oDB.CommitTrans oRS.close oDB.close Set oRS=Nothing Set oDB=Nothing

E. Examples using Recordset Object Methods


Move Previous If Not oRS =True Then oRS.moveprevious End If Move Next If Not oRS =True Then oRS.movenext End If Record cursor type must support this

Works even with forward only cursor types

Add a new Record With oRS .addnew .Fields(Field1) = myVal1 .Fields(Field2) = myVal2 .Fields(Field3) = myText3 .Update Updates database End With

InduSoft Web Studio

2927

IWS Training Guide

The ADO RecordSet Object

Deleting a Record If Not (oRS.BOF=True) Or (oRS.EOF=True) Then oRS.Delete End If

2928

InduSoft Web Studio

The Stream Object

IWS Training Guide

The Stream Object


The Stream object provides the means to read, write, and manage a stream of bytes. This byte stream may be text or binary and is limited in size only by system resources. Typically, ADO Stream objects are used to contain the data of a Recordset saved in XML format This Example saves a Recordset to a file and then to a Stream. It then opens the persisted stream into another Recordset. Dim con, rs1, rs2, stm, StrRst Const adPersistXML =1 Set con = CreateObject("ADODB.Connection") Set rs1 = CreateObject("ADODB.Recordset") Set rs2 = CreateObject("ADODB.Recordset") Set stm = CreateObject("ADODB.Stream") con.Provider = "Microsoft.Jet.OLEDB.4.0" con.Properties("Data Source").value = $GetAppPath()& "MachineInfo.mdb" con.Open Set rs1 = con.Execute ("Select * From Table1") rs1.Save $GetAppPath()& "MachineInfo.xml", adPersistXML rs1.Save stm, adPersistXML rs2.Open stm This Example persists a Recordset into a Stream in XML format. It then reads the Stream into a string that you can examine, manipulate, or display. Dim con, rs, stm, StrRst Const adReadAll = -1 Const adPersistXML =1 Set con = CreateObject("ADODB.Connection") Set rs = CreateObject("ADODB.Recordset") Set stm = CreateObject("ADODB.Stream") con.Provider = "Microsoft.Jet.OLEDB.4.0" con.Properties("Data Source").value = $GetAppPath()& "MachineInfo.mdb" con.Open Set rs = con.Execute ("Select * From Table1") rs.Save stm, adPersistXML strRst = stm.ReadText (adReadAll) 'Display thee XML data. MsgBox strRst

InduSoft Web Studio

2929

IWS Training Guide

Using the ADOX Object Model

Using the ADOX Object Model


ADOX (ADO Extensions) is a set of Extension Objects to the ADO Programming Model, created by Microsoft following the release of ADO 2.1. These Objects are primarily used for Schema (Data) Definition and Security. The entire ADOX Model is beyond the scope of these materials, although there are some useful features which will be covered here. Microsoft designed ADOX to work with the Microsoft Jet OLE-DB Provider. This means that a runtime system with IWS and the Jet OLE-DB Provider can create blank Excel spreadsheets or Access Database without either the Excel or Access program being installed on the runtime system. ADOX can be used to create additional tables (Access) or Worksheets (Excel), and define the fields (columns). However, the use of ADOX with other databases is problematic. For example, ADOX will not work with Oracle since Oracle is case-sensitive, while Jet is not. The ADOX object model starts with the Catalog object, the top-level object providing schema information about a Data Store. The Catalog object contains a number of objects as Properties, each of which are collections. (For example, the Tables property of the Catalog object is a collection of Table objects.) These Catalog Object Properties include: Tables Groups Users Procedures Views ADOX CatalogObject Properties Property ActiveConnection Description Sets a Connection Object of a string containing the definition for a connection. Returns the active Connection Object.

ADOX Catalog Object Methods Method Create Description Creates a new Catalog. Uses a connection string parameter to connect to the Data Source

ADOX Catalog Collections Collection Tables Users Description A collection containing all the Tables in the Catalog A collection containing all the Catalogs users

2930

InduSoft Web Studio

Using the ADOX Object Model

IWS Training Guide

In addition to the Catalog Object, ADOX has two other Objects that are useful to manipulate Data Sources. These are the Table Object and Column Object. The Table Object can be used to create a new Table consisting of columns, indexes and keys. ADOX Table Object Properties Property Name Type Parent Catalog ADOX Table Collections Collection Columns Keys Description Contains all Column Objects of a Table Contains all Keys of a Table Description Sets or Returns the name of the Table Returns the Type of Table (e.g. Table, System Table, or Global Temporary. Sets and Returns the Parent Catalog of the Table Object.

The Columns Collection for the Table Object represents al of the Column Objects in the Table. This Collection is useful for adding and removing Columns in the Table. ADOX Column Collection Methods Method Append Delete Description Adds a new Column Object to the Columns Collection Deletes a Column from the Table Object

Example Usage of the ADOX Column Collection Object oTable.Columns.Append Column [,optType] [,optDefinedSize] where: Column= a Name to create and append, or Column Object to append to the Table optType= a long value that spefices the data type of the Column optDefiendSize= a long value that specifies the size of the Column

The Column Object is used to represent a column (Fields) for a Table. ADOX Column Object Properties Property Name Type Parent Catalog Sort Order Defined Size Numeric Scale Description Sets or Returns the name of the Column Sets or Returns a Long value that can be one of the DataTypeEnum constants. Default is adVarWChar. Sets and Returns the Parent Catalog of the Column Object. Indicates the Sort sequence for the column (Index columns only). Default is adSortAscending. Sets and Returns a Long value that is the maximum length in characters of the data value(s). Default is 0 (no limit) Used when the Type Property is set to adNumeric or adDecimal. Defines the scale of data values. Byte value. Default is 0.

InduSoft Web Studio

2931

IWS Training Guide

Using the ADOX Object Model

Example using the Catalog Object to Create a new Microsoft Access Database The Catalog Object first needs to be instantiated just like other Objects in VBScript. This is done by the following method: Dim oADOXDB Set oADOXDB = CreateObject (ADOX.Catalog) Now that we have created a Catalog Object, we can use the Catalog Object to create a new Data Source using the Data Provider. For instance, we could create a new Microsoft Access Database. Dim oADOXDB Set oADOXDB = CreateObject (ADOX.Catalog) oADOXDB.Create "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & $GetAppPath()& "newDB.mdb" The location and name of the new Access Database can be changed by specifying a different name in the Data Provider string. Note that this is similar to a connection string. Note: The name of the Data Source must be unique (i.e. does not already exist). If it does, you will receive the following error message: Viewer: Runtime Error => screenX.scr : Screen Script : Line X : Database already exists. (-2147217897) in the Output Window. The Sceen Name and Line Number will depend on your application (or the Script may be located in a Math Worksheet). Now that the Access database file has been created, we can create a Table in the database, and add Fields (columns) and a Primary Key constraint. Dim oADOXDB, oTable Const adInteger = 3 Const adVarWChar = 202 Set oADOXDB = CreateObject (ADOX.Catalog) Set oTable = CreateObject(ADOX.Table) oADOXDB.Create "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & $GetAppPath()& "newDB.mdb" oTable.Name = Table1 oTable.Columns.Append ID, adInteger integer column oTable.Columns.Append Machine Name, adVarWChar, 30 variable width character column, max=30 oTable.Columns.Append Hourly Production. adInteger integer column oTable.Keys.Append PK_ID, 1, ID primary key column, 1=primary key oADOXDB.Tables.Append oTable In the example above, Table1 is the new table name, Machine Name is a column that is 30 characters wide, with variable width characters and Hourly Production is a column containing integers. The ID column will be used as the Primary Key field. The Keys.Append command puts a Primary Key constraint nd on this field. PK_ID is the name of the Primary Key, the 2 argument is the type of key (1=primary key), and rd the 3 argument in the Keys.Append command specifies the column which will be the Primary key. Remember that each primary key needs to be a unique number or name. As an alternative, we could have chosen to put a primary key constraint on the Machine Name column.

2932

InduSoft Web Studio

Using the ADOX Object Model

IWS Training Guide

Example using the Catalog Object to Create a new Microsoft Excel File Following the above example (creating a new Microsoft Access Database), we can create a new Microsoft Excel file using the following code: Dim oADOXDB, oTable, oColumn, i Const adDouble = 5 Set oADOXDB = CreateObject("ADOX.Catalog") Set oTable = CreateObject("ADOX.Table") oADOXDB.ActiveConnection = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & $GetAppPath()& _ "newXL.xls;" & "Extended Properties = ""Excel 8.0; HDR=Yes""" oTable.Name = "ProdData" For i = 1 To 4 Set oColumn = CreateObject("ADOX.Column") With oColumn .Name ="Col" & i .Type = adDouble End With oTable.Columns.Append oColumn Set oColumn = Nothing Next oADOXDB.Tables.Append oTable

Notes: ADOX is primary used to support Microsoft Access and Excel. It has limited support for Microsoft SQL Server. For other databases, use the Database Manager tool to create a new catalog. You can use SQL the Create Table command and possibly the Create Database command to create a new Catalog (if the Database Server supports this command). You can use T-SQL for Microsoft SQL Server to create a new Catalog. ADOX is powerful in that you can create Microsoft Access databases and Excel worksheets on a runtime system (from the IWS application) without Microsoft Access or Microsoft Excel being installed on the system. The file (.mdb for Access, .xls for Excel) can be later copied or moved to a remote platform. A Windows CE version of ADOX is available ADOXCE.

InduSoft Web Studio

2933

IWS Training Guide

ADOCE and ADOXCE

ADOCE and ADOXCE


Microsoft provides a version of ADO for Windows CE applications. The ADOCE version 3.1 control is shipped with Microsoft Embedded Tools 3.0 and can be downloaded from Microsofts website. ADOCE version 3.1 replaces ADOCE control 2.0 and 3.0. You must use the version number in the programmatic identifier, or ProgID. If you do not, you may get a Create Object Error when executing your application. The ADOCE version 3.1 control is designed to work with data sources that use an OLE-DB provider. ADOCE provides a subset of ADOs (ADODB) functionality. Most of ADOCEs syntax is the same as ADO, and many of the error values and error strings are the same. ADOXCE is Microsofts ActiveX Data Objects Extensions for Data Definition Language (DDL) and Security for the Windows CE operating system (ADOXCE), an extension (companion library) to the ADOCE objects and programming model. ADOXCE provides objects for schema creation and modification (creating, modifying and deleting schema objects such as databases and tables). Unlike ADOX, ADOXCE does not include any security objects (e.g. users or groups). The ADOCE Object Model is shown below. Note that unlike the ADO Object Model, the following Objects are not available in ADOCE: Command Object, Record Object, Stream Object, Errors Object ADOCE Object Connection Recordset Fields Field Errors Error OpenSchema ProgID ADOCE.Connection.3.1 ADOCE.Recordset.3.1 Description Used to establish connections between VBScript and the database server Used to store, view and manipulate results of a query. Also used to store and manipulate created records. A collection of Field Objects Allows you to access each Field (column) in a Recordset Object A collection of Error Objects An Error Object containing the details of a Data Provider error

ADOB.Error

2934

InduSoft Web Studio

ADOCE and ADOXCE

IWS Training Guide

The RecordSet Object


Recordset Object Properties Property AbsolutePage AbsolutePosition ActiveConnection BOF Bookmark CacheSize CursorType EditMode EOF Locktype PageCount PageSize RecordCount Source Description Specifies which page to move for a new current record Specifies the ordinal number (position) of the current Record in the Recordset Sets the current database connection. Default is a zero-length string Indicates whether the current Record pointer is pointing to the beginning of the Recordset. Boolean read-only value. Specifies a bookmark that uniquely identifies a record in a Recordset Object Specifies the number of records from a Recordset Object that are cached locally in memory. Specifies the type of cursor ADO will use for the underlying Data Provider. Default is adOpenForwardOnly. Indicates the editing status of the current record Indicates whether the current Record pointer is pointing to the end of the Recordset. Boolean read-only value. Reflects the current locking scheme placed in the Records during editing (ReadOnly, Pessimistic, Optimistic, or BatchOptimistic) Indicates how many pages of data the Recordset Object contains Indicates how many records constitute one page in the Recordset Returns a Long Value that indicates the current number of records in a Recordset Object Indicates the source for the data in a Recordset Object SQL statement or Table name

Recordset Object Methods Method AddNew CancelUpdate Clone Close Delete GetRows Move Description Adds a new record to the recordset and to the underlying data if the recordset is updateable Cancels the update to the current record (cancels changes held in memory) Creates a duplicate of the current Recordset Closes the current Recordset Deletes the current Record or group of Records from the Recordset and the underlying data (if the cursor type of the recordset supports updating) Retrieves multiple records from a Recordset into an Array Moves the current record pointer to a certain number of positions forward or backward frin the current Record. The Recordset must support the forward and backward movement. Moves the Record pointer to the first Record in the Recordset Moves the Record pointer to the last Record in the Recordset Moves the Record pointer to the next Record in the Recordset Moves the Record pointer to the previous Record in the Recordset Defines and opens a Recordset, executes SQL commands Determines if the Recordset supports certain features Saves changes the current record into the Database

MoveFirst MoveLast MoveNext MovePrevious Open Supports Update

InduSoft Web Studio

2935

IWS Training Guide

ADOCE and ADOXCE

'ADOCE Cursor types Const adOpenKeyset = 1 Const adOpenDynamic = 2 Const adOpenStatic = 3 'ADOCE Lock Types Const adLockReadOnly = 1 Const adLockPessimistic = 2 Const adLockOptimistic = 3 Const adLockBatchOptimistic = 4

Example: Instancing the ADOCE Connection Object and Recordset Object Dim oConn, oRS Set oConn = CreateObject(ADOCE.Connection.3.1) Set oRS = CreateObject(ADOCE.Recordset.3.1)

2936

InduSoft Web Studio

ADOVBS Constants

IWS Training Guide

ADOVBS Constants
Microsoft provides an ADO Constants Include file for use with VBScript. This file can generally be found in the C:\Program Files\Common Files\System directory. The contents of this file are documented below for reference purposes: '---- CursorTypeEnum Values ---Const adOpenForwardOnly = 0 Const adOpenKeyset = 1 Const adOpenDynamic = 2 Const adOpenStatic = 3 '---- CursorOptionEnum Values ---Const adHoldRecords = &H00000100 Const adMovePrevious = &H00000200 Const adAddNew = &H01000400 Const adDelete = &H01000800 Const adUpdate = &H01008000 Const adBookmark = &H00002000 Const adApproxPosition = &H00004000 Const adUpdateBatch = &H00010000 Const adResync = &H00020000 Const adNotify = &H00040000 Const adFind = &H00080000 Const adSeek = &H00400000 Const adIndex = &H00800000 '---- LockTypeEnum Values ---Const adLockReadOnly = 1 Const adLockPessimistic = 2 Const adLockOptimistic = 3 Const adLockBatchOptimistic = 4 '---- ExecuteOptionEnum Values ---Const adAsyncExecute = &H00000010 Const adAsyncFetch = &H00000020 Const adAsyncFetchNonBlocking = &H00000040 Const adExecuteNoRecords = &H00000080 Const adExecuteStream = &H00000400 '---- ConnectOptionEnum Values ---Const adAsyncConnect = &H00000010 '---- ObjectStateEnum Values ---Const adStateClosed = &H00000000 Const adStateOpen = &H00000001 Const adStateConnecting = &H00000002 Const adStateExecuting = &H00000004 Const adStateFetching = &H00000008 '---- CursorLocationEnum Values ---Const adUseServer = 2 Const adUseClient = 3

InduSoft Web Studio

2937

IWS Training Guide

ADOVBS Constants

'---- DataTypeEnum Values ---Const adEmpty = 0 Const adTinyInt = 16 Const adSmallInt = 2 Const adInteger = 3 Const adBigInt = 20 Const adUnsignedTinyInt = 17 Const adUnsignedSmallInt = 18 Const adUnsignedInt = 19 Const adUnsignedBigInt = 21 Const adSingle = 4 Const adDouble = 5 Const adCurrency = 6 Const adDecimal = 14 Const adNumeric = 131 Const adBoolean = 11 Const adError = 10 Const adUserDefined = 132 Const adVariant = 12 Const adIDispatch = 9 Const adIUnknown = 13 Const adGUID = 72 Const adDate = 7 Const adDBDate = 133 Const adDBTime = 134 Const adDBTimeStamp = 135 Const adBSTR = 8 Const adChar = 129 Const adVarChar = 200 Const adLongVarChar = 201 Const adWChar = 130 Const adVarWChar = 202 Const adLongVarWChar = 203 Const adBinary = 128 Const adVarBinary = 204 Const adLongVarBinary = 205 Const adChapter = 136 Const adFileTime = 64 Const adPropVariant = 138 Const adVarNumeric = 139 Const adArray = &H2000

2938

InduSoft Web Studio

ADOVBS Constants

IWS Training Guide

'---- FieldAttributeEnum Values ---Const adFldMayDefer = &H00000002 Const adFldUpdatable = &H00000004 Const adFldUnknownUpdatable = &H00000008 Const adFldFixed = &H00000010 Const adFldIsNullable = &H00000020 Const adFldMayBeNull = &H00000040 Const adFldLong = &H00000080 Const adFldRowID = &H00000100 Const adFldRowVersion = &H00000200 Const adFldCacheDeferred = &H00001000 Const adFldIsChapter = &H00002000 Const adFldNegativeScale = &H00004000 Const adFldKeyColumn = &H00008000 Const adFldIsRowURL = &H00010000 Const adFldIsDefaultStream = &H00020000 Const adFldIsCollection = &H00040000 '---- EditModeEnum Values ---Const adEditNone = &H0000 Const adEditInProgress = &H0001 Const adEditAdd = &H0002 Const adEditDelete = &H0004 '---- RecordStatusEnum Values ---Const adRecOK = &H0000000 Const adRecNew = &H0000001 Const adRecModified = &H0000002 Const adRecDeleted = &H0000004 Const adRecUnmodified = &H0000008 Const adRecInvalid = &H0000010 Const adRecMultipleChanges = &H0000040 Const adRecPendingChanges = &H0000080 Const adRecCanceled = &H0000100 Const adRecCantRelease = &H0000400 Const adRecConcurrencyViolation = &H0000800 Const adRecIntegrityViolation = &H0001000 Const adRecMaxChangesExceeded = &H0002000 Const adRecObjectOpen = &H0004000 Const adRecOutOfMemory = &H0008000 Const adRecPermissionDenied = &H0010000 Const adRecSchemaViolation = &H0020000 Const adRecDBDeleted = &H0040000 '---- GetRowsOptionEnum Values ---Const adGetRowsRest = -1 '---- PositionEnum Values ---Const adPosUnknown = -1 Const adPosBOF = -2 Const adPosEOF = -3

InduSoft Web Studio

2939

IWS Training Guide

ADOVBS Constants

'---- BookmarkEnum Values ---Const adBookmarkCurrent = 0 Const adBookmarkFirst = 1 Const adBookmarkLast = 2 '---- MarshalOptionsEnum Values ---Const adMarshalAll = 0 Const adMarshalModifiedOnly = 1 '---- AffectEnum Values ---Const adAffectCurrent = 1 Const adAffectGroup = 2 Const adAffectAllChapters = 4 '---- ResyncEnum Values ---Const adResyncUnderlyingValues = 1 Const adResyncAllValues = 2 '---- CompareEnum Values ---Const adCompareLessThan = 0 Const adCompareEqual = 1 Const adCompareGreaterThan = 2 Const adCompareNotEqual = 3 Const adCompareNotComparable = 4 '---- FilterGroupEnum Values ---Const adFilterNone = 0 Const adFilterPendingRecords = 1 Const adFilterAffectedRecords = 2 Const adFilterFetchedRecords = 3 Const adFilterConflictingRecords = 5 '---- SearchDirectionEnum Values ---Const adSearchForward = 1 Const adSearchBackward = -1 '---- PersistFormatEnum Values ---Const adPersistADTG = 0 Const adPersistXML = 1 '---- StringFormatEnum Values ---Const adClipString = 2 '---- ConnectPromptEnum Values ---Const adPromptAlways = 1 Const adPromptComplete = 2 Const adPromptCompleteRequired = 3 Const adPromptNever = 4

2940

InduSoft Web Studio

ADOVBS Constants

IWS Training Guide

'---- ConnectModeEnum Values ---Const adModeUnknown = 0 Const adModeRead = 1 Const adModeWrite = 2 Const adModeReadWrite = 3 Const adModeShareDenyRead = 4 Const adModeShareDenyWrite = 8 Const adModeShareExclusive = &HC Const adModeShareDenyNone = &H10 Const adModeRecursive = &H400000 '---- RecordCreateOptionsEnum Values ---Const adCreateCollection = &H00002000 Const adCreateStructDoc = &H80000000 Const adCreateNonCollection = &H00000000 Const adOpenIfExists = &H02000000 Const adCreateOverwrite = &H04000000 Const adFailIfNotExists = -1 '---- RecordOpenOptionsEnum Values ---Const adOpenRecordUnspecified = -1 Const adOpenOutput = &H00800000 Const adOpenAsync = &H00001000 Const adDelayFetchStream = &H00004000 Const adDelayFetchFields = &H00008000 Const adOpenExecuteCommand = &H00010000 '---- IsolationLevelEnum Values ---Const adXactUnspecified = &Hffffffff Const adXactChaos = &H00000010 Const adXactReadUncommitted = &H00000100 Const adXactBrowse = &H00000100 Const adXactCursorStability = &H00001000 Const adXactReadCommitted = &H00001000 Const adXactRepeatableRead = &H00010000 Const adXactSerializable = &H00100000 Const adXactIsolated = &H00100000 '---- XactAttributeEnum Values ---Const adXactCommitRetaining = &H00020000 Const adXactAbortRetaining = &H00040000 '---- PropertyAttributesEnum Values ---Const adPropNotSupported = &H0000 Const adPropRequired = &H0001 Const adPropOptional = &H0002 Const adPropRead = &H0200 Const adPropWrite = &H0400

InduSoft Web Studio

2941

IWS Training Guide

ADOVBS Constants

'---- ErrorValueEnum Values ---Const adErrProviderFailed = &Hbb8 Const adErrInvalidArgument = &Hbb9 Const adErrOpeningFile = &Hbba Const adErrReadFile = &Hbbb Const adErrWriteFile = &Hbbc Const adErrNoCurrentRecord = &Hbcd Const adErrIllegalOperation = &Hc93 Const adErrCantChangeProvider = &Hc94 Const adErrInTransaction = &Hcae Const adErrFeatureNotAvailable = &Hcb3 Const adErrItemNotFound = &Hcc1 Const adErrObjectInCollection = &Hd27 Const adErrObjectNotSet = &Hd5c Const adErrDataConversion = &Hd5d Const adErrObjectClosed = &He78 Const adErrObjectOpen = &He79 Const adErrProviderNotFound = &He7a Const adErrBoundToCommand = &He7b Const adErrInvalidParamInfo = &He7c Const adErrInvalidConnection = &He7d Const adErrNotReentrant = &He7e Const adErrStillExecuting = &He7f Const adErrOperationCancelled = &He80 Const adErrStillConnecting = &He81 Const adErrInvalidTransaction = &He82 Const adErrUnsafeOperation = &He84 Const adwrnSecurityDialog = &He85 Const adwrnSecurityDialogHeader = &He86 Const adErrIntegrityViolation = &He87 Const adErrPermissionDenied = &He88 Const adErrDataOverflow = &He89 Const adErrSchemaViolation = &He8a Const adErrSignMismatch = &He8b Const adErrCantConvertvalue = &He8c Const adErrCantCreate = &He8d Const adErrColumnNotOnThisRow = &He8e Const adErrURLIntegrViolSetColumns = &He8f Const adErrURLDoesNotExist = &He8f Const adErrTreePermissionDenied = &He90 Const adErrInvalidURL = &He91 Const adErrResourceLocked = &He92 Const adErrResourceExists = &He93 Const adErrCannotComplete = &He94 Const adErrVolumeNotFound = &He95 Const adErrOutOfSpace = &He96 Const adErrResourceOutOfScope = &He97 Const adErrUnavailable = &He98 Const adErrURLNamedRowDoesNotExist = &He99 Const adErrDelResOutOfScope = &He9a Const adErrPropInvalidColumn = &He9b Const adErrPropInvalidOption = &He9c Const adErrPropInvalidValue = &He9d Const adErrPropConflicting = &He9e

2942

InduSoft Web Studio

ADOVBS Constants

IWS Training Guide

Const adErrPropNotAllSettable = &He9f Const adErrPropNotSet = &Hea0 Const adErrPropNotSettable = &Hea1 Const adErrPropNotSupported = &Hea2 Const adErrCatalogNotSet = &Hea3 Const adErrCantChangeConnection = &Hea4 Const adErrFieldsUpdateFailed = &Hea5 Const adErrDenyNotSupported = &Hea6 Const adErrDenyTypeNotSupported = &Hea7 Const adErrProviderNotSpecified = &Hea9 Const adErrConnectionStringTooLong = &Heaa '---- ParameterAttributesEnum Values ---Const adParamSigned = &H0010 Const adParamNullable = &H0040 Const adParamLong = &H0080 '---- ParameterDirectionEnum Values ---Const adParamUnknown = &H0000 Const adParamInput = &H0001 Const adParamOutput = &H0002 Const adParamInputOutput = &H0003 Const adParamReturnValue = &H0004 '---- CommandTypeEnum Values ---Const adCmdUnknown = &H0008 Const adCmdText = &H0001 Const adCmdTable = &H0002 Const adCmdStoredProc = &H0004 Const adCmdFile = &H0100 Const adCmdTableDirect = &H0200 '---- EventStatusEnum Values ---Const adStatusOK = &H0000001 Const adStatusErrorsOccurred = &H0000002 Const adStatusCantDeny = &H0000003 Const adStatusCancel = &H0000004 Const adStatusUnwantedEvent = &H0000005

InduSoft Web Studio

2943

IWS Training Guide

ADOVBS Constants

'---- EventReasonEnum Values ---Const adRsnAddNew = 1 Const adRsnDelete = 2 Const adRsnUpdate = 3 Const adRsnUndoUpdate = 4 Const adRsnUndoAddNew = 5 Const adRsnUndoDelete = 6 Const adRsnRequery = 7 Const adRsnResynch = 8 Const adRsnClose = 9 Const adRsnMove = 10 Const adRsnFirstChange = 11 Const adRsnMoveFirst = 12 Const adRsnMoveNext = 13 Const adRsnMovePrevious = 14 Const adRsnMoveLast = 15 '---- SchemaEnum Values ---Const adSchemaProviderSpecific = -1 Const adSchemaAsserts = 0 Const adSchemaCatalogs = 1 Const adSchemaCharacterSets = 2 Const adSchemaCollations = 3 Const adSchemaColumns = 4 Const adSchemaCheckConstraints = 5 Const adSchemaConstraintColumnUsage = 6 Const adSchemaConstraintTableUsage = 7 Const adSchemaKeyColumnUsage = 8 Const adSchemaReferentialConstraints = 9 Const adSchemaTableConstraints = 10 Const adSchemaColumnsDomainUsage = 11 Const adSchemaIndexes = 12 Const adSchemaColumnPrivileges = 13 Const adSchemaTablePrivileges = 14 Const adSchemaUsagePrivileges = 15 Const adSchemaProcedures = 16 Const adSchemaSchemata = 17 Const adSchemaSQLLanguages = 18 Const adSchemaStatistics = 19 Const adSchemaTables = 20 Const adSchemaTranslations = 21 Const adSchemaProviderTypes = 22 Const adSchemaViews = 23 Const adSchemaViewColumnUsage = 24 Const adSchemaViewTableUsage = 25 Const adSchemaProcedureParameters = 26 Const adSchemaForeignKeys = 27 Const adSchemaPrimaryKeys = 28 Const adSchemaProcedureColumns = 29 Const adSchemaDBInfoKeywords = 30 Const adSchemaDBInfoLiterals = 31 Const adSchemaCubes = 32 Const adSchemaDimensions = 33 Const adSchemaHierarchies = 34

2944

InduSoft Web Studio

ADOVBS Constants

IWS Training Guide

Const adSchemaLevels = 35 Const adSchemaMeasures = 36 Const adSchemaProperties = 37 Const adSchemaMembers = 38 Const adSchemaTrustees = 39 Const adSchemaFunctions = 40 Const adSchemaActions = 41 Const adSchemaCommands = 42 Const adSchemaSets = 43 '---- FieldStatusEnum Values ---Const adFieldOK = 0 Const adFieldCantConvertValue = 2 Const adFieldIsNull = 3 Const adFieldTruncated = 4 Const adFieldSignMismatch = 5 Const adFieldDataOverflow = 6 Const adFieldCantCreate = 7 Const adFieldUnavailable = 8 Const adFieldPermissionDenied = 9 Const adFieldIntegrityViolation = 10 Const adFieldSchemaViolation = 11 Const adFieldBadStatus = 12 Const adFieldDefault = 13 Const adFieldIgnore = 15 Const adFieldDoesNotExist = 16 Const adFieldInvalidURL = 17 Const adFieldResourceLocked = 18 Const adFieldResourceExists = 19 Const adFieldCannotComplete = 20 Const adFieldVolumeNotFound = 21 Const adFieldOutOfSpace = 22 Const adFieldCannotDeleteSource = 23 Const adFieldReadOnly = 24 Const adFieldResourceOutOfScope = 25 Const adFieldAlreadyExists = 26 Const adFieldPendingInsert = &H10000 Const adFieldPendingDelete = &H20000 Const adFieldPendingChange = &H40000 Const adFieldPendingUnknown = &H80000 Const adFieldPendingUnknownDelete = &H100000 '---- SeekEnum Values ---Const adSeekFirstEQ = &H1 Const adSeekLastEQ = &H2 Const adSeekAfterEQ = &H4 Const adSeekAfter = &H8 Const adSeekBeforeEQ = &H10 Const adSeekBefore = &H20

InduSoft Web Studio

2945

IWS Training Guide

ADOVBS Constants

'---- ADCPROP_UPDATECRITERIA_ENUM Values ---Const adCriteriaKey = 0 Const adCriteriaAllCols = 1 Const adCriteriaUpdCols = 2 Const adCriteriaTimeStamp = 3 '---- ADCPROP_ASYNCTHREADPRIORITY_ENUM Values ---Const adPriorityLowest = 1 Const adPriorityBelowNormal = 2 Const adPriorityNormal = 3 Const adPriorityAboveNormal = 4 Const adPriorityHighest = 5 '---- ADCPROP_AUTORECALC_ENUM Values ---Const adRecalcUpFront = 0 Const adRecalcAlways = 1 '---- ADCPROP_UPDATERESYNC_ENUM Values ---Const adResyncNone = 0 Const adResyncAutoIncrement = 1 Const adResyncConflicts = 2 Const adResyncUpdates = 4 Const adResyncInserts = 8 Const adResyncAll = 15 '---- MoveRecordOptionsEnum Values ---Const adMoveUnspecified = -1 Const adMoveOverWrite = 1 Const adMoveDontUpdateLinks = 2 Const adMoveAllowEmulation = 4 '---- CopyRecordOptionsEnum Values ---Const adCopyUnspecified = -1 Const adCopyOverWrite = 1 Const adCopyAllowEmulation = 4 Const adCopyNonRecursive = 2 '---- StreamTypeEnum Values ---Const adTypeBinary = 1 Const adTypeText = 2 '---- LineSeparatorEnum Values ---Const adLF = 10 Const adCR = 13 Const adCRLF = -1 '---- StreamOpenOptionsEnum Values ---Const adOpenStreamUnspecified = -1 Const adOpenStreamAsync = 1 Const adOpenStreamFromRecord = 4

2946

InduSoft Web Studio

ADOVBS Constants

IWS Training Guide

'---- StreamWriteEnum Values ---Const adWriteChar = 0 Const adWriteLine = 1 '---- SaveOptionsEnum Values ---Const adSaveCreateNotExist = 1 Const adSaveCreateOverWrite = 2 '---- FieldEnum Values ---Const adDefaultStream = -1 Const adRecordURL = -2 '---- StreamReadEnum Values ---Const adReadAll = -1 Const adReadLine = -2 '---- RecordTypeEnum Values ---Const adSimpleRecord = 0 Const adCollectionRecord = 1 Const adStructDoc = 2

InduSoft Web Studio

2947

IWS Training Guide

Exercise: Using ADO with VBScript

Exercise: Using ADO with VBScript


This Exercise will read data from an Access Database where Trend data is stored. It will read up to 10 records and display the results. To use this exercise, you must first have the Trend001 Worksheet configured to store data into a Microsoft Access Database (MyDB.mdb) located in the Application Folder, storing into the Table Trend001. Open the ADO.scr Screen Add a Button object, with the Caption Read From Trend Data Add a Command Dynamic Property, and select VBScript as the Type and add the following code: Dim database, strConn Dim db, rs, i, msg database = $GetAppPath() & "myDB.mdb" strConn = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source=" & database & ";" Set db = CreateObject("ADODB.Connection") db.open = strConn Set rs = CreateObject("ADODB.Recordset") Set rs = db.Execute("Select * FROM Trend001") msg = "" For i = 1 To 10 If Not rs.EOF Then msg = msg & rs("Time_Stamp") & " " msg = msg & rs("tank_1_temperature") & " msg = msg & rs("tank_2_temperature") & " msg = msg & rs("tank_3_temperature") & " msg = msg & vbCrLf rs.MoveNext End If Next MsgBox msg rs.close db.close Set rs = Nothing Set db = Nothing

" " "

Save and Close the Screen

2948

InduSoft Web Studio

Exercise: Using ADOX to create an blank Access Database

IWS Training Guide

Exercise: Using ADOX to create an blank Access Database


This Exercise will add VBScript code to the Startup Script to create a blank Microsoft Access Database named myDB.mdb stored in the project application folder if the database does not exist. We will use this database to store data (e.g. from the Trend001 Worksheet) which will be configured to store data into the Table Trend001. Open the Startup Script from the Script folder in the Tasks tab of the Workspace Add the following code:

Open the dialog box Project

Settings

Options

Default Database Configure

Put the following in the Connection String field Provider=Microsoft.Jet.OLEDB.4.0; Data Source= {your app path}\MyDB.mdb where {your app path} is the path to your application folder. Configure the Trend Worksheet(s) and Alarm/Events (via Project Database) to use the Relational Database Settings Options Alarm and Event

InduSoft Web Studio

2949

IWS Training Guide

Exercise: Using ADOX to create an blank Access Database

Notes

2950

InduSoft Web Studio

Chapter 30.

Reading & Writing XML using VBScript

XML (Extensible Markup Language) has become a commonly used language for transporting data in a crossplatform environment. It is a companion technology to HTML, but one does not replace the other. HTML is a standard used for displaying data (e.g. web pages) that has graphics and text, whereas XML is a standard used for structuring and transferring data. XML is a standard under the control of the World Wide Web Consortium (W3C), www.w3.org, In an InduSoft Web Studio (IWS) application, Recipes can be saved to or loaded from a file that is in XML format. These XML recipe files can be created in a separate computer and made available to the PC (or PCs) using the Recipe Manager. In addition to the Recipe Manager, IWS can create, read from, and write to XML files using VBScript. This is a powerful capability that can be utilized, for example, to transfer production data records (e.g. summary data, sample data) and reports from a PC running IWS to another PC or PDA that uses an XML Server. In this Chapter, we will cover two methods to create and manipulate XML files; ADO and the XMLDOM (Microsofts XML Parser). Using ADO is by far the simplest, and the XML file includes

Note: XML can be viewed by Microsoft Notepad, Wordpad or Word Microsoft XML Notepad 2007 is available free of charge. It is found at www.microsoft.com in the Downloads section.

Persisting Data in XML Format using ADO


ADO provides the ability to persist in XML format both Recordset Objects and Stream Objects using the Microsoft OLE DB Persistence Provider. This Provider generates a forward-only, read-only rowset from a saved XML file or Stream that contains the schema information generated by ADO. Similarly, it can take an ADO Recordset, generate XML, and save it to a file or any object that implements the COM IStream interface. (A file is just another example of an object that supports IStream.) ADO uses the Microsoft XML Parser (MSXML) to load the XML into the Recordset; therefore msxml.dll is required. Once the Data is in XML format, XSLT (XML Style Sheet Language) can be used to transform the XML data into an HTML table.

Note: XSLT scripts can be used to transform XML into HTML Tables Many higher-level databases such as SQL Server can store data in XML format. A Recordset can be saved directly into the XML DOM object for further processing.

InduSoft Web Studio

301

IWS Training Guide

Persisting Data in XML Format using ADO

The following example uses persists an ADO Recordset using adPersistXML Const adPersistXML = 1 Const adVarChar = 200 Const MaxCharacters = 70 Const adFldIsNullable = 32 Dim fso, XMLRS, i ' Delete any existing XML file Set fso = CreateObject("Scripting.FileSystemObject") If fso.fileexists($myXMLFile) Then fso.deletefile $myXMLFile End If ' Write to the XML file Set XMLRS = CreateObject("ADODB.Recordset") XMLRS.Fields.Append "Line", adVarChar, MaxCharacters, adFldIsNullable XMLRS.Fields.Append "Machine", adVarChar, MaxCharacters, adFldIsNullable XMLRS.Fields.Append "Alarms", adVarChar, MaxCharacters, adFldIsNullable XMLRS.Fields.Append "Output", adVarChar, MaxCharacters, adFldIsNullable XMLRS.Open For i = 0 To 3 XMLRS.AddNew XMLRS("Line") = $eData[i].Line XMLRS("Machine") = $eData[i].Machine XMLRS("Alarms") = $eData[i].Alarms XMLRS("Output") = $eData[i].Output Next XMLRS.Update XMLRS.Sort = "Line" XMLRS.Save $myXMLFile, adPersistXML XMLRS.Close Set XMLRS = Nothing Set fso = Nothing

The following example saves a ADO Recordset to the XML DOM Object
Dim oConn, oRS, oXMLDOM, stm, StrRst Const adPersistADO =1 Set oConn = CreateObject("ADODB.Connection") Set oRS = CreateObject("ADODB.Recordset") Set oXMLDOM = CreateObject(MSXML.DOMDocument) oConn.Provider = "Microsoft.Jet.OLEDB.4.0" oConn.Properties("Data Source").value = $GetAppPath()& "MachineInfo.mdb" oConn.Open Set oRS = oConn.Execute ("Select * From Table1") oRS.Save oXMLDOM, adPersistADO Notes: adPersistADO indicates that ADOs own Extensible Markup language format (XML) will be used. The XMLDOM can be used to add additional XML.

302

InduSoft Web Studio

Using the XMLDOM

IWS Training Guide

The ADO Stream Object, as previously shown, provides the means to read, write, and manage a stream of bytes. This byte stream may be text or binary and is limited in size only by system resources. Typically, ADO Stream objects are used to contain the data of a Recordset saved in XML format This Example saves a Recordset to a file and then to a Stream. It then opens the persisted stream into another Recordset. Dim con, rs1, rs2, stm, StrRst Const adPersistXML =1 Set con = CreateObject("ADODB.Connection") Set rs1 = CreateObject("ADODB.Recordset") Set rs2 = CreateObject("ADODB.Recordset") Set stm = CreateObject("ADODB.Stream") con.Provider = "Microsoft.Jet.OLEDB.4.0" con.Properties("Data Source").value = $GetAppPath()& "MachineInfo.mdb" con.Open Set rs1 = con.Execute ("Select * From Table1") rs1.Save $GetAppPath()& "MachineInfo.xml", adPersistXML rs1.Save stm, adPersistXML rs2.Open stm This Example persists a Recordset into a Stream in XML format. It then reads the Stream into a string that you can examine, manipulate, or display. Dim con, rs, stm, StrRst Const adReadAll = -1 Const adPersistXML =1 Set con = CreateObject("ADODB.Connection") Set rs = CreateObject("ADODB.Recordset") Set stm = CreateObject("ADODB.Stream") con.Provider = "Microsoft.Jet.OLEDB.4.0" con.Properties("Data Source").value = $GetAppPath()& "MachineInfo.mdb" con.Open Set rs = con.Execute ("Select * From Table1") rs.Save stm, adPersistXML strRst = stm.ReadText (adReadAll) 'Display the XML data. MsgBox strRst

Using the XMLDOM


Please refer to Application Note AN-00-0004

InduSoft Web Studio

303

IWS Training Guide

Using the XMLDOM

Notes

304

InduSoft Web Studio

Chapter 31.
ActiveX Overview

ActiveX Controls and .NET Assemblies

ActiveX is a loosely defined set of Microsoft technologies developed for common program execution and the sharing of information between two or more applications that run on a Microsoft Windows OS. ActiveX is the outgrowth of other Microsoft technologies such as OLE (Object Linking and Embedding) and COM (Component Object Model). When most people refer to ActiveX, they are referring to ActiveX Controls which are modular programs designed to execute at the system level in conjunction with an application. ActiveX has a set of rules on how applications should share information. The power of ActiveX comes from the ability of an ActiveX Control to have full access to the underlying Windows Operating System. ActiveX Controls must be registered with the Windows System Registry prior to their use. IWS is a Container for ActiveX Controls. This means that 3 party Controls can be added to an IWS application, and IWS will have access to their various Properties, Methods and Events.
rd

Installing an ActiveX Control


An ActiveX Control is typically a file with an .OCX (or .DLL) file extension. A single .OCX DLL can contain any number of ActiveX Controls. The .OCX or .DLL file is generally copied during the installation process of the ActiveX control, and the location where the file is installed is not important. However, the ActiveX Control must be registered with the Windows System Registry. This is done using one of a few methods: The ActiveX Control is registered during the installation process (this is generally the case) Run the Regsvr32 command using the Windows Command Line processor (e.g. Start Regsvr32 file) Use the IWS Register Controls Tool (from the Main Menu Bar, Tools Use another ActiveX Registration Tool (there are several available) Run CMD

Register Controls)

Note: If you use an ActiveX Control in an application, you may need to seperately install the ActiveX Control in the Web Thin Client.

Inserting an ActiveX Control


An ActiveX Control can be used with an IWS application by either: Using the IWS OCX Tool (located in the Active Objects Toolbar) to select and insert an ActiveX Control onto an Application Screen Instantiating an ActiveX Control from VBScript using the CreateObject statement In order for an ActiveX Control to be viewable on an Application Screen, it must be inserted using the OCX Tool. Once the OCX tool is activated, an Insert ActiveX Control dialog box will appear, allowing you to select the ActiveX Control that you want to insert on the Screen. Once the ActiveX Control is inserted on the Application Screen, the graphical interface object can be selected and repositioned on the Display Screen. Certain Dynamic Properties (e.g. Command Dynamic, Position (including visibility), and Size) can be added to the ActiveX Control. By double-clicking on the ActiveX object, you can access its Object Properties. For example, the Microsoft Slider

InduSoft Web Studio

311

IWS Training Guide

Using the XMLDOM

ActiveX Control (as shown) will have a Object Properties dialog box as show. The Name of the Object will have a numeric (integer) value behind it that changes for each time the ActiveX Control is used in the Application. This Name can be changed, but it must be unique within the Application. The Property Pages button provides access to settings that change the look and feel of the ActiveX Control. The Configuration button provides access to the ActiveX Controls Properties, Methods and Events.

Once the ActiveX Control is inserted onto an Application Screen, its Properties, Methods and Events can be accessed from the Object Properties dialog box, and the ActiveX Controls Properties and Methods can be accessed from VBScript code in either the Screen Script or in a Command Dynamic associated with an IWS object placed on the same Application Screen. If the ActiveX Control is instantiated using the CreateObject statement from VBScript, it will not be visible on an Application Screen and can only be used from the VBScript code segment that created it.

ActiveX Properties, Methods and Events


ActiveX Controls can have Properties, Methods and Events. Each of these serves a different purpose. Properties Properties are attributes or characteristics of an ActiveX Control. . ActiveX Controls are not required to have Properties or expose them to the User Interface, although most ActiveX Controls do include Properties. Properties can be read only, write only, or read-write. Methods Methods are specific functions that the ActiveX Control performs. ActiveX Controls are not required to have any Methods, or expose them to the User Interface, although most ActiveX Controls do include Methods.. Events Events are notifications generated by the ActiveX Control, based upon a specified Event (or action) occurring. ActiveX Controls are not required to have any Events, or expose them to the User Interface, although most ActiveX Controls do include Events. The ActiveX Control usually fires an event based upon a User action (e.g. click, double click, Error, etc.). The Configuration dialog box has the Events tab that allows selection of the type of event and what, if any, IWS Script or VBScript code should be executed when the Event fires.

312

InduSoft Web Studio

Using the XMLDOM

IWS Training Guide

From the Configuration dialog box (of the Object Properties) for the ActiveX Control, IWS Tags or Expressions can be used in the Tag/Expression field for the ActiveX Controls Properties and Methods. Events have a Parameter field that allows for the triggering of an Event, and a Script field that can be used to define the Script (IWS Script of VBScript) to be executed when the specific Event fires. Notes: In the Configuration dialog box, IWS Tags and Expressions can be entered in the Tag/Expression field for Properties and Methods. In the Configuration dialog box, IWS Script or VBScript can be defined to execute when an Event fires The ActiveX Object Name can be change in the Object Properties dialog box From VBScript, an ActiveX Object inserted on an Application Screen can be used by referencing the Name of the ActiveX Object and the Property or Method. ActiveX Events cannot be accessed from VBScript. You need to use the Configuration dialog box of the Object Properties ActiveX Controls are identified by their Program ID (ProgID) or Class ID (CLSID)

.NET Overview
Microsofts .NET architecture is an outgrowth of Microsoft DNA (Distributed Network Architecture), developed to address network-based applications. The principle concept is that the .NET architecture erases the boundary between the application and the network. In principle, .NET connects the user to an array of computers and services that can exchange and combine objects and data. Thus, users will have access to information from any device, any time, any where using the Internet (or Intranet). The .NET architecture is built on the following technologies: HTTP (Hypertext Transfer Protocol, the underlying protocol for transfer of information over the World Wide Web), XML (Extensible Markup Language, a W3C or World Wide Web Consortium specification for how data is transmitted between applications in an operating system-independent and applications-independent method), SOAP (Simple Object Access Protocol, a light weight XML-based messaging protocol used information exchange between applications that are operating system-independent and applications-independent), and UDDI (Universal Description, Discovery and Integration, a web-based distributed directory that allows discovery of .NET applications). In the .NET Framework, a .NET Assembly is the .NET corollary to an ActiveX Control. C# or VB.NET code is compiled into an intermediate language known as the Common Intermediate Language (CIL). Microsofts CIL is also knows as Microsoft Intermediate Language (MSIL), and is a just-in-time compiled code. This MSIL code is housed in what is called a .NET Assembly, a portable executable file (.EXE or .DLL). An Assembly is a .NET unit of deployment, versioning, and security. Unlike ActiveX Controls, which after being registered have a Program ID and Class ID, .NET Assemblies are known by their Namespace, a unique identifier. IWS is a Container for .NET Assemblies. This means that 3rd party .NET Assemblies (also called .NET Controls) can be used in an IWS application, and that the IWS application will have access to the .NET Assemblys Properties, Methods, and Events. The Microsoft .NET 2.0 Framework is required for WS to be a .NET container. The WS v.6.5 installation installs the .NET 2.0 Framework (updated from 1.1)

InduSoft Web Studio

313

IWS Training Guide

Using the XMLDOM

Installing a .NET Assembly


Unlike ActiveX Controls which can be installed into any folder but need to be registered with the System Registry, a .NET Assembly must be installed into one of two specific folders but does not need to be registered with the System Registry. So where does a .NET Assembly go? The answer is that it needs to go into one of two places. The first is the GAC, or Global Assembly Cache. With Windows XP Pro, this can be found in C:\Windows\Assembly. The second place it can go is into the IWS Application folder.

Inserting a .NET Assembly


A .NET Assembly can be inserted onto an IWS Application Screen by clicking on the .NET Tool icon found in the Active Objects Toolbar. A .NET Framework Components dialog box will open, and a list of .NET Assemblies will appear. Select the Assembly of interest and press OK.

The .NET Assembly graphical interface will now appear on the IWS Application Screen. You can double click on the .NET Assembly to access the Object Properties dialog box, providing access to the Property Pages and the Members dialog box (provides access to Properties, Methods and Events). As with the ActiveX Control(s), you can change the name of the .NET Assembly as it is referenced from IWS by changing the name in the Name field.

314

InduSoft Web Studio

Using the XMLDOM

IWS Training Guide

Key differences between ActiveX and .NET Assemblies


.NET Assemblies dont have to be registered but they must be located in GAC (Global Assembly Cache) or in the Application Folder. Some commentators advise to keep GAC as clean as possible, so put .NET controls in application folder. ActiveX Properties, Methods and Events can be accessed by VBScript. Currently, the Properties, Methods and Events for .NET Assemblies can only be configured on an IWS Screen and the Tag/Expression field used. VBScript is not an option since VBScript is not a .NET language.

InduSoft Web Studio

315

IWS Training Guide

Exercise: Inserting an ActiveX Control

Exercise: Inserting an ActiveX Control


In this exercise, we will insert an ActiveX control onto a Screen and read one of its Properties using VBScript. Open the ActiveX.scr Screen (or create it) Click on the ActiveX Tool in the Active Objects Toolbar In the Insert ActiveX Control dialog box, locate the ActiveX control Microsoft Slider Control 6.0 and click on it to select it. Click the OK button to insert this Control on to the Screen Double click on the Slider ActiveX Control (or right mouse click) and when the Object Properties dialog box opens, change its name to Slider1. Close the Object Properties dialog box.

Move your mouse cursor to a blank area of the Screen and click the right mouse button Select the Screen Script option. Insert the VBScript code as shown:

Save and Close the Screen Script. Specify v6 to be an Integer Tag.

316

InduSoft Web Studio

Exercise: Inserting an ActiveX Control

IWS Training Guide

On the ActiveX.scr Screen, insert a Text Object with the caption Slider value = ####, add a Text I/O Property with the Tag set to v6.

Save and Close the ActiveX.scr Screen

InduSoft Web Studio

317

IWS Training Guide

System.Collections

System.Collections
While the general rule is VBScript does not have access to the .NET Framework Classes (i.e. doesnt support .NET Assemblies), there are some .NET Classes that have COM-callable wrappers. One example of these .NET Classes are the System.Collections provided by Microsoft. The Namespace for this Class is System.Collections and is included in the Mscorlib Assembly (mscorlib.dll). The System.Collections Class is available for most Windows Platforms including Windows XP, Server 2003, Vista (with .NET 3.0) and Windows CE (with .NET Compact Framework 1.0 or 2.0). The System.Collections Class supports certain functions that can be quite useful, depending on your application. These functions include: ArrayList Queue Stack HashTable SortedList

ArrayList
The ArrayList can be useful for creating, copying and sorting an Array. Methods Add AddRange Clear

Clone Contains CopyTo (Array) CopyTo (Array, Int32) Get Range Insert Insert Range Remove Remove At Remove Range Repeat Reverse Reverse (Int32, Int32) Estrange Sort To Array

Adds an object to the end of the ArrayList. Value can be null (Nothing). Return value is the ArrayList index at which the value has been added. Adds the elements of a Collection to the end of the ArrayList Object. The order of the elements in the Collection is preserved in the ArrayList Removes all elements from the ArrayList. Count is set to zero, and references to other objects from elements of the Collection are released. Does not effect capacity. Not supported when ArrayList is read-only or fixed size. Creates a shallow copy of the ArrayList (i.e. contains elements of the collection but does not copy objects referenced) Determines whether an element is in the ArrayList. Returns true if found, otherwise false. Performs a linear search Copies the entire ArrayList to a compatible one-dimensional array, starting at the beginning index Copies the entire ArrayList to a compatible one-dimensional Array, starting at the specified index of the target array. Returns an ArrayList which represents a subset of the elements in the source ArrayList Inserts an element into the ArrayList at a specified index Inserts elements of a collection into an ArrayList at the specified index Removes the first occurrence of the specified object Removes the element at the specified index Removes a range of elements from the ArrayList Creates a new ArrayList whose elements are copies of the specified value Reverses the order of the elements of the entire ArrayList Reverses the order of the elements in the specified range Copies the elements of a collection over a range of elements in the ArrayList Sorts the elements in the entire ArrayList Copies the elements of the ArrayList to a new Array

318

InduSoft Web Studio

System.Collections

IWS Training Guide

Properties Capacity Count IsFixedSize IsReadOnly IsSynchronized Item SyncRoot

Gets or sets the number of elements that ArrayList can contain Gets the number of elements actually contained in the ArrayList Gets a boolean value indicating whether the ArrayList has a fixed size (true (default) if fixed size, otherwise false) Gets a boolean value indicating whether the ArrayList is read-only (true if read only, otherwise false (default)) Gets a boolean value indicating whether access to the ArrayList is synchronized (thread safe) Gets or sets the element at the specified index Gets an Object that can be used to synchronize access to the ArrayList

Example VBScript ' Create an empty ArrayList, and add some elements. Dim myAL, i, msg Set myAL=CreateObject("System.Collections.Arraylist") myAL.Add("a") myAL.Add("abc") myAL.Add("abcdef") myAL.Add("abcdefg") myAL.Insert 0, "xyz" myAL.Insert 1, "uvwxyz" msg = "Number of elements in the list is " & myAL.Count & vbCrLf For i = 0 To myAL.count-1 msg = msg & "Element " & i & " Is " & myAL(i) & vbCrLf Next MsgBox msg

InduSoft Web Studio

319

IWS Training Guide

System.Collections

Queue
A Queue is a first-in, first-out collection of Objects and can be useful for storing messages in the order they were received for sequential processing of the messages. Queue elements can be null values. Methods Clear Contains CopyTo Dequeue Enqueue Equals GetEnumerator ToArray

Removes all objects from the Queue. Determines whether an element is in the Queue Copies the Queue elements to an existing one-dimensional Array, starting at the specified array index Removes and returns the object at the beginning of the Queue. Adds an object to the end of the Queue. Overloaded. Determines whether two Object instances are equal. (inherited from Object) Returns an enumerator that iterates through the Queue. Copies the Queue elements to a new Array

Properties Count

Gets the number of elements contained in the Queue.

VBScript Example Dim myQueue, msg Set myQueue=CreateObject("System.Collections.Queue") myQueue.Enqueue("one") myQueue.Enqueue("two") myQueue.Enqueue("three") myQueue.Enqueue("four") myQueue.Enqueue("five") Msg = "total entries = " & myQueue.count & vbCrLf Msg = msg & "Peek at first element in queue= " & myQueue.Peek() & vbCrLf msg = msg & "Deque first entry = " & myQueue.Dequeue() & vbCrLf msg = msg & "New count = " & myQueue.count & vbCrLf Msg = msg & "Peek at new first element in queue= " & myQueue.Peek() & vbCrLf MsgBox msg

3110

InduSoft Web Studio

System.Collections

IWS Training Guide

Stack
A Stack is a last-in, first-out collection of Objects (compared to the Queue which is a first-in, first-out collection). Methods Clear Clone Contains CopyTo Equals GetHashCode GetType Peek Pop Push ReferenceEquals Synchronized ToArray ToString

Removes all objects from the Stack. Creates a shallow copy of the Stack. Determines whether an element is in the Stack. Copies the Stack to an existing one-dimensional Array, starting at the specified array index. Overloaded. Determines whether two Object instances are equal. (inherited from Object) Serves as a hash function for a particular type. (inherited from Object) Gets the Type of the current instance. (inherited from Object) Returns the object at the top of the Stack without removing it. Removes and returns the object at the top of the Stack. Inserts an object at the top of the Stack. Determines whether the specified Object instances are the same instance. (inherited from Object) Returns a synchronized (thread safe) wrapper for the Stack. Copies the Stack to a new array. Returns a String that represents the current Object. (inherited from Object)

Properties Count

Gets the number of elements contained in the Queue.

VBScript Example Dim stack Set stack=CreateObject("System.Collections.Stack") stack.Push("Hello") stack.Push("World") MsgBox "Count = " & stack.count & " Top value = " & stack.Peek stack.Pop MsgBox "Count after popping = " & stack.count

InduSoft Web Studio

3111

IWS Training Guide

System.Collections

Random
The System.Random Class provides a pseudo-random generator. While VBScript provides a random number generator function, the System.Random Class is easier to use. Methods Random.Next Random.Next_2 (Int32, Int32) Randon.NextDouble

Returns a nonnegative random number. Returns a random number within a specified range. Returns a random number between 0.0 and 1.0 (double-precision floating point)

VBScript Example Set oRandom=CreateObject("System.Random") MsgBox oRandom.Next (1,100)

3112

InduSoft Web Studio

Chapter 32.

Web Thin Clients

IWS is built on a Client/Server architecture, and you can support both Thin Clients and Thick Client. The choice of the type of Client architecture depends upon your system requirements. Thin Client A Thin (Lean) Client is a computer that depends primarily on the central Server for processing activities. The Thin Client needs to have a processor with minimal memory, a browser (Internet Explorer) and a network connection (e.g. to the Internet or Intranet). InduSoft uses the terminology Web Client to refer to a Thin Client solution. IWS lets you choose the type of browser that is best for your runtime environment: Microsoft Internet Explorer. This type of browser is best for desktop or remote access environments. InduSofts Secure Viewer, a dedicated viewer for IWS applications. Secure Viewer does not let the user browse to other websites, and will only connect to a specified IWS Server. Secure Viewer is intended for plant floor environments were browsing to other web sites is not required or desired.

Thick Client. A Thick (Fat) Client is a computer that performs most, if not all, of the processing activity. The Thick Client has sufficient processing power, memory, memory, graphics, etc. to run the application. The Thick Client can exchange data with the Server as required (e.g. archival of data, program synchronization). A Server can also be a Thick Client to another Server. In this chapter, we will explore using Web Thin Clients with IWS. Thick Clients will be covered in a subsequent chapter.

Web Thin Clients in IWS


IWS allows you to create screens that can be visualized in a remote station a regular web browser (e.g. Internet Explorer). The station where the user can visualize the graphical interface (screens) on the web browser is called the Web Thin Client. The Thin Client (Browser) is the host.

Typical Web Thin Client Architecture IWS is installed on the Server station only. Also, the application (screen files, tags database, configuration worksheets, etc.) is stored on the Server only. You do not need to install IWS or the application on the Web Thin Client. This solution provides a high level of flexibility because any computer physically linked to the Server station (via a TCP/IP link) can access the graphical screen and online/history data from the Server without installing IWS or the application on the Web Thin Client stations.

InduSoft Web Studio

321

IWS Training Guide

System.Collections

All background tasks (Math, Scheduler etc) and communication tasks (e.g. Driver, OPC, DDE TCP/IP) are executed only on the Server station. The Web Thin Client is able to load the graphical interface configured on the Server (screens with objects and dynamics) and display the online values from the tags configured in the server, as well as history data (Alarm, Events and Trend history data). Note: Since VBScript and the IWS Scripting Language can be associated with a screen as well as a Command Dynamic for an Object, these Scripts can execute on a Web Thin Client.

Any computer or device (e.g. a PDA powered with Windows CE) running Microsoft Internet Explorer 6.0 (or higher) browser or InduSofts Secure Viewer browser can be a Web Thin Client for an IWS application. Moreover, IWS provides a sophisticated Security System to prohibit unauthorized access to the application From the Web Thin Client, you are able to visualize data from the Server and capable of changing set points, acknowledging alarms and/or sending commands to the Server. When configuring the application, you can optionally enable or disable all commands from the Web Thin Client to the Server. Even if the Server has disabled all command from the Web Thin Client, the Web Thin Client can still read data from the Server but cannot send any data to the Server.

InduSoft Web Thin Client Competitive Advantages


InduSoft is built on a Client/Server architecture that supports true Web Thin Clients. This capability is built-in to IWS and is not an add-on. This means that: The IWS Server supports a large number of concurrent Thin Clients (up to 128 IE-based and 128 Secure Viewer-based). Each Web Thin Client can view the same or different screens as another Web Thin Client. The IWS Server knows which display each Web Thin Client viewing and automatically pushes any updated Tag values to the Web Thin Client, keeping the Thin Client display current and eliminating the need for screen refreshes The IWS Server can support runtime language switching for each Web Thin Client. This means that one Web Thin Client can be viewing a screen in English while another Web Thin Client can display the same screen in Spanish.

Many competitive products offer either a static display on a Thin Client (i.e. it must be manually refreshed to get the latest data), a Terminal Server solution (requires the Server to build multiple instances of the application to support each Thin Client), or offer a Thin Client solution similar to IWS but with expensive add-on software products. Other InduSoft Web Thin Client advantages include: Optional Secure Viewer that does not allow navigation outside the IWS application. Secure Viewer is not based on Microsofts Internet Explorer. Ability to run VBScript and IWS Scripting Language on the Web Thin Client Can build Web Thin Client applications using Windows CE devices as the Server. Ability to support redundant Web Servers and Data Servers, with automatic switchover.

InduSoft Web Thin Client Licensing


The maximum number of Web Thin Client stations connected simultaneously to the Server depends on the settings of the license installed on the Server. The user does not have to install any license on the Web Thin Client.

322

InduSoft Web Studio

Building a Simple Web Thin Client Application Step by Step

IWS Training Guide

Building a Simple Web Thin Client Application Step by Step


As we will see shortly, there is no one way to build a Web Thin Client application. The following procedures allow you to develop a simple, unsecured Web Thin Client application.

Procedure A: Web Thin Client using NTWebServer, Local Loopback


An easy way to initially develop and test a Web Thin Client application is to use the InduSoft light-weight Web Server NTWebServer on your development PC, initiate the application runtime and use Microsoft Internet Explorer on the same PC to display the Web pages.

Step 1: Configure IWS Settings In the Development Environment, select Project Settings Web (tab).
In the Data Server IP Address field, enter 127.0.0.1 Check the Auto Screen Scaling, Enable File Compression, and Enable Tooltips checkboxes are checked - Click on the IP Security Button. Be sure then Enable checkbox is unchecked. Click OK. - Click on the Advanced Button. Be sure the Web Tunneling Gateway Enabled checkbox is unchecked. Click OK. Select Project Status Execution and be sure the TCP/IP Server task is set to Automatic -

Step 2: Configure Database In the Development Environment, select the Database


tab of the Workspace. Open the Applications Tags folder.

Be sure the application tags are properly set to either Server or Local. If the tags are to be exposed to the Web Client, then set them to Server, otherwise set to Local.

Step 3: Develop your Screens and create HTML screens


Develop your application screen. Depending on your Web Thin Client screen size, you may want to develop a separate set of screens with a different resolution. Auto Screen scaling is supported (enabled in a prior step), but auto screen scaling naturally has limitations. Save and Close all application screens Be sure you have defined a Startup Screen (Project Settings the Startup Screen in the Startup Screen field (e.g. startup.sg). Runtime Desktop (tab). Specify

In the Development Environment, select File from the Main Menu Bar. You can save individual display screens as HTML using the Save as HTML or Save Screen Group as HTML, or save all Screens and Screen Groups as HTML by selecting the Save All as HTML option. If you are just updating a Screen, and especially when you make any configuration changes to the Web settings, you should run the Verify Application tool (Tools Verify Application) from the Main Menu Bar. The HTML (web) pages will be stored in the \Web sub-folder of your application folder.

InduSoft Web Studio

323

IWS Training Guide

Building a Simple Web Thin Client Application Step by Step

Step 4: Install NTWebServer


NTWebServer is InduSofts light-weight Web Server for Windows NT/XP/2000/Server 2003/Vista environments. NTWebServer.exe is found in the \Bin folder of the IWS program installation folder (generally c:\Programs and Files\InduSoft Web Studio v6.1\Bin Copy NTWebServer.exe from the \Bin folder and paste it into the \Web sub-folder of your Application folder. From the \Web sub-folder, double click on NTWebServer to start it. A new window should pop-up. At the bottom, there should be a message indicating that NTWebServer is listening. If a message appears that NTWebServer failed to open a socket, it is most likely caused by Microsoft IIS (Web Server) running in a background mode. If this is the case, you will need to stop IIS, and then restart NTWebServer

Step 5: Start the Application Runtime


From the Development Environment, click on the Run application button to start the runtime.

Step 6: Launch Microsoft Internet Explorer and connect to the Web Server
Click on the Start button (or Alt Tab) to access the Microsoft Internet Explorer program. Start Internet Explorer, and http://127.0.0.1/startup.html type the address of the starting (home webpage). E.g.

Note that the startup.sg (or whatever your startup display or screen group name is) will have a HTML file extension on it when accessed from Internet Explorer. Sign on as Guest with no password, assuming no security has been enabled.

Procedure B: Web Thin Client using NTWebServer, Network IP


Once Procedure A has been completed, the next step is to enable network connected Web Thin Clients, instead of using the local loopback. You need to know the IP address of your PC, as seen from the network. You can get this information from the Network Settings in the Control Panel, or putting the function GetComputerIP() in a Rectangle Object on a screen and running the application.

Step 1: Configure IWS Settings


Stop any active application runtime. In the Development Environment, select Project Settings Web (tab). In the Data Server IP Address field, enter the IP address of your PC (as viewed from the network). E.g. 192.168.1.100 Run the Verify Application tool (Tools Verify Application). This will set change the Data Server IP address in the web pages, so that the Web Thin Client will automatically exchange data with the correct Data Server.

Step 2: Start the Application Runtime


From the Development Environment, click on the Run application button to start the runtime. Be sure NTWebServer is still running.

Step 3: Launch Microsoft Internet Explorer and connect to the Web Server
Click on the Start button (or Alt Tab) to access the Microsoft Internet Explorer program. Start Internet Explorer, and http://192.168.1.100/startup.html type the address of the starting (home webpage). E.g.

Sign on as Guest with no password, assuming no security has been enabled.

324

InduSoft Web Studio

Building a Simple Web Thin Client Application Step by Step

IWS Training Guide

Procedure C: Web Thin Client using IIS, Network IP


Once Procedure B has been completed, the next step is to enable IIS to become the Web Server for your Web Thin Clients instead of NTWebServer. The following are the basic steps to configuring IIS, although depending on your network and Operating System environment, additional settings may need to be configured such as user security.

Step 1: Configure IWS Settings


Be sure NTWebServer is terminated. Click the Start button, then Control Panel Administrative Tools Select (click on) Internet Information Services Expand the Web Sites tree structure to see the Default Web Site Right click on the Default Web Site and select Properties to get the Default Web Site Properties dialog box.

InduSoft Web Studio

325

IWS Training Guide

Building a Simple Web Thin Client Application Step by Step

Click on the Home Directory tab. Click on the Local Path Browse button and point to your applications \Web subfolder. Click on the Web Site tab. Make sure the TCP port is set to 80. You can click the Advanced button to enable the IIS Web Server to respond to specific IP addresses and IP Port numbers. If your Web Server is behind a Proxy, be sure to check the HTTP Keep-Alives Enabled checkbox. It does not hurt anything if this is always checked.

326

InduSoft Web Studio

Building a Simple Web Thin Client Application Step by Step

IWS Training Guide

Click on the HTTP Headers tab. Click on the MIME Map File Types button to open the File Types dialog box. Next, click on the New Type button to add a new MIME type. Put the file extension in the Associated Extension field. In the Content type (MIME) field, put MIME type followed by a / character, followed by the file extension name (application/IWS). E.g.

Associated Extension: .scc Content Type: application/IWS

InduSoft Web Studio

327

IWS Training Guide

Building a Simple Web Thin Client Application Step by Step

About MIMEs MIME, or Multipurpose Internet Mail Extensions, types instruct a Web browser how to handle files received from a server. For example, when a Web browser requests an item on a server, it also requests the MIME type of the object. Some MIME types, like graphics, can be displayed inside the browser. Others, such as word processing documents, require an external helper application to be displayed. When IIS delivers a Web page to a client Web browser, it also sends the MIME type of the data it is sending. If there is an attached or embedded file in a specific format, IIS also tells the client application the MIME type of the embedded or attached file. The client application then knows how to process or display the data being received from IIS. IIS serves only files with known extensions registered in the MIME types list or with the operating system. IIS allows you to configure additional MIME types and change or remove MIME types. Removing a MIME type in IIS does not block access to that MIME type by other applications if it is also registered with the operating system. IIS is preconfigured to recognize a default set of global MIME types. These MIME types are recognized by all Web sites you create in IIS. MIME types can also be defined at the Web site and directory levels, independent of one another or the types defined globally. When you view MIME types at the Web site or directory level, only the types unique to that level are displayed, not all types inherited from the next level up. IIS returns a 404.3 error if a client request refers to a file name extension that is not defined in the MIME types MIME configuration is usually only required for Windows Server 2003, not Windows XP or Vista due to Windows 2003 default settings. MIME types should include all file extensions found in the \Web directory. These include: - .app - .bin - .csv - .gis - .html - .ico - .ini - .lst - .scc - .sg - .stmp - .tra - .txt

Click on the Directory Security tab. From this tab, you can change the settings for Anonymous User Access and Authentication Control as well as Secure Communications (i.e. using SSL 3.0). Click on the Anonymous User Access and Authentication Control Edit button to get the Authentication Methods dialog box. Normally, you do not have to do anything in this dialog box but depending on the Security system your network administrator has installed, you may need to adjust settings in this dialog box. The Secure Communications Server Certificate button opens a wizard that lets you define a Certificate for support of secure communications using SSL.

328

InduSoft Web Studio

Building a Simple Web Thin Client Application Step by Step

IWS Training Guide

Step 2: Start IIS and start the IWS Application


Be sure NTWebServer is terminated. Click on the IIS Start button Start up the IWS Application

InduSoft Web Studio

329

IWS Training Guide

Building a Simple Web Thin Client Application Step by Step

Notes: If IIS is not installed on your PC, you can add it (to Windows XP Pro/Windows 2000 or Windows Server 2003) by opening the Control Panel, then selecting Add/Remove Programs Add/Remove Windows Components and checking the Internet Information Services (IIS) checkbox in the Windows Components Wizard. You can click on the Details button to select various components of IIS to install. Note that you may need to have your Windows installation disk. You can get more information on IIS by opening a browser and entering http://localhost/iishelp in the browser navigation address bar. Note that IIS must be running. NTWebServer is a Windows Application, while IIS is a Windows Service. It is STRONGLY SUGGESTED that you use IIS instead of NTWebServer in a runtime mode. It is more reliable and higher performance than NTWebServer.

Troubleshooting: If you get a Cannot find Server error message, - From the browser, ping the server IP address (primary and/or backup). You can ping using the IP address or use the NetBios name to ping the server (e.g. from a command prompt enter Ping 152.57.100.25 or Ping ServerName. - Be sure IIS is running - Be sure your IWS application is running - Make sure the TCP/IP Server (in the IWS Application) is running - Be sure IIS is set to the correct Home Page (root directory). - Be sure the Port addresses are correct (HTTP Port 80, HTTPS (SSL) Port 443, Data Port 1234) - Make sure you firewall has these ports open - If you are using a Windows CE-based device, be sure ISSymbol is properly loaded and registered - Be sure your runtime license supports the Web Client configuration If you get a Page cannot be displayed error message, - From the browser, ping the server IP address - Stop and restart IIS - Be sure the MIME types are properly set - Make sure you updated your web pages (i.e. Save as HTML) and use the Verify Application tool if you change any Web settings. - Verify the Windows security settings are properly set - Be sure that the Screen name (and Web Page name) do not have any spaces in the name If the web pages are incorrect: - Be sure you are pointing to the correct primary URL - Be sure your backup URL (if you use it) has the correct (updated) web pages

3210

InduSoft Web Studio

Web Thin Clients The Underlying Technology

IWS Training Guide

Web Thin Clients The Underlying Technology


In an IWS Application, there are several components used to implement the Web Thin Client capability.

Server IWS Application Data Server IWS TCP/IP Server Data Push TCP/IP Port 1234

Web Client ISSymbol (IWS) ActiveX Downloads: - Screens - Database files Web Tunneling Gateway (WTC) Performs security Launches virtual TCP/IP Client to communicate between Data Server and Web Client HTTP: TCP/IP Port 80 SSL (HTTPS): Port 443 Will exchange Tag data based on settings IE 6/IE 7 Web Browser or Secure Viewer

IWS Tag Database Server Web Pages Web Server E.g. IWS NTWebServer, CEWebServer, IIS, Apache

Screen HTML Files

These components are: Data Server The Data Server is built-in to the IWS runtime. The Data Server has direct access to the IWS Application Tags Database (runtime) and is responsible for working with ISSymbol to make sure any Tag data being displayed on a Web page at any Web Thin Client is updated with the latest value(s). IWS can support a backup or secondary Data Server that will be used should the Primary Data Server become unavailable. The Web Thin Client will automatically switch over to the Secondary without user intervention required. Web Server The Primary Web Server is responsible for providing Web pages on demand (i.e. when requested by the Client) through navigation to various application screens by the Web Thin Client. The Web Server communicates with the Web Thin Client via HTTP protocol over TCP/IP. SSL (Secure Socket Layer) encrypted communications can be enabled. The Web Server does not need to reside on the same PC as the IWS runtime application. In fact, the Web Server could be a non-Windows corporate Web Server. However, the Web Server needs to have access to the HTML files that are the application Web pages. IWS supports a Secondary Web Server that will be automatically switched to (by the Client) in case the Primary Web Server becomes unavailable. However, if the runtime application environment is Windows CE 3.0, the Backup URL field specifies the address of the Primary Web Server (due to Windows CE 3.0 limitations).

InduSoft Web Studio

3211

IWS Training Guide

Web Thin Clients The Underlying Technology

Web Browser The Web Browser is located on the Web Thin Client PC and provides the graphical interface function with the user. Web pages (HTML) is passed to the browser via demand (pull) and data is pushed to the browser by the Data Server whenever a Tag or Tags referenced on the Screen displayed on the Web Client is updated in the Tag Database. ISSymbol ISSymbol is an InduSoft-provided ActiveX Control that facilitates the interaction between the browser on the Web Client and the Web Server as well as the Data Server. There are ISSymbol ActiveX Control versions for Windows XP/2000/NT/Server 2003/Vista and all Windows CE platforms. The ISSymbol ActiveX Control is used for both the Internet Explorer-based and Secure Viewer-based browsers. Web Tunneling Gateway The (Primary) Web Tunneling Gateway is a bridge between the Web Server and the Data Server that is used in one of two situations. The first is whenever data security is required (e.g. IWS data exchanged with the Web Thin Client needs to be encrypted). The second situation is when the Data Server is hid behind a corporate firewall, and only the Web Server IP address (or URL) is exposed. IWS supports a backup (Secondary) Web Tunneling Gateway to be used if the Primary Web Tunneling Gateway becomes unavailable. The Web Thin Client will automatically switch over to the secondary Web Tunneling Gateway. The Web Tunneling Gateway is automatically installed when IWS is installed on your PC if the installation program detects that IIS is present.

Notes: The Web Tunneling Gateway is automatically installed if IIS is detected during the installation process. Otherwise, it must be manually installed. The main function of the Web Tunneling gateway is to encapsulate data packets in HTTP or HTTPS for communication through a firewall.

3212

InduSoft Web Studio

ISSymbol ActiveX Control

IWS Training Guide

ISSymbol ActiveX Control


ISSymbol is an ActiveX Control designed by InduSoft used to display the screens created with IWS on the web browser and exchange data (tag values and history data) using the TCP/IP server module of IWS. It is a central component in the operation of a Web Thin Client. On the Web Thin Client station, the web browser (e.g. Internet Explorer) is the container that hosts the ISSymbol ActiveX Control. ISSymbol works as a control layer between the IWS application and the web browser equivalent to the Java Virtual Machine for Java-based applications. This approach provides a high level of security because ISSymbol does not allow the application to access the operating system directly. When the web browser downloads the HTML page specified by the user, it checks for ISSymbol control registration (Certificate of Authenticity) on the current computer. If it does not find it, the browser attempts to download registration from the URL specified in the Project Settings Web Advanced dialog box. The web browser is not able to display the screens from the IWS application if the ISSymbol control is not properly registered in the Web Thin Client station. Note: Make sure your web browser is enabled to download signed ActiveX controls, in order to download ISSymbol automatically. Otherwise, you will need to register ISSymbol manually in the Web Thin Client station. Check your web browsers documentation about security settings if you have questions about how to configure these settings.

Configuring the Web Server for automatic download of ISSymbol


As long as your Windows browser (Web Client) platform is not based on Windows CE, and your browser is configured to allow downloading of ActiveX controls, you can configure the Web Client and Web Server to automatically download the ISSymbol ActiveX Control to a Web Client. Windows CE-based platforms do not currently support downloading and automatic registration of ActiveX Controls, this must be done manually.

InduSoft Web Studio

3213

IWS Training Guide

ISSymbol ActiveX Control

By selecting Project Settings Web tab and clicking on the Advanced tab, you open the Web Configuration Advanced dialog box. In the ISSymbol URL field, there is a default URL pointing to InduSofts website to a path for downloading the ISSymbol ActiveX Control if it is not already installed on your Web Thin Client. But what do you do if your Web Client does not have Internet connectivity? No problem, you simply put a copy of the ISSymbolVM.cab file (found in the C:\Program Files\InduSoft Web Studio v6.1\Bin folder) into your Web Servers root folder (i.e. the folder or path where the Web Server (e.g. IIS) is pointing to for HTML files). Then, you change the path in the ISSymbol URL field (in the Advanced Dialog box) to reflect the URL or IP address of your Web Server. E.g. http://152.30.75.100. Then, when a Web Client (without ISSymbol installed and registered) connects to the Web Server, ISSymbol can be automatically downloaded and will self-register.

Installing the ISSymbol control manually


You can install the ISSymbol ActiveX Control manually in a Web Thin Client PC. The procedure to install ISSymbol in each operating system is described below: Windows XP/2000/NT/Server 2003/ Vista: Copy the files ISSymbolReg.exe and ISSymbolVM.cab from the \BIN sub-folder of Indusoft Web Studio v6.1 (C:\Program Files\Indusoft Web Studio v6.1) folder and paste them in any directory of the Web Thin Client station. Make sure that both files are stored in the same directory. Run ISSymbolReg.exe to register ISSymbol control in the Web Thin Client station. Windows CE: Copy the file ISSymbolCE.ocx and IndHTTP.dll from the \Redist\<OS Version>\<Processor Type>\ sub-folder of Indusoft Web Studio v6.1, and paste them in any directory of the Web Thin Client station. Execute the following command from the Prompt window: regsvrce.exe \<ISSymbolPath>\ISSymbolCE.ocx (e.g. regsvrce.exe \Storage Card\ISSymbolCE.ocx) Save the registry settings to keep ISSymbolCE.ocx registered when you reboot the Windows CE device. Windows CE PocketPC: Copy the files RegSvrCE.exe, ISSymbolCE.ocx and ndHTTP.dll from the \Redist\<OS Version>\<Processor Type>\ sub-folder of Indusoft Web Studio v6.1 and paste them in any directory of the Web Thin Client station. Make sure that both files are stored in the same directory. Execute the RegSvrCE.exe program on the Web Thin Client device. To register ISSymbolCE.ocx, do the following: Select the \<ISSymbolPath>\ISSymbolCE.ocx file Select the option Register Click the OK button

Note: Internet Explorer is not able to download ActiveX controls automatically from Windows CE and Windows CE PocketPC. Therefore, before using Windows CE devices as Web Thin Clients, you must register the ISSymbolCE.ocx control manually.

3214

InduSoft Web Studio

ISSymbol ActiveX Control

IWS Training Guide

How ISSymbol Operates with the Web Thin Client


After you open the browser on the Web Thin Client, you enter the URL for the startup web page in the Web Server (e.g. http://192.168.1.100/startup.html) into the Address field. {Note: the Secure Viewer does not require the entry of the URL for the startup Web page}. At this point, the Web Thin Client executes the following process: 1. The browser downloads the HTML page of the screen you specified from the Web Server. 2. The browser checks for ISSymbol ActiveX Control registration in the local computer. If it does not find it, or if the ISSymbol ActiveX Control is an out of date version, the browser attempts to download the ISSymbol component from the URL configured in the application (settings are embedded in the HTML page). If the ISSymbol control is properly registered in the Web Thin Client station, the browser loads it. From this point on, ISSymbol takes over the communication with the Web Server, and the browser is used only as a host for ISSymbol. 3. ISSymbol now connects to the Data Server. The Data Server IP Address was initially configured in the Project Settings Web dialog window. This setting is now embedded in the HTML page. 4. ISSymbol prompts a window on the Web Thin Client, asking for the User Name and Password. The data you enter is encrypted and sent to the server. The Web Server checks the validity of the data and whether you have the rights to open the startup screen. If so, the process continues. If not, you are prompted with an error message indicating that the User Name and/or Password are invalid. In this case, the process will not continue. Note: Step 4 is skipped if the Security System is disabled during the configuration of the application. If the Security System is disable, use Guest as the User Name (with no Password). 5. ISSymbol downloads the necessary files to display the screen specified by the user (screen files, tags database, translation files, etc.). 6. ISSymbol connects to the Data Server and reads the value of the tags that are displayed in the screen you specified. 7. ISSymbol displays the screen on the browser and keeps updating the objects according to the values read from the Data Server. Whenever the value of any tag displayed on the open screen(s) changes on the Data Server, the new value is sent to the Web Thin Client (and vice-versa). Therefore, there is no pooling between the Web Thin Client and the server station. This method increases the communication performance and optimizes the traffic in the network.

InduSoft Web Studio

3215

IWS Training Guide

Web Server Configuration

Web Server Configuration


There are several different Web Servers that can be used with an IWS application to support Web Thin Clients. The choice of Web Server depends on the platform used. As previously mentioned, the Web Server is not required to be on a Microsoft Windows OS platform, it could be on a Linux corporate web server. However, if you require the Web Tunneling Gateway (designed by InduSoft), the Web Server must be Microsoft IIS (Internet Information Services). Examples of Web Servers include: Web Server NTWebServer CEWebServer IIS 4.0 IIS 5.0 IIS 5.1 IIS 6.0 IIS 7.0 IIS for CE.NET Operating System Windows NT, 2000, XP, Server 2003, Vista Windows CE Windows NT Windows 2000 Windows 2000, XP Pro Windows Server 2003 Windows Vista Windows CE.NET 4.x, 5.0, 6.0 Comments InduSoft provided light weight Web Server. An application, not a Service. InduSoft provided light weight Web Server. An application, not a Service.

Apache 2.0 for Windows

Windows XP, 2000, Server 2003

Max. 10 simultaneous connections No limit on connections No limit on connections Must be included in Platform Builder. Default is 10 maximum simultaneous connections. Can run as an Application or Service

NTWebServer is located in the \Bin sub-folder of the IWS program folder following installation. CEWebServer is located in the \Redist\<WinCE version>\<Processor Type> sub-folder of the IWS program folder following installation. Regardless of which InduSoft Web Server you use, it needs to be copied to the \Web sub-folder of your application folder and executed from this folder. The home directory (Web Root directory) for both of these Web Servers is the directory where they are executed. NTWebServer and CEWebServer were designed primarily for simple tests and/or for demos. InduSoft recommends using third-party commercial Web Servers such as IIS (Internet Information Services) from Microsoft or Apache for real-world applications. A commercial Web Server must be configured prior to use. One of the key settings for the Web Server is to assign a home directory (or Web Root directory), which should be the \Web sub-folder located in the application folder. Consult your Web Servers documentation for further information about its configuration.

3216

InduSoft Web Studio

Web Tunneling Gateway Configuration

IWS Training Guide

Web Tunneling Gateway Configuration


Web Thin Clients are commonly connected to the Web Server via the Internet. However, the Data Server(s) (PC where the IWS is running) is often not directly connected to the Internet. In this case, the Data Server computer does not have an IP address recognized on the internet. Therefore, the Data Server cannot be connected directly through the Internet. The Web Tunneling Gateway (WTG), developed by InduSoft, provides the routing capabilities to solve this problem. The WTG must be installed in the PC with the Fixed IP Address on the Internet. Generally, this is the Web Server. Consult your ISP provider for further information about how to get a Fixed IP Address for your PC on the Internet. The PC where the WTG is running must have the Microsoft IIS Web Server installed and running. The WTG is an ISAPI extension for IIS. The Web Tunneling Gateway also provides the ability to encapsulate the data packets between the Data Server and the Web Client in HTTP or HTTPS. Follow the procedure below to install the WTG on the Web Server computer: Copy the WebGtw.exe file from the \BIN sub-folder of IWS into any directory of the web server computer. Execute the WebGtw.exe file on the web server computer. The WTG works as a router between the Web Thin Clients (connected to the Internet) and the Data Server PC (connected to the Intranet). The same WTG can route information for more than one Data Server simultaneously.

InduSoft Web Studio

3217

IWS Training Guide

Web Browser Configuration

Web Browser Configuration


IWS supports two types of Web Browsers for use with Web Thin Clients; Microsoft Internet Explorer, which supports ActiveX Controls, and the InduSoft-developed Secure Viewer. Both browsers can use used concurrently with the Web Server, and the choice of browser depends on the application requirements. The Secure Viewer browser is targeted at plant floor use, while the Internet Explorer browser is generally more appropriate for desktop applications or where the Web Thin Client needs to browse different Web Servers.

Configuring Microsoft Internet Explorer


There is really very little that needs to be done to configure Microsoft Internet Explorer to be used as a Web Browser for an IWS Web Thin Client. The primary items are: Make sure ActiveX Controls are enabled. The settings to control this are generally found in Tools Internet Options Security. Click on the Custom Level button and be sure to allow the ISSymbol ActiveX Control to be installed, then you can return to a higher security level. (Otherwise, be sure to install the ISSymbol ActiveX Control manually). Be sure VBScript is supported on your PC. This is generally not an issue with Windows XP/NT/2000/Server2003/Vista based PCs, but can be an issue on Windows CE-based devices. You will need to be sure the VBRun.dll is installed and registered on your PC. If you are going to use Microsoft Internet Explorer as your web browser for Web Thin Client applications, you may want to remove some navigation bars and buttons to reduce the amount of space taken up by these items. You can create an icon on the desktop that is a shortcut to your startup web page on the Web Server. This will take you to the web page when you click on the icon. Additionally, you can put this shortcut in the Startup folder so that the Web page is automatically started whenever the browser is started.

Installing the Secure Viewer Browser on Windows XP/2000/Vista PC


You will need to install the Secure Viewer browser from your CD (or download from the InduSoft website). Follow the following steps: Request the Secure Viewer installer from your software vendor, save it to the designated computer, and start it. Follow the instructions of the installation wizard. There are only two settings that must be configured during installation:

URL: Enter the URL or filepath of the application file (*.app) on the Web Server.

3218

InduSoft Web Studio

Web Browser Configuration

IWS Training Guide

Server IP: Enter the IP address or hostname of the TCP/IP Server.

Finish the installation and click Finish to close the installer. The installation wizard automatically installs and registers the Web Thin Client ActiveX component (ISSymbol.ocx), so if you have correctly configured the URL and Server IP settings, then the Secure Viewer should be ready to go. Note: For additional security of the runtime environment, add a shortcut to the Secure Viewer (Viewer.exe) to the Startup directory in Windows. Viewer.exe will install into the \Bin sub-folder where the IWS program installs.

Installing the Secure Viewer Browser on Windows CE


You can also install the Secure Viewer on a Windows CE device, by copying the necessary files to the devices non-volatile memory. To install Secure Viewer: Create and configure a viewer.ini file with the appropriate settings for the Windows CE device. (For more information about creating this file, see the previous section.) Determine the OS version and processor type of the Windows CE device, and then find the corresponding sub-folder in the InduSoft Web Studio program directory. For example, for Windows CE v4.0 running on a MIPS processor, find the \Indusoft Web Studio v6.1\Redist\WinCEv4.0\MIPS\ subfolder. Select the Secure Viewer program (Viewer.exe) and ISSymbol control (ISSymbolCE.ocx) from this sub-folder, as well as the viewer.ini file youve already created, and copy all three to non-volatile memory on the Windows CE device. Register the ISSymbol control on the Windows CE device by executing the following command from the Prompt window: regsvrce.exe "\<ISSymbolPath>\ISSymbolCE.ocx" Example regsvrce.exe "\Storage Card\ISSymbolCE.ocx" Save the registry settings to keep ISSymbolCE.ocx registered when you reboot the Windows CE device. Start the Secure Viewer by running Viewer.exe. Tip: Check the device manufacturers documentation for how to save the registry settings.

InduSoft Web Studio

3219

IWS Training Guide

Web Browser Configuration

Changing the Secure Viewer Configuration


After initial installation, the configuration of the Secure Viewer is saved in the viewer.ini file, which should be in the same directory as Viewer.exe. (This should be in the \Bin sub-folder where the Secure Viewer program is installed). There are two ways to change the configuration of the Secure Viewer after it has been installed. First, you can run the Viewer configuration utility (ViewerCfg.exe) that was also installed.

The configuration utility provides the following options: Load button: Click to load a viewer.ini file into the utility for editing. Save button: Click to save your changes to the viewer.ini file. Data Server IP field: Enter the IP address (or host name) of your data server station. The data server station is the computer or device where the TCP/IP Server module is running. TCP Port field: Enter the port number of the Data Server, if it is different than the default port of 1234. URL field: Enter the URL or filepath of the application file (*.app) on the Web Server. Enable Splash Window option: Check (enable) this option to see a splash window when you start the Secure Viewer. Enable Progress Bar option: Check (enable) this option to see a progress bar while the Secure Viewer loads the application file. Advanced button: Click to access additional configuration options:

Secure Viewer Configuration Utility Advanced Settings Secondary Data Server IP field: Type the IP address (or host name) of the secondary data server station. If the primary data server fails, the Secure Viewer will attempt to connect to the secondary data server automatically.

3220

InduSoft Web Studio

Web Browser Configuration

IWS Training Guide

Web Tunneling Gateway: If you have configured a Web Tunneling Gateway to bridge your intranet to the Internet (see Architecture 4: Web server and Web Thin Clients in different networks on page 138), then enter the addresses for the gateway here. Log on as Guest option: Check (enable) to have the Secure Viewer automatically log on as Guest, eliminating the need to enter a Username or Password.

The second way to change the configuration of the Secure Viewer is to manually edit the viewer.ini file with a text editor. The structure of the file is as follows: [Options] nosplash = // Enable (0) or disable (1) the splash window noprogressbar = // Enable (0) or disable (1) the progress bar ds1 = // Data Server Primary ds2 = // Data Server Secondary dsp = // Data Server Port wtg1 = // Web Tunneling Gateway Primary wtg2 = // Web Tunneling Gateway Secondary url = // URL from application file (*.app) proxyip = // Proxy Address proxyp = // Proxy Port ceemul = // Enable (1) or disable (0) CEView emulation Example: PC with IWS Runtime Application (has both Web Server (NTWebServer or IIS) and Data Server) IP Address is 192.168.1.106 Project is called SecureViewerTest Application is SecureViewerTest.app Secure Viewer configuration dialog box Data Server IP = 192.168.1.106 TCP Port = 1234 URL = http://192.168.1.106//SecureViewerTest.app Alternatively, you could edit the viewer.ini file [Options] url= http://192.168.1.106//SecureViewerTest.app noprogressbar=1 ds1=192.168.1.106 nosplash=1 ds2= dsp=1234 wtg1= wtg2= user=Guest [OEM] Splash=Splash.bmp //this is a splash screen

Notes: Your IWS runtime license must support a Secure Viewer (Thin Client) otherwise the connection to the Data Server will be refused. Be sure to put NTWeb Server in the application root folder (not \Web subfolder) or point IIS to the application root folder. The Secure Viewer Configurator is not available for Windows CE. Modify the Viewer.ini file settings instead.

InduSoft Web Studio

3221

IWS Training Guide

Data Server and Web Client Configuration

Data Server and Web Client Configuration


IWS has a couple dialog boxes that are used for configuration of the Data Server and the Web Server configuration to be used. This information is embedded in the HTML web pages that correspond the screens. The Data Server is part of the IWS runtime application and uses the TCP/IP Server module. There are three (3) basic steps to this configuration: 1: Web Settings dialog box configuration In the Main Menu toolbar, click on Project Settings and select the Web tab. Enter the IP address of the PC where the IWS application runtime will reside in the Data Server IP Address field. Check the checkboxes for Auto Screen Scaling, Enable File Compression and Enable Tooltips. If you want to disable the Web Client from issuing commands to the Server, check the Disable Remote Client Commands checkbox. If the Web Client is to use a Virtual Keyboard, check the Virtual Keyboard checkbox and any additional settings for the Virtual Keyboard at the Thin Client. By clicking on the Advanced button, you can define a backup URL (i.e. backup Website for web pages) and a Secondary Data Server IP address. This is for a redundant Web Server and/or a redundant Data Server, respectively. Web Tunneling can also be enabled in this dialog box. The URL for the ISSymbol OCX can also be defined if it is not found on the Web Server By click on the IP Security button, you can define a range of IP addresses that will be accepted by the Data Server. If a request for data comes from an IP address outside of the defined ranges, the request will not be acknowledged. This is an Embedded Firewall function.

3222

InduSoft Web Studio

Data Server and Web Client Configuration

IWS Training Guide

2: Communication Settings dialog box configuration In the Main Menu toolbar, click on Project Settings and select the Communication tab. Enter the Port number (1234 is the default) for the Data Server. You can also define the Data Send Period (i.e. time period for updated communication of data values to the Web Client). Optionally enable Binary Control of the data. It is more secure, but is slower. The default is disabled.

3: Enable the TCP/IP task In the Main Menu toolbar, click on Project Status and select the Execution Tasks tab. Be sure the TCP/IP Server is set to Automatic. This should be the default state, but can be manually configured by selecting the Startup button. Be sure the TCP Port number is properly set (see Communication Settings above), otherwise the TCP/IP Server will start then stop.

InduSoft Web Studio

3223

IWS Training Guide

Data Server and Web Client Configuration

Notes: This configuration information (from Step 1 & 2) gets embedded in the Web Pages generated from the IWS development environment when you Save As HTML. If you change any of these settings, you MUST run the Verify Application tool

Using the SetWebConfig Function


The IWS SetWebConfig() built-in function allows the developer to programmatically configure the Data Server and Web Client configuration, and the resulting configuration settings are automatically updated in the applications HTML files (located in the \Web subfolder). This function always runs on the IWS Server, and works in both a Windows XP and Windows CE environment. The function is called as follows: SetWebConfig( strServerIP, strOptBackupURL, strOptPath, numOptHostPort, strOptSecondaryServerIP, numOptProtocolFlag, numOptGtwPort, strOptGtwIP, strOptSecondaryGtwIP, strOptISSymbolURL), where: strServerIP Data Server IP Address. IP address (or hostname) of the computer where the TCP Server module of IWS is running. strOptBackupURL Optional alternative URL for the application web pages. The Web Thin Client will look for the web pages in this URL if it does not find them in the same URL written in the Address field of the web browser. strOptPath Optional path where the web pages that must be updated are stored. Note: You can specify an individual file (e.g. you only want to update one file. This is especially useful for Windows CE applications. numOptHostPort Optional TCP Port number that the Web Thin Client must use to exchange data with the TCP Server module of IWS. strOptSecondaryServerIP Optional alternative data server IP address. The Web Thin Client will attempt to connect to the TCP Server module of IWS in this IP Address if it is not able to connect to the TCP Server module running in the IP Address specified in the strServerIP parameter. numOptProtocolFlag Optional When you use the Web Tunneling Gateway option, this parameter specifies whether the Web Thin Client will use either HTTP to exchange data with the Web Server or HTTPS (SSL Secure Socket Layer). If this flag has the value 0, the Web Thin Client will use HTTP. If this flag has the value 1, the Web Thin Client will use HTTPS (SSL). numOptGtwPort Optional TCP Port number that the Web Thin Client must use to exchange data with the Web Server when using the Web Tunneling Gateway. strOptGtwIP Optional IP Address (or hostname) of the computer where the Web Tunneling Gateway is running. strOptSecondaryGtwIP Optional Alternative IP Address (or hostname) of the computer where the Web Tunneling Gateway is running. The Web Thin Client will attempt to connect to the Web Tunneling Gateway in this IP Address if it is not able to connect to the Web Tunneling Gateway running in the IP Address specified in the strOptGtwIP parameter. strOptISSymbolURL Optional URL from where the updated version of ISSymbol (ActiveX control) must be downloaded if it is not properly registered in the Web Thin Client station.

3224

InduSoft Web Studio

Data Server and Web Client Configuration

IWS Training Guide

Configuring the Web Server to support IE and Secure Viewer Browsers


IWS is capable of supporting both Interned Explorer (IE)-based browsers and Secure Viewer-based browser at the same time. To do this however, you need to take some care in how you configure your system. From the Web-Server side All HTML files go into the Project Application \Web subfolder Put a copy of any translation file(s) in the \Web subfolder and the Project Application folder. In the Project Settings Options dialog box, have the Automatic Translation Translation File Name point to the translation file in the \Web subfolder Configure your Web Server (e.g. IIS) to have its root folder point to the Project Application folder Put ISSymbolVM.cab in the Project Application folder if an internet connection to InduSofts Web Site is not available and the ISSymbol ActiveX control is not installed on the IE-based Web Client.

From the Web-Client side The Secure Viewer-based browser should be configured to point to the .APP file in the Project Application folder The IE-based browser should have as an initial URL something like as follows: http://192.168.1.100/Web/startup.html, where startup.html is your startup web page.

InduSoft Web Studio

3225

IWS Training Guide

Example Web Server/Thin Client Architectures

Example Web Server/Thin Client Architectures


This section describes some example architectures applied for web-based solutions and provides information on how to configure the IWS application for each architecture. This section does not describe all possible architectures, but it provides the concepts necessary to design and configure different scenarios based on the basic architectures illustrated below The Web Settings are configured by the Web tab of the Project Settings dialog. To open this dialog, in the development environment select from the Main Menu Bar Project Settings Web (tab). By pressing the Advanced button, you access additional settings. The following pictures illustrate these dialog boxes:

The following table describes the meaning of the main Web settings illustrated in the above dialog boxes: Setting
Data Server IP Address Secondary Data Server IP Address Web Tunneling Gateway IP Address Web Tunneling Gateway Secondary IP Address

Description
When the Web Tunneling Gateway is disabled: The Web Thin Client Control (ISSymbol) uses the Data Server IP Address to connect to the Studio TCP/IP Server Task. When the Web Tunneling Gateway is enabled: The Web Tunneling Gateway uses the Data Server IP Address to connect to the Studio TCP/IP Server Task. Same as the Data Server IP Address. However, the Secondary IP Address is used only when the connection with the Data Server IP Address fails. The Web Thin Client Control (ISSymbol) uses the Web Tunneling Gateway IP Address to connect to the Web Tunneling Gateway. Same as the Web Tunneling Gateway IP Address. However, the Web Tunneling Gateway Secondary IP Address is used only when the connection with the Web Tunneling Gateway IP Address fails.

The Secondary addresses can be used in the following scenarios: - When the Web Thin Clients can connect to either one of two redundant Servers (Web or Data); or - When the Web Thin Clients can connect to the Server through the Intranet (LAN Local Area Network) or through the Internet (WAN Wide Area Network). In this case, the Primary addresses should be configured based on the network used more often by the Web Thin Clients. In the following examples, the LAN addresses are used as Primary and the WAN addresses are used as Secondary.

3226

InduSoft Web Studio

Example Web Server/Thin Client Architectures

IWS Training Guide

The following table describes the meaning from some terms used in the next examples: Term
LAN WAN

Description
Local Area Network (for example, Intranet) Wide Area Network (for example, Internet) Station where the following components are running: - Studio (TCP/IP Server task) - Web Server (for example, Internet Information Services from Microsoft IIS) - Web Tunneling Gateway for IIS (if enabled) Although Studio does not need to run in the same station where the other components are running, the following examples assume that it is. Web Thin Client station (Web Browser + ISSymbol control) that connects the Server via the LAN. Web Thin Client station (Web Browser + ISSymbol control) that connects the Server via the WAN. IP Address of the Server on the LAN. IP Address of the Server on the WAN. IP Address of the Router on the LAN. IP Address of the Router on the WAN. Name of the application screen, saved as HTML, that is open on the Web Thin Client station.

Server

Web Thin Client LAN Web Thin Client WAN IP_SERVER_LAN IP_SERVER_WAN IP_ROUTER_LAN IP_ ROUTER_WAN ScreenName

InduSoft Web Studio

3227

IWS Training Guide

Example Web Server/Thin Client Architectures

Example 1: Web Server and Web Thin Client in the same Intranet (LAN)
IP_SERVER_LAN LAN

Web Thin Client LAN

Server

This is the very common architecture, as well as the simplest to configure. In this architecture, both the Web Server (e.g. IIS) and the Data Server (IWS TCP/IP Server module) are running in the same PC. The Web Thin Client connects to the Web Server to download the HTML screen file(s). Then it connects to the Data Server to exchange data with the IWS runtime application. Since both the Web Thin Client and the Server station are connected to the same network, the Web Thin Client can access the Server station directly through its IP address (or host name). Configuration: Setting Data Server IP Address Secondary Data Server IP Address Web Tunneling Gateway IP Address Web Tunneling Gateway Secondary IP Address WTG Enabled IP_SERVER_LAN IP_SERVER_LAN Web Gateway Disabled IP_SERVER_LAN -

Remarks: URL From Web Thin Client LAN: http://IP_SERVER_LAN/ScreenName.html Home directory of the web server (HTTP server) on the server station: \Web sub-folder of the application -

3228

InduSoft Web Studio

Example Web Server/Thin Client Architectures

IWS Training Guide

Example 2: Web Server with Intranet (LAN) and Internet (WAN) Connections

WAN

IP_SERVER_LAN IP_SERVER_WAN

Web Thin Client WAN

LAN Web Thin Client LAN Server

This architecture has both the Web Server (e.g. IIS) and the Data Server (IWS TCP/IP Server module) running in the same PC. Web Thin Clients can connect to the Server through either an Intranet (LAN) connection to the Server or an Internet (WAN) connection to the Server (e.g. two different Ethernet ports).

Configuration: Setting Data Server IP Address Secondary Data Server IP Address Web Tunneling Gateway IP Address Web Tunneling Gateway Secondary IP Address Web Gateway Enabled IP_SERVER_LAN IP_SERVER_LAN IP_SERVER_LAN IP_SERVER_WAN Web Gateway Disabled IP_SERVER_LAN IP_SERVER_WAN -

Remarks: URL From Web Thin Client LAN: http://IP_SERVER_LAN/ScreenName.html URL From Web Thin Client WAN: http://IP_SERVER_WAN/ScreenName.html Home directory of the Web Server (HTTP server) on the Server station: \Web sub-folder of the application You must assign a Fixed IP address to the Web Server on the Internet (WAN), and the application must be running in this Server. Consult your ISP provider or IT department for further information about how to get a Fixed IP address for your Server.

InduSoft Web Studio

3229

IWS Training Guide

Example Web Server/Thin Client Architectures

Example 3: Web Server with Intranet (LAN) and Router Internet (WAN) Connections
WAN

Web Thin Client LAN

Server IP_ROUTER_WAN Router LAN IP_SERVER_LAN IP_ROUTER_LAN

Web Thin Client WAN

This architecture has both the Web Server (e.g. IIS) and the Data Server (IWS TCP/IP Server module) running in the same PC. Web Thin Clients can connect to the Server through either an Intranet (LAN) connection or an Internet (WAN) connection. There is a Router between the Intranet (LAN) and the Internet (WAN).

Configuration: Setting Data Server IP Address Secondary Data Server IP Address Web Tunneling Gateway IP Address Web Tunneling Gateway Secondary IP Address Web Gateway Enabled IP_SERVER_LAN IP_SERVER_LAN IP_SERVER_LAN IP_ROUTER_WAN Web Gateway Disabled IP_SERVER_LAN IP_ROUTER_WAN -

Remarks: URL From Web Thin Client LAN: http://IP_SERVER_LAN/ScreenName.html URL From Web Thin Client WAN: http://IP_ROUTERR_WAN/ScreenName.html The Router must be configured to forward the TCP Port(s) from its public IP (IP_ROUTER_WAN) to the Server private IP (IP_SERVER_LAN). If the Web Gateway is enabled, only the HTTP Port (80, by default) or the HTTPS Port (SSL Port 443, by default) must be forwarded from IP_ROUTER_WAN to the IP_SERVER_LAN. If the Web Gateway is disabled, both the HTTP Port (80, by default) and the InduSoft TCP/IP Server Port (1234, by default) must be forwarded from IP_ROUTER_WAN to the IP_SERVER_LAN. Consult the Router documentation for further information about how to configure Port Forwarding on it. Home directory of the Web Server (HTTP server) on the Server station: \Web sub-folder of the application You must assign a Fixed IP address to the Router on the Internet (WAN), and the application must be running in this Server. Consult your ISP provider or IT department for further information about how to get a Fixed IP address for your Server.

3230

InduSoft Web Studio

Security for Web Based Applications

IWS Training Guide

Security for Web Based Applications


There are various methods for implementing security of Web based Applications. The approach that you require can depend on a number of factors, and may involve one or more methods of implementing Security.

1. Password Protection
IWS provides the ability to create Groups of Users and individual Users within a Group. Each Group (e.g. Operators, Supervisors, Maintenance) can have different security levels and access different levels of functionality. Individual passwords can be configured for each User.

In addition, Groups can have advanced settings, allowing features like minimum password size, password aging, e-signature on Objects with Command Dynamics, Account Auto-lockup (e.g. lock up after a number of invalid attempts to access), and User Account blocking (temporarily disable e.g. when employee is on vacation).

InduSoft Web Studio

3231

IWS Training Guide

Security for Web Based Applications

If System Security is enabled, these Password Protection features are also available at the Web Thin Client station. When a User at a Web Thin Client station attempts to connect to the Web Server, they will be prompted for a User Name and a Password. If either is invalid, the User will not be let on to the system.

Within an application, the various Objects and their Dynamics, and Screen access can have a security level assigned to it. The current User logged on must have a access level range which matches the desired Object or Screen. The following is a representative method of assigning security access levels by Group.

3232

InduSoft Web Studio

Security for Web Based Applications

IWS Training Guide

2. Disabling Web Thin Client Commands


IWS allows bi-directional data exchange between the Web Thin Client and the Data Server. However, for security reasons it may be advantageous to only allow the Web Thin Client to view the process or machine data, and not send any data back to the Data Server. By checking the Disable Remote Client Commands check-box from the Project Settings Web dialog window of the IWS development environment, this will insures that all commands coming from a Web Thin Client station are blocked. The communication becomes unidirectional (from the Server to the Web Thin Clients):

InduSoft Web Studio

3233

IWS Training Guide

Security for Web Based Applications

3. Embedded Firewall
This feature allows the user to filter access to the application based on the Web Thin Clients IP Address. When a Web Thin Client attempts to connect to the Server station, the Server checks if the IP Address of the Web Thin Client station is authorized to access the application. The ranges of authorized IP Addresses can be configured in the Server station by pressing the IP Security button from the Project Settings Web dialog window of the Studio development environment:

4. Encrypted Communications (SSL)


By enabling the Web Tunneling Gateway (WTG), you can enable all communications between the Data Server + Web Server and the Web Thin Client to be encrypted using RC6, a highly-secure 128-bit encryption standard. To use SSL, you must do the following: From the IWS development environment, select Project Settings Web (tab). Click on the Advanced button. Check the Web Tunneling Gateway Enabled check-box. Click on the SSL radio button and be sure the SSL port is set to 442. Click OK. In your Web Server, be sure SSL capabilities are enabled and that a SSL Certificate of Authentication is present. Be sure SSL is enabled in the Web Client Set up all other Web configurations to support the WTG.

3234

InduSoft Web Studio

Security for Web Based Applications

IWS Training Guide

5. VPN
A VPN is a Virtual Private Network. It is called virtual since it really uses the public Internet to transport data from one computer to another. But since this network is encrypted and uses other security mechanisms enabled by the ISP, is it a very secure Private Network. While VPNs are inherently secure, they are more costly that a simple public Internet connection.

InduSoft Web Studio

3235

IWS Training Guide

Port Usage

Port Usage
There are various ports that are used by IWS and/or related software. These are: Port # 20 21 25 80 110 118 161 162 389 443 502 663 1028 1029 1234 1443 1444 1521 1526 2030 3001 3306 3872 3997 4322 5432 47808 Application FTP Server (Data) FTP Server (Command) SMTP Server Microsoft IIS Server for HTTP packets POP3 Microsoft SQL Server Services SNMP SNMP Trap LDAP Microsoft IIS Server for HTTPS packets (SSL) Modbus TCP/IP protocol LDAP over SSL FTP Client (Command) FTP Client (Data) IWS TCP/IP Server Microsoft SQL Server Microsoft SQL Server default port (Monitor) Oracle Oracle Oracle A-B Ethernet TCP/IP Protocol (default) MySQL (can be configured to use 3306-3309) Oracle Management Remote Agent IWS ADO Gateway IWS Remote Agent (CEServer) PostgreSQL BACNet UDP Protocol (default)

You may need to accommodate one or more of these ports usage in your Firewall settings.

3236

InduSoft Web Studio

Exercise: Viewing Your Application on the Web

IWS Training Guide

Exercise: Viewing Your Application on the Web


To view your application, use the following steps: Expand the Screens folder and double-click on your Main.scr screen.

Selecting a Screen Select File Save as HTML to save the screen in HTML format. Web files are stored in the Web folder, so open the folder and verify that you saved the Main screen successfully. You should see main.html.

main.html

InduSoft Web Studio

3237

IWS Training Guide

Exercise: Viewing Your Application on the Web

Select Project Settings from main menu bar, and then select the Web tab.

Open the Project Settings Dialog Configure the Data Server IP Address to use the IP Address of the Server station (computer on which you are running) at runtime. The Web Thin Client station exchanges on-line data (tag values) with the station specified in this field. Type the URL path to your main.html file (in the Web folder) into the URL field. The URL depends on the Home directory configured in the Web Server of your Server station. Note: Microsoft provides Web Servers for any Microsoft operating system. Consult your Microsoft documentation about installing and configuring a Web Server. After configuring the Web settings, click OK to close the Project Settings dialog. Close all screens in the screen editor (Window Close All) and execute the Tools V erify Application command to update the Web settings to your Web page. Caution: You must execute the Tools Verify Application again after changing any settings in the Project Settings menu.

3238

InduSoft Web Studio

Exercise: Viewing Your Application on the Web

IWS Training Guide

To test your Web-based application, use the following steps: Click the Run Application button ( ) to execute the application locally on the Server station.

Open an Internet Browser (Microsoft Internet Explorer or Netscape) and type the URL address to open your main.html screen from the Server station. When the Log On dialog displays in the Browser, type guest into the User Name field, then click OK to open the main.html screen in the Browser.

Log On Dialog Notice that you can modify the level of any tank locally (Server station) using the Viewer run-time module or remotely (Web Thin Client) using the Browser. Note: A Web Thin Client requires an ActiveX component (ISSymbol.ocx) to handle screens on the Browser. If you connect the Web Thin Client to the Internet, this component is downloaded and registered automatically. .

InduSoft Web Studio

3239

IWS Training Guide

Exercise: Viewing Your Application on the Web

Notes

3240

InduSoft Web Studio

Chapter 33.

Web Thick Clients

The IWS TCP/IP Client/Server modules enable two or more InduSoft applications to keep their databases synchronized. These modules use TCP/IP protocol to make the communication between the applications. Before using the IWS TCP/IP Client/Server modules, you must install and configure the TCP/IP protocol on the machines that will run these modules.

Configuring the Server


On the server machine, you do not have to configure anything. You just have to run the IWS TCP/IP Server module. In the development environment window, go to the Project Settings dialog and set the TCP/IP Server to run automatically. When running this program, a small icon will display in your system tray. To close the IWS TCP/IP Server module, right-click on the icon in the system tray, and select Exit.

Configuring the Client


On the client machine, you must use the TCP/IP Client Configuration worksheet to configure the Server IP address and the tags you want to share with the server. In the Workspace, select the COMM tab and right-click the TCP folder to insert a new TCP worksheet. Configure the following fields: Description: Type a description of the worksheet for documentation purposes only. The TCP/IP Client module ignores this field. Connection Status: Type a tag name. The TCP/IP Client Configuration module updates this tag according to connection status. If the tag value is 0 (zero), then the connection is OK. Otherwise, the Windows Socket library returns an error code. Server IP Address: Type the server IP Address. The entry can be a string or you can use a tag enclosed by brackets. For example, if you fill this field with {tag_name}, the TCP/IP Client module will try to connect to the server indicated by the tag_name tag. Tag Name: Type the tags you want to share with the server. If the tag is an array or a class (or both), every element and member is shared. You should type the tag name only in this fieldwithout specifying the index or class member. If you specify an index or a class, the TCP/IP Client module ignores it. Remote Tag: Type the name of the tag to be linked with the tag specified in the Tag Name field. This field is optional. If you leave it in blank, the same tag name will be used for both the client and the server. Notes: If you need to share an array, then the tag in the server should contain the same number of elements as the tag in the client. If the tag is a class, then the class definition should be the same in both server and client applications. If you do not follow these rules, unpredictable results will occur.

InduSoft Web Studio

331

IWS Training Guide

Exercise: Viewing Your Application on the Web

RUNNING THE TCP/IP CLIENT MODULE


You can choose to run the module automatically. Select Project Status, Runtime Tasks Table, and enter TCP/IP Client. After running this program, a small icon will display in your system tray.

Setting Custom Parameters


You can configure the following parameters for the Application Configuration (.app) file: [TCP] Port: TCP/IP port number. Default is 1234. This parameter should be the same in both the client and server machines. SendPeriod: Time in milliseconds before the client/server module will update the tag values of the other machine. Default is 250. ConnectRetryTimeout: Time in seconds before the client should retry to connect to the server. Default is 30. Only the client module uses the ConnectionRetryTimeout.

332

InduSoft Web Studio

Exercise: Viewing Your Application on the Web

IWS Training Guide

Notes

InduSoft Web Studio

333

Chapter 34.

System Level Redundancy

In this section, we will cover system level redundancy. Database redundancy and Web Server/Data Server redundancy have been covered previously. System level redundancy is simply an extension of a Thick Client application, combined with some Script (e.g. VBScript in a Background Script) along with the Scheduler. To implement System-level redundancy (of IWS Servers), you will need two or more IWS Servers with identical applications. To illustrate how this works, consider the following:

Server 1 TCP/IP Client TCP/IP Server Communications

Server 2 TCP/IP Server TCP/IP Client Communications

PLC We have two IWS Servers (Server 1 and Server 2), each with the same application. These are common elements between the two Servers applications: Server 1 knows the IP address for Server 2 Server 2 knows the IP address for Server 1 Server 1 and Server 2 have a Scheduler function to create a heartbeat that will be enabled if the Server is the Primary Server 1 has a TCP/IP Client Worksheet to check the heartbeat of Server 2. This will be triggered periodically if Server 1 is the Hot Standby. Server 2 has a TCP/IP Client Worksheet to check the heartbeat of Server 1. This will be triggered periodically if Server 2 is the Hot Standby. Server 1 has a TCP/IP Client Worksheet to read the application tags of Server 2. This will be enabled if Server 1 is the Hot Standby Server 2 has a TCP/IP Client Worksheet to read the application tags of Server 1. This will be enabled if Server 2 is the Hot Standby Both Server 1 and Server 2 have Communication Worksheet(s) to read from the PLCs, but only the Primary will have the Communication Worksheets enabled.

To implement System-level redundancy, the following logic sequence must take place The first Server to power-up checks to see if another Server is running, If not, it will asserts itself as the Primary. If there is a Master already running (with a heartbeat), the Server asserts itself as the Hot Standby The Hot Standby periodically checks the heartbeat of the Primary. If it goes away, the Hot Standby asserts itself as the Master.

InduSoft Web Studio

341

IWS Training Guide

Exercise: Viewing Your Application on the Web

Using this scenario, each Server is running the same application but one Server (the Primary) is getting the data from real world devices while the other Server (the Hot Standby) is getting data from the Tags Database of the Primary. The redundancy switch-over time is a function of the heartbeat rate and the frequency of the Hot Standby Server checking the heartbeat of the Master. Each Thick Client will appear as though it is operationally controlling (monitoring) the machine or process, while in reality only one Server is communicating with the real-world devices.

342

InduSoft Web Studio

Exercise: Viewing Your Application on the Web

IWS Training Guide

Notes

InduSoft Web Studio

343

Chapter 35.

FTP

IWS supports FTP (File Transfer Protocol) via IWS built-in functions, allowing uploading or downloading of files to/from a remote FTP Server. FTP Server IWS Client

The FTP Server


A FTP Server is located in a remote PC with a TCP/IP connection to the IWS Server. The FTP Server provides the file transfer service through Microsoft IIS (Internet Information Services - FTP), or any one of several commercially available or freeware FTP Servers (e.g. FileZilla Server, zFTPServer) FTP is a TCP-based Service (exclusively), there is no UDP data component. On the PC that has the FTP Server, there are generally two ports dedicated to the FTP Server; a Command port (also known as a Control port) usually port 21, and a Data Port usually port 20 (for the Active Mode, may be another port number for the Passive Mode). With an Active Mode FTP, the Client (the IWS Application) uses an unprivileged port number N (N>1023) to connect to the FTP Servers Command port (port 21). The Client then begins to listen on port N+1. The Client sends the Client N+1 port number to the FTP Servers Command port, and the FTP Server will connect back to the Clients specified Data port (N+1) from the FTP Servers local port (Port 20). Server Client

Port 20 Data

Port 21 Command

Port 1028 Command

Port 1029 Data

Active Mode FTP Connection Sequence

InduSoft Web Studio

351

IWS Training Guide

Exercise: Viewing Your Application on the Web

The above diagram illustrates the connection sequence between the Client and the FTP Server: Step 1 In Step 1, the Clients Command port (1028) connects to the FTP Server s Command Port (21) and sends the command Port 1029 (to specify the Clients Data port to the FTP Server). The Client begins listening on Data port 1029. Step 2 The FTP Server sends an Ack to the Clients Command port Step 3 The FTP Server initiates a connection from its local Data port (Port 20) to the Clients specified Data port (Port 1029). Step 4 The Client sends an Ack to the Servers Data port.

Any Server-side Firewall needs to have the following ports opened: Port 21 from anywhere (allowing a Client initiated connection) Port 21 to Port N (the Client Command Port) Port 20 to Port N+1 (the Client Data Port) Port 20 from Port N+1 An Active Mode FTP can create problems when there is a Firewall on the Client-side. Since it is the Servers Data port (Port 21) connecting to the Clients Data port (e.g. Port 1029), instead of the Clients Data port making the connection to the FTP Servers Data port, it appears to a Client-side Firewall that an outside system is initiating a connection to an internal client, and this will usually be blocked. This can be accommodated for by opening up the Data port on the Client side (via the Firewall). There is a Passive Mode FTP connection that can be used to resolve the problem of the FTP Server initiating the connection to the Clients Data port. With a Passive Mode FTP, the Client initiates both connections to the Server. When the connection to the FTP Server is initiated, the Client will open up two ports, N (where N > 1023) and N+1. The Client (on Port N) will connect to the FTP Servers Command port (Port 20) and issue a Port command (specifying the Clients Data Port). Next, the Client (from port N+1) will issue a Pasv to the FTP Server, which will open up a random unprivileged port (P > 1023) and send a Port P command back to the Client. The Client then initiates a connection from its Data port N+1 to the FTP Servers port P to transfer files (data). Server Client

Port 20 Data

Port 2020 Data

Port 21 Command

Port 1028 Command

Port 1029 Data

4 Passive Mode FTP Connection Sequence

352

InduSoft Web Studio

Exercise: Viewing Your Application on the Web

IWS Training Guide

The above diagram illustrates the connection sequence between the Client and the FTP Server: Step 1 In Step 1, the Clients Command port (1028) connects to the FTP Server s Command Port (21) and sends the command Pasv command. The Client begins listening on Data port 1029. Step 2 The FTP Server sends a Port 2020 command (or another port number P) to the Client, telling the Client which port to listen for the Data connection Step 3 The Client initiates a connection from its local Data port (Port 1029) to the FTP Servers specified Data port (Port 2020). Step 4 The FTP Server (Port 2020) sends an Ack to the Clients Data port.

Any Server-side Firewall needs to have the following ports opened: Port 21 from anywhere (allowing a Client initiated connection) Port 21 to Port N (the Client Command Port) Port P (the Server Data Port) to remote Port N+1 (the Client Data Port) Port P (the Server Data Port) from Port N+1 While this Passive FTP Server solves the problems of the Client-side connection, it can open up other problem. That is the need to allow remote connections to high numbered ports on the FTP Server. This can be resolved by specifying the Port range the FTP Server is allowed to use. Notes: Most Web Browsers only support Passive Mode FTP Active Mode FTP does not function when used in conjunction with Client-side devices that implement NAT (Network Address Translation). Active Mode FTP is beneficial to the administration of the FTP Server, but can impose problems at the Client Passive Mode FTP is beneficial to the administration of the Client, but can impose problems at the FTP Server. Port and Pasv commands actually send the IP address and the Port number . For an IWS application, the Active Mode FTP should work sufficiently See Microsoft Knowledge Base KB189262 for Passive Mode FTP with IIS

InduSoft Web Studio

353

IWS Training Guide

Exercise: Viewing Your Application on the Web

Configuring IWS to work with the FTP Server


IWS provides a built-in function to configure the FTP connection on the PC that is running IWS. This function is CNFFtp and is supported on Windows XP (NT, 2000, Server 2003, Vista), Windows CE and Web Thin Clients. You must configure the FTP Server connection prior to executing ftpPut or ftpGet. CNFFtp Function Usage CNFFtp(strServer, strUser, strPwd, numPassiveMode, numPort) Parameters strServer The FTP Server Name strUser The User Name. Default is Anonymous. strPwd The User Password. Default is blank numPassiveMode 0 = Active Mode (default) 1 = Passive Mode numPort The FTP Servers Command (Control) Port number the FTP Client is to use. Default is 21 Return Values 0 = Successful connection -1 = Invalid number of parameters -2 = Invalid Server Name -3 = Invalid User Name Example CNFFtp(ftp.myFTPServer.com, admin, 12345) //Configures the FTP Connection for Active Mode Note: The CNNFtp function does not establish a connection with the FTP Server. Instead, it defines the FTP Server/Client connection.

Uploading and Downloading Files to/From an FTP Server


Once the CNFFtp function has been executed (to specify the FTP Server/Client connection parameters), you are ready to upload or download files from the FTP Server. This is accomplished through the IWS built-in functions ftpGet (retrieves a file from the FTP Server) and ftpPut (sends a file to the FTP Server). Both the ftpGet and ftpPut functions execute asynchronously, so you may need to execute the IWS built-in function ftpStatus to determine the state of the transfer. The ftpGet function retrieves a file from the FTP Server and will store it in a local file. ftpGet Function Usage ftpGet(strRemoteFile, strLocalFile, numOverWrite, numTransferType) Parameters strRemoteFile This is a String Tag or Expression representing the fully qualified name of the remote file (as it is referenced on the FTP Server). The FTP Server will have a FTP Site Directory that will contain the files available for FTP, and may have a default file listing style (Windows/DOS or Unix). Some FTP Servers are case-sensitive. strLocalFile This is a String Tag or Expression representing the fully qualified name of the remote file (as it is referenced on the FTP Server). The FTP Server will have a FTP Site Directory that will contain the files available for FTP, and may have a default file listing style

354

InduSoft Web Studio

Exercise: Viewing Your Application on the Web

IWS Training Guide

(Windows/DOS or Unix). numOverWrite Defines whether a file is to be overwritten if it exists. 0 = Do not overwrite. Error generated if the LocalFile already exists (default) 1 = Overwrite numTransferType Defines the type of file being transferred 0 = Unknown (default) 1 = ASCII 2 = Binary Returned Value 0 = Success 1 = Failed to create FTP thread -1 = Invalid number of parameters -2 = Unknown system error -3 = Invalid remote file -4 = Invalid local file -5 = Invalid transfer type Example ftpGet(\Reports\040307.txt, C:\Report040307.txt) The ftpPut function stores a file on the FTP Server. ftpPut Function Usage ftpPut(strLocalFile, strRemoteFile, numTransferType) Parameters strLocalFile This is the fully qualified name of the remote file (as it is referenced on the FTP Server). The FTP Server will have a FTP Site Directory where the files that are sent via FTP will be stored. The FTP Server may have a default file listing style (Windows/DOS or Unix). strRemoteFile This is a String Tag or Expression representing the fully qualified name of the remote file (as it is referenced on the FTP Server). The FTP Server will have a FTP Site Directory that will contain the files available for FTP, and may have a default file listing style (Windows/DOS or Unix). Some FTP Servers are case-sensitive. numTransferType Defines the type of file being transferred 0 = Unknown (default) 1 = ASCII 2 = Binary Returned Value 0 = Success 1 = Failed to create FTP thread -1 = Invalid number of parameters -2 = Unknown system error -3 = Invalid remote file -4 = Invalid local file -5 = Invalid transfer type Example ftpPut(C:\Report040307.txt, \Reports\040307.txt)

InduSoft Web Studio

355

IWS Training Guide

Exercise: Viewing Your Application on the Web

The ftpStatus function returns the current status of an FTP transaction initiated by a ftpGet or ftpPut function. The ftpStatus function is required since the ftpGet and ftpPut functions operate asynchronously. ftpStatus Function Usage ftpStatus(strTagName) Parameters strTagName This is a string expression representing the name of a String Tag that will receive a status description. Returned Value 0 = No transaction is being executed 1 = Transaction executed successfully 2 = Resolving Name 3 = Name Resolved 4 = Connecting to Server 5 = Connected to Server 6 = Closing Connection 7 = Connection Closed 8 = Sending Request 9 = Request Sent 10 = Receiving Response 11 = Intermediate Response Received 12 = Response Received 13 = Request Completed -2 = Invalid opttagErrorDescription -6 = Error Opening Connection (see Status String for Details) -7 = Error Establishing Connection (see Status String for Details) -8 = Error receiving the file (see Status String for Details) -9 = Transfer Pending Example Tag Name Expression numStat ftpStatus(strStatusDescription)

356

InduSoft Web Studio

Chapter 36.

SNMP

SNMP (Simple Network Management Protocol) is a new capability added to IWS Version 6.1 Service Pack 2. SNMP is an applications layer protocol used to facilitate the exchange of management information with network devices (e.g. Servers, Printers, Hubs, Switches, Routers) and network Administrators or network Management software. SNMP is part of the TCP/IP (Transmission Control Protocol/Internet Protocol) protocol suite.

In a typical SNMP architecture, there are three major components; the Managed Devices, Agents, and the Network Management Systems. Managed Devices A Managed Device is a node on a managed network that contains an SNMP Agent and is performs some sort of function that can be configured or monitored by the Network Management Systems. Examples of Managed Devices include Servers (e.g. an IWS Server), Routers, Switches, Hubs, and Printers. Agents An Agent is a network management software module that resides on a Managed Device, and provides information about the Managed Device to the Network Management System in Management Information Bases (MIBs). The Agent responds to requests from the SNMP requestor (Network Management System, or Manager). Network Management Systems The Network Management System is a set of applications that monitor and control the Managed Devices. One or more Network Management Systems (or SNMP Manager(s)) can exist on any managed network. The SNMP Manager communicates with the Managed Device using Read and Write Commands. The Managed Device uses Trap Commands to asynchronously report events to the SNMP Manager when a specified Event occurs. A device can operate as an SNMP Manager, Agent or both. SNMP lacks any authentication capabilities, and is therefore vulnerable to a variety of security threats. Often, Managed Devices (and their Agents) will not implement any Set operations, thereby reducing SNMP to a monitoring function.

SNMP with IWS


Using IWS or CEView, you can provide real-time data from the devices connected to the SCADA/HMI system through the native communication drivers and OPC interfaces e.g. from controllers, machines, etc.) to a thirdparty SNMP Manager, such as Microsoft Operations Manager (MOM), HP Openview, Novell NMS, IBM NetView, or Sun Net Manager. When used in this mode, IWS becomes the SNMP Agent, working as a gateway between the devices on the plant-floor and the corporative equipment management system (the SNMP Manager) at the ERP level.

InduSoft Web Studio

361

IWS Training Guide

Exercise: Viewing Your Application on the Web

IWS can also be configured as an SNMP Manager, requesting data from third-party SNMP Agents and displaying this information through its graphical interface, locally or remotely to Thin Client stations.

Installing SNMP
The SNMP interface from IWS uses the standard SNMP Service from Microsoft. The installation procedure depends on the operating system where you install the system and some dialogs illustrated in this document may vary depending on the OS version/type that you are using. Installation on Microsoft Windows 2000, Windows XP or Windows 2003 Server Step 1: Install the Microsoft SNMP Service Note: Follow the following procedures if Microsoft SNMP Service is not installed on your OS. You may need your Operating System CD-ROM for this procedure. Open the Control Panel (Start Control Panel) and double-click on the Add/Remote Programs icon. Select the option Add/Remove Windows Components, click on the Management and Monitoring Tools option and then click on the button Details. Check the option Simple Network Management Protocol, then click Ok and Next to install the Microsoft SNMP. Step 2: Configure the Microsoft SNMP Service After installing the Microsoft SNMP Service, you must configure its settings. Open the Control Panel (Start Control Panel), double-click on the Administrative Tools icon and then double-click on the Services icon. Right-click on the SNMP Service name and click on Properties. Make sure that the Local System Account radio button is selected in the Log On tab.

362

InduSoft Web Studio

Exercise: Viewing Your Application on the Web

IWS Training Guide

Select the Traps tab and add the Community Name called public (in case it does not exist yet) and add to the Trap destinations box the host name or IP address of the station(s) that must receive traps from the SNMP Agent (i.e. the host name or IP address of the station(s) where the SNMP Manager is running). Note: The SNMP protocol supports unsolicited messages (traps) from the SNMP Agent to the SNMP Manager (e.g.: change os status, alarm condition, etc) in order to optimize the communication in the network.

InduSoft Web Studio

363

IWS Training Guide

Exercise: Viewing Your Application on the Web

Select the Security tab and either select the option Accept SNMP packets from any host or select and option Accept SNMP packets from these hosts and add the list of host(s) where the SNMP Manager is running.

Step 3: Configure the InduSoft Web Studio SNMP Agent Open the Registry Editor (Start Run RegEdit). Select the key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SNMP\Parameters\ExtensionAge nts. This key lists the SNMP Agents linked to the Microsoft SNMP Service. Add a new String Value with the next sequential number available for the list and set its data value to SOFTWARE\Studio\SNMP.

364

InduSoft Web Studio

Exercise: Viewing Your Application on the Web

IWS Training Guide

Next, create the Key HKEY_LOCAL_MACHINE\SOFTWARE\Studio\SNMP and add a new String value with the name Pathname, whose value must be set with the path of the Studio SNMP Agent DLL file (StudioSnmp.dll) for example: c:\Program Files\InduSoft Web Studio v6.1\bin\StudioSnmp.dll. Close the Registry Editor.

Open the ProgramSettings.INI file with a text editor (e.g.: Notepad). The ProgramSettings.INI file is located on the \BIN sub-folder of the Indusoft Web Studio installation path (e.g.: c:\Program Files\InduSoft Web Studio v6.1\bin\Program Settings.ini). Create the following settings in the Program Settings.INI file: [SNMP] OidEnterpriseNumber=26640 TrapInterval=1 ApplicationTcpPort=1234 Save the changes and close the file editor. Notes: OidEnterpiseNumber: Unique number, which defines the position in the SNMP tree where the Studio data will be exposed (.1.3.6.1.4.1.[OidEnterpriseNumber]). The Studio number is 26640. TrapInterval: Interval (in seconds) used to send traps to the remote SNMP Manager(s). This parameter must be configured with a integer positive number. The default value is 1. ApplicationTcpPort: TCP Port number used to exchange data with the TCP/IP Server task from InduSoft Web Studio. The default value is 1234. After configuring all settings, re-start the SNMP Service by rebooting the computer or by right-clicking on the SNMP Service (<Start> _ Control Panel _ Administrative Tools _ Service) and clicking on the option Restart. Note: The Studio SNMP Agent exchanges data with the TCP/IP Server task from InduSoft Web Studio. Therefore, the TCP/IP Server task MUST be running in order to provide data to the SNMP Agent module. Make sure to set the TCP/IP Server task to Automatic in the InduSoft Web Studio menu (Project Status.

InduSoft Web Studio

365

IWS Training Guide

Exercise: Viewing Your Application on the Web

Installation on Microsoft Windows CE Step 1: Install the Microsoft SNMP Service The SNMP Server must be previously enabled in the image of the Windows CE device. If your Windows CE device does not provide the SNMP Agent, please consult your hardware vendor and ask them to add this Service to the image of the device. Step 2: Configure the InduSoft Web Studio (CEView) SNMP Agent Copy the following files into a non-volatile directory of the Windows CE device (preferentially, the same directory where CEView.exe is installed): - StudioSnmp.dll - StudioSnmpReg.exe

Note: The files mentioned above are stored in the following sub-folder after installing InduSoft Web Studio in your computer: \Redist\<OS_Version>\<ProcessorType> (e.g.: C:\Program Files\InduSoft Web Studio v6.1\Redist\Wince 4.0\x86). You can use the Send Files command from the Exeuction Environment dialog of InduSoft Web Studio to download these files to your Windows CE device. Optionally, you ca create a text file with a Text Editor (e.g.: Notepad) and save it with the name StudioSnmpReg.ini. This file must follow the structure illustrated in the example below: [SNMP] SnmpAgentPath=<Full path to the file StudioSnmp.dll> ProductPath=<Full path of the Bin folder of Studio> OidEnterpriseNumber=<enterprise number> ApplicationTcpPort=<TCP port used to communicate to Studio> TrapInterval=<Trap period, in seconds> SNMPDriverOrder=<SNMP driver order> [Trap Destination] 1=<IP address> 2=<IP address> 3=<IP address> The StudioSnmpReg.ini file allows you to customize some settings before installing the Studio SNMP Agent on your Windows CE device. If this file does not exit, the Studio SNMP Agent is installed with the default settings as described in the following table: Key Default Value Description Key Default Value Description SnmpAgentPath Same directory where Path where the StudioSnmp.dll is stored. StudioSnmpReg.exe is executed from. ProductPath Same directory where Path for the \BIN sub-folder of CEView (same folder StudioSnmpReg.exe is executed where CEView.exe is stored) from. OidEnterpriseNumber 26640 Unique number, which defines the position in the SNMP tree where the Studio data will be exposed (.1.3.6.1.4.1.[OidEnterpriseNumber]). TrapInterval 1 Interval (in seconds) used to send traps to the remote SNMP Manager(s). This parameter must be configured with a integer positive number. ApplicationTcpPort 1234 TCP Port number used to exchange data with the TCP/IP Server task from InduSoft Web Studio. SNMPDriverOrder Order to load the SNMP Driver. Usually, this parameter is not required. Consult you software vendor if you have problems during the installation of the IWS SNMP Agent.

366

InduSoft Web Studio

Exercise: Viewing Your Application on the Web

IWS Training Guide

In addition to the parameters mentioned above, the Key [Trap Destination] list the Host Name or IP Address of the station(s) that must receive traps from the SNMP Agent. In other words, the host name or IP address of the station(s) where the SNMP Manager is running. Copy the StudioSnmpReg.ini (if any) to the same directory where the StudioSnmpReg.exe is stored (on the Windows CE device) and execute the StudioSnmpReg.exe program to install the Studio SNMP Agent on the Windows CE device. Wait until a message is displayed indicating the completion of the installation. Save the Registry and reboot the Windows CE device and the Studio SNMP Agent must be automatically loaded by the SNMP Service from the operating system. Notes: It is strongly recommended copying the StudioSnmpReg.ini, StudioSnmpReg.exe and StudioSnmp.dll in the same directory where CEView.exe is stored (e.g.: \HardDisk\Studio\BIN\). The Studio SNMP Agent exchanges data with the TCP/IP Server task from CEView. Therefore, the TCP/IP Server task MUST be running in order to provide data to the SNMP Agent module. Make sure to set the TCP/IP Server task to Automatic in the InduSoft Web Studio menu Project Status.

Step 3: Configure the InduSoft Web Studio (CEView) SNMP Agent The Studio SNMP Agent exposes data from the current application via the SNMP protocol. The Studio SNMP Agent has a unique ID number. Each data value exposed by the Studio SNMP Agent has an address (OID). The root of the OID space is .1.3.6.1.4.1.[EN] or (iso.org.dod.internet.private.enterprise.[EN]), where [EN] is the number configured in the parameter OidEnterpriseNumber of the file Program Settings.INI (Windows 2K/XP/2K3) or StudioSnmpReg.ini (Windows CE). By default, the EN number is 26640.

The OIDs exposed by Studio SNMP Agent are listed below: Name OID Type Description Name OID Type Description studioVersion 1.3.6.1.4.1.[EN].1.1.0 String Studio version number studioLicense 1.3.6.1.4.1.[EN].1.2.0 String Studio license type applicationName 1.3.6.1.4.1.[EN].1.3.0. String Name of the application being executed by Studio applicationRevision 1.3.6.1.4.1.[EN].1.4.0 String Revision Number of the application being executed by Studio. tagTable 1.3.6.1.4.1.[EN].1.5 Table Table containing a list of the tags used in the current application and exposed to the SNMP Manger. The Table tagTable has 5 columns with the following information: Column Name De Column Name Description 1 tagName String. The tag name. 2 tagType String. The Tag Type (bool, integer, real or string). 3 tagValue String. The current tag value. 4 tagQuality String. The quality of the tag value. (good or bad). 5 tagTrap String. A number that indicates if the tag fires a trap when its value changes. 1 means trap is active; 0 means trap is inactive. You must configure the tags that will be exposed by the Studio SNMP Agent (by default, no tags are exposed). In order to configure the tags that will be exposed by the Studio SNMP Agent, just create a Text File with the CSV (Comma Separated Value) format. The file name must be SNMP.csv and it must be saved in the \Config sub-folder of your application.

InduSoft Web Studio

367

IWS Training Guide

Exercise: Viewing Your Application on the Web

You can configure one tag in each line of the file, according to the following syntax: TagName, Trap Where: - TagName: Name of the tag that will be exposed by the Studio SNMP Agent. - Trap: Flag indicating if the Studio SNMP Agent must generate traps when this tag changes of value (0=trap disabled; 1=trap enabled). The following example illustrates a valid SNMP.CSV file, which makes three tags available to remote SNMP Manager (TagLevel, Alarm and Second) and generates traps automatically when the tag Alarm changes of value. TagLevel,0 Alarm,1 Second.0

368

InduSoft Web Studio

Chapter 37.

Using the Remote Agent

After configuring an application and testing it locally (on your development workstation), you can download the application to a remote run-time workstation that is running under Windows NT/2000/XP or CEView under Windows CE.

Exercise: Configuring the Remote Agent


Before you begin, verify that the Remote Agent (CEServer.exe) is running on the remote target workstation. Note: The CESERVER.EXE file is located in the following directory on Windows NT/2000/XP computers: \InduSoft Web Studio\Redist\CEView\<Processor Type>\BIN The file should be located in the \<non-volatile> folder on WinCE device. Run the CEServer.exe to launch the Remote Agent dialog on the remote workstation.

Remote Agent Dialog Click the Setup button in the Remote Agent dialog on the run-time workstation. When the Setup dialog opens, specify the device connection method (Serial or TCP/IP) for connecting to the development workstation.

Remote Agent Setup Dialog

InduSoft Web Studio

371

IWS Training Guide

Exercise: Configuring the Remote Agent

Note: We recommend using TCP/IP instead of Serial Link for performance reasons. Click OK to close the Setup dialog, but leave the Remote Agent program running in the remote workstation. Select Project Execution Environment from IWS (on the development workstation).

Execution Environment Dialog Specify a link type for the Target Station (Network IP or Serial Port). If you select Network IP, type the IP address of the remote workstation into the text box.

Specifying Link Type and IP Address Click the Connect button to connect to the remote workstation. Note: If the remote workstation is a WinCE device, you can click on the Install System Files button to download the CEView runtime files to the remote workstation.

In the Workspace window, select the Application tab and click the Send to Target button to download the application to the remote workstation. After downloading all application files, click the Run button to execute the application in the remote target workstation.

372

InduSoft Web Studio

Downloading a CEView Application

IWS Training Guide

Downloading a CEView Application


You must use the Project Settings dialog to configure the CEServer.EXE for TCP/IP communications before running your CE unit. In the development environment (on the development workstation), click the Execution Environment button. When the Execution Environment dialog displays, type the IP address of the CE unit, and then click the Connect button.

Execution Environment Dialog When the Status field display indicates that you are connected, click the Install system files button to install the CEView on the remote workstation. After installing CEView, click the Application tab.

Click the Application Tab

InduSoft Web Studio

373

IWS Training Guide

Downloading a CEView Application

Click the Browse button, located next to the Target field, when the Browse Target dialog displays, and choose the remote directory where you will download the application.

Select the Remote Directory Click the Send to Target button to download the application. Note: The CE unit must be running CEServer.exe. After downloading the application, you can click the Run button to start the application and click Stop to stop the application while connected to the CE unit. The Status field displays the last operation status.

Other notes:

A.

Remote Agent CEServer Needs to be installed on the target machine Can be used for Windows XP/2000/NT machines or Windows CE Note: Windows CE-based systems may not automatically update the system registry following a file download. If not, the registry must be updated (saved) manually using CECP, SaveReg, RegSave or some other utility provided by the hardware manufacturer.

B. Allows download of system files, application and license files License information embedded in registry Application and system files installed in same directory as CEServer

374

InduSoft Web Studio

Downloading a CEView Application

IWS Training Guide

Notes

InduSoft Web Studio

375

Chapter 38. Runtime Configuration


After configuring an application and testing it locally (on your development workstation), you can download the application to a remote run-time workstation that is running under Windows NT/2000/XP or CEView under Windows CE.

Automatic booting of application at runtime For XP/2000/NT-based systems: Put a shortcut to RunStartUp (in IWS \Bin folder) into the Windows StartUp folder. For CE-based systems: Under Path:\<non-volatile>\ put CE_Start.exe and CE_Start.ini into this folder. When the WinCE device launches, it executes the file in CE_Start.ini. This file needs to be provided by the hardware manufacturer, and is not provided by InduSoft. Another file in this folder is CEApp.ini, which contains the path of the InduSoft application. This file is updated by InduSoft Remote Agent. See ImageforCEView Technote.

InduSoft Web Studio

381

Appendix A. VBScript Examples


The following are examples of VBScript code used with IWS for various purposes.

Using WSDL & SOAP (Windows XP)


WSDL (Web Services Description Language, pronounced wiz-dull) is an XML-based language used for communication of data with Web-based services. It is generally used in conjunction with SOAP and XML Schema to provide web services over an Internet connection. The Client device connects to the web service, and can read the WSDL to determine what functions are available on the Server. Any special data types used are embedded in the WSDL file in the form of XML Schema. The client can then use SOAP to actually call one of the functions listed in the WSDL. SOAP (Simple Object Access Protocol) is a protocol used for exchanging XML-based messages over a computer network, normally using HTTP (can also work with SMTP). SOAP is often used with Web Services. This application calls a Web Service to convert between temperatures (C F, F C) $tempC = 37 Set oXML = CreateObject("MSSOAP.SoapClient") oXML.ClientProperty ("ServerHTTPRequest") =True WSDL = "http://developerdays.com/cgi-bin/tempconverter.exe/wsdl/ITempConverter" oXML.mssoapinit WSDL $tempF = oXML.CtoF (CInt($tempC)) Set oXML = Nothing This application calls a Web Service to generate random lottery If $trigger_flag = 1 Then $trigger_flag = 0 WSDL = "http://reto.checkit.ch/scripts/lotto.dll/wsdl/IgetNumbers" lotto_min = 1 lotto_max = 48 lotto_number = 6 lotto_count = 1 Set oXML = CreateObject("MSSOAP.SoapClient") oXML.ClientProperty ("ServerHTTPRequest") =True oXML.mssoapinit WSDL $lotto_result = oXML.getLottoNumbers (lotto_min, lotto_max, lotto_number, lotto_count) Set oXML = Nothing End If

InduSoft Web Studio

A1

IWS Training Guide

Using the WSHShell Object (Windows XP)

Using the WSHShell Object (Windows XP)


WSH (Windows Scripting Host) allows you to run Command Line tools (via the Shell Object) similar to CMD.exe, and to conduct system administration tasks (via COM Objects). WSHShell can provide access to the System Registry, environmental variables, location of System Folders and start Processes. Dim WSHShell Set WSHShell = CreateObject("WScript.Shell") ' Define the path for the special folder MsgBox WSHShell.SpecialFolders("Startup") ' Allows access to System environment variables, Types are System, User, Volatile or Process Set WSHEnv = WSHShell.Environment("System") MsgBox WSHEnv("Path") MsgBox WSHEnv("Processor_Architecture") ' Runs an application and send the application keystrokes (as if they were typed WSHShell.Run ("%windir%\notepad.exe") WSHShell.AppActivate "Notepad" ' Puts Data in the Application WSHShell.SendKeys "Hello World" WSHShell.SendKeys "{Enter}" Set WSHNetwork = CreateObject("WScript.Network") msg = "UserName:" & WSHNetwork.Username & vbCrLf msg = msg & "ComputerName:" & WSHNetwork.ComputerName & vbCrLf ' msg = msg & "Domain:" & WSHNetwork.Domain & vbCrLf MsgBox msg

The following example is from Microsoft and has not yet been tested This WSH script uses ADSI, (Active Directory) to create a new User Account Set objOU = Wscript.GetObject("LDAP://OU=management,dc=fabrikam,dc=com") Set objUser = objOU.Create("User", "cn=MyerKen") objUser.Put "sAMAccountName", "myerken" objUser.SetInfo

A2

InduSoft Web Studio

Using the Windows Shell (Windows XP)

IWS Training Guide

Using the Windows Shell (Windows XP)


Windows also provides a Shell.LocalMachine COM class that allows access to information about your local PC. Dim objComputer, msg Set objComputer = CreateObject("Shell.LocalMachine") msg = "" msg = msg & "Computer name: " & objComputer.MachineName & vbCrLf msg = msg & "Shutdown allowed: " & objComputer.IsShutdownAllowed & vbCrLf msg = msg & "Friendly UI enabled: " & objComputer.IsFriendlyUIEnabled & vbCrLf msg = msg & "Guest access mode: " & objComputer.IsGuestAccessMode & vbCrLf msg = msg & "Guest account enabled: " & objComputer.IsGuestEnabled(0) & vbCrLf msg = msg & "Multiple users enabled: " & objComputer.IsMultipleUsersEnabled & vbCrLf msg = msg & "Offline files enabled: " & objComputer.IsOfflineFilesEnabled & vbCrLf msg = msg & "Remote connections enabled: " & objComputer.IsRemoteConnectionsEnabled &_ vbCrLf msg = msg & "Undock enabled: " & objComputer.IsUndockEnabled & vbCrLf MsgBox msg

InduSoft Web Studio

A3

IWS Training Guide

Using the WinMgmts and WMIServices Object (Windows XP)

Using the WinMgmts and WMIServices Object (Windows XP)


WMI (or Windows Management Instrumentation) provides an interface between an IWS application and the Operating System (Windows 2000/XP/Server 2003/Vista). It is not fully supported on Windows NT, and not supported on Windows CE. WMI is Microsofts implementation of the Common Information Model (CIM) initiative, promoted by an association of vendors including Microsoft, Cisco, and HP. WMI exposes a collection of COM (Component Object Modules) modules to a Scripting language such as VBScript. It support access to local and remote computers. You can use WMI to access and manipulate basic system settings (e.g what would be available through the Control Panel), display and control the hardware attached to the computer, and display security settings (e.g. firewall). Dim objWMIService, objWMIService2, objService, objComputer, objCSItem, objOS, objOSItem Dim objItem, objOperatingSystem Dim colSettings colOSes, colOSItems, colServices, colCSItems, colItems, colSettings Dim msg, strComputer strComputer = "." Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & _ strComputer & "\root\cimv2") 'Verify if SQL is installed on this PC Set colServices = objWMIService.ExecQuery ("Select * from Win32_Service Where Name =_ 'MSSQLServer'") If colServices.Count > 0 Then For Each objService In colServices MsgBox "SQL Server is " & objService.State & "." Next Else MsgBox "SQL Server is not installed on this computer." End If msg = "" Set colSettings = objWMIService.ExecQuery ("Select * from Win32_ComputerSystem") For Each objComputer In colSettings msg = msg & "System Name: " & objComputer.Name & vbCrLf msg = msg & "Total Physical Memory: " & objComputer.TotalPhysicalMemory & vbCrLf Next Set colOSes = objWMIService.ExecQuery("Select * from Win32_OperatingSystem") For Each objOS In colOSes msg = msg & "Computer Name: " & objOS.CSName & vbCrLf msg = msg & "Caption: " & objOS.Caption & vbCrLf 'Name msg = msg & "Version: " & objOS.Version & vbCrLf 'Version & build msg = msg & "Build Number: " & objOS.BuildNumber & vbCrLf 'Build number msg = msg & "Build Type: " & objOS.BuildType & vbCrLf ' Build type msg = msg & "OS Type: " & objOS.OSType & vbCrLf msg = msg & "Other Type Description: " & objOS.OtherTypeDescription & vbCrLf msg = msg & "Service Pack: " & objOS.ServicePackMajorVersion & "." & objOS.ServicePackMinorVersion & vbCrLf Next Set objWMIService2 = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") Set colCSItems = objWMIService2.ExecQuery("SELECT * FROM Win32_ComputerSystem") For Each objCSItem In colCSItems msg = msg & "Total Physical Memory: " & objCSItem.TotalPhysicalMemory & vbCrLf

A4

InduSoft Web Studio

Using the WinMgmts and WMIServices Object (Windows XP)

IWS Training Guide

Next Set colOSItems = objWMIService2.ExecQuery("SELECT * FROM Win32_OperatingSystem") For Each objOSItem In colOSItems msg = msg & "Free Physical Memory: " & objOSItem.FreePhysicalMemory & vbCrLf msg = msg & "Total Virtual Memory: " & objOSItem.TotalVirtualMemorySize & vbCrLf msg = msg & "Free Virtual Memory: " & objOSItem.FreeVirtualMemory & vbCrLf msg = msg & "Total Visible Memory Size: " & objOSItem.TotalVisibleMemorySize & vbCrLf Next MsgBox msg Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") strComputer = "." Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" _ & strComputer & "\root\cimv2") Set colSettings = objWMIService.ExecQuery ("Select * from Win32_OperatingSystem") For Each objOperatingSystem In colSettings MsgBox "Available Physical Memory: " & objOperatingSystem.FreePhysicalMemory Next strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set colItems = objWMIService.ExecQuery("Select * from Win32_CDROMDrive") msg = "" For Each objItem In colItems msg = msg & "Device ID: " & objItem.DeviceID & vbCrLf msg = msg & "Description: " & objItem.Description & vbCrLf msg = msg & "Name: " & objItem.Name & vbCrLf Next MsgBox msg This example displays each System-level Service and its status strComputer = "." Set objSWbemServices = GetObject("winmgmts:\\" & strComputer) Set colSWbemObjectSet = objSWbemServices.InstancesOf("Win32_Service") For Each objSWbemObject In colSWbemObjectSet s = "Display Name: " & objSWbemObject.DisplayName & vbCrLf & " State: " & objSWbemObject.State & vbCrLf & _ " Start Mode: " & objSWbemObject.StartMode MsgBox s Next

InduSoft Web Studio

A5

Using CDO (Windows XP)


CDO (or Collaboration Data Objects) is a Microsoft technology for building messaging (Email) or collaboration application. Several components are included with Microsoft Windows (2000, NT, XP) while others are only included with Microsoft Exchange. The following example will send an email. Const cdoSendUsingMethod= "http://schemas.microsoft.com/cdo/configuration/sendusing" Const cdoSendUsingPort = 2 Const cdoSMTPServer = "http://schemas.microsoft.com/cdo/configuration/smtpserver" Const cdoSMTPServerPort = "http://schemas.microsoft.com/cdo/configuration/smtpserverport" Const cdoSMTPConnectionTimeout = _ "http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout" Const cdoSMTPAuthenticat = "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate" Const cdoBasic = 1 Const cdoSendUserName = "http://schemas.microsoft.com/cdo/configuration/sendusername" Const cdoSendPassword = "http://schemas.microsoft.com/cdo/configuration/sendpassword" Dim objConfig Dim objMessage Dim Fields 'CDO.Configuration 'CDO.Message 'ADODB.Fields

' Get a handle on the config object and it's fields Set objConfig = CreateObject("CDO.Configuration") Set Fields = objConfig.Fields ' Set config fields we care about With Fields ' .Item(cdoSendUsingMethod) .Item(cdoSMTPServer) .Item(cdoSMTPServerPort) .Item(cdoSMTPConnectionTimeout) .Item(cdoSMTPAuthenticate) .Item(cdoSendUserName) .Item(cdoSendPassword) .Update End With

= cdoSendUsingPort = "smtp.ameritech.yahoo.com" = 25 = 10 = cdoBasic = "name@ameritech.net" = "password"

Set objMessage = CreateObject("CDO.Message") Set objMessage.Configuration = objConfig With objMessage .To = "name@indusoft.com" .From = "Display Name <email_address>" .Subject = "SMTP Relay Test" .TextBody = "SMTP Relay Test Sent @ " & Now() .Send End With Set Fields = Nothing Set objMessage = Nothing Set objConfig = Nothing

InduSoft Web Studio

A1

IWS Training Guide

Using Office Automation (Windows XP)

Using Office Automation (Windows XP)


While VBA is typically used to automation Microsoft Office applications, VBScript can do the job as well. This (lengthy) application that reads data from a Microsoft Access Database, uses the data to populate an Excel Spreadsheet, generate a Graph of the data, send the Graph as an picture object to Microsoft Word and print a report. Const xlPrimary = 1 Const xlCategory =1 Const xlValue = 2 Const xlLocationAsNewSheet=1 Const wdOrientPortrait = 0 Const wdOrientLandscape = 1 Const wdPrinterDefaultBin = 0 Const wdSectionNewPage = 2 Const wdAlignVerticalTop = 0 Const wdAlignParagraphLeft = 0 Const wdAlignParagraphCenter = 1 Const wdAlignParagraphRight = 2 Const wdAlignParagraphFull = 1 Const wdMainTextStory = 1 Const wdVerticalPositionRelativeToPage = 6 Const xlLine = 4 Const adOpenKeyset = 1 Const adLockOptimistic = 3 Const adUseServer = 2 Dim xlsapp, xlsBook, xlsdoc, xlschart, db Dim xlsAxisCategory, xlsAxisValue, xlsSeries Dim fso, rc Dim strConn Dim strPathToMDB, myStr Dim strSQL Dim DBRowCount Dim OldMyDbRead1Line Sub MSAccessReadDB(TableNum) strPathToMDB = $InfoAppDir() & "\Data\MyDB.mdb" strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & strPathToMDB & ";" Set db = CreateObject ("ADODB.Connection") db.open strConn If TableNum = 0 Then strSQL = "Select * From Table1" ' read from table 1 If TableNum = 1 Then strSQL = "Select * From Table2" ' read from table 2 Set rs = db.Execute (strSQL) DbRowCount = -1 While Not rs.EOF DbRowCount = DbRowCount + 1 $ProdStat[DbRowCount].Time= CStr(rs("Time")) $ProdStat[DbRowCount].Total = CInt(rs("Total")) $ProdStat[DbRowCount].Good = CInt(rs("Good")) $ProdStat[DbRowCount].Marginal = CInt(rs("Marginal")) $ProdStat[DbRowCount].Bad = CInt(rs("Bad")) rs.MoveNext Wend db.close Set db = Nothing

A2

InduSoft Web Studio

Using Office Automation (Windows XP)

IWS Training Guide

End Sub Function InchesToPoints(Inches) InchesToPoints = Inches * 72 End Function 'This procedure is executed just once when this screen is open. Sub Screen_OnOpen() $MyReportLine = 1 $MyDbRead1Line = 0 OldMyDbRead1Line = $MyDbRead1Line MSAccessReadDB($MyDbRead1Line) $myProdName[0] = "Batch 1234" $myProdName[1] = "Batch ABCD" End Sub 'This procedure is executed continuously while this screen is open. Sub Screen_WhileOpen() If $MyDBRead = 1 Then ' Read the CSV file $MyDBRead = 0 myFolder = $InfoAppDir() & "\Data" strConn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & myFolder & ";" strConn = strConn & "Extended Properties=""text;HDR=Yes;FMT=CSVDelimited""" Set Conn = CreateObject("ADODB.Connection") Conn.open = strConn Set rs = CreateObject("ADODB.Recordset") strSql = "Select * FROM MyData.txt" Set rs = Conn.Execute(strSql) recStr="" Do Until rs.EOF recStr = recStr & "value1= " & rs.Fields.Item("val1") recStr = recStr & " val2= " & rs.Fields.Item("val2") recStr = recStr & " val3= " & rs.Fields.Item("val3") & vbCrLf rs.Movenext Loop MsgBox recStr rs.close Conn.close Set rs = Nothing Set Conn = Nothing End If ' The example below calls a routine that reads from a MS Access file and stores the information into a Class tag ' The class tag is then displayed in a Grid Object on the Screen If OldMyDbRead1Line <> $MyDbRead1Line Then ' Check for a change in the radio button being pressed to read a different table OldMyDbRead1Line = $MyDbRead1Line MSAccessReadDB(CInt($MyDbRead1Line)) End If

' The code below generates a sample production report using MS Word. Production data is put into an

InduSoft Web Studio

A3

IWS Training Guide

Using Office Automation (Windows XP)

' Excel chart and the chart is copied into the Word document If $genReport = 1 Then ' see if the report key has been set $genReport = 0 ' Yes. Reset the key and generate the report. Set fso = CreateObject("Scripting.FileSystemObject") WordName = $InfoAppDir() & "\Data" & "\MyNewReport.doc" XLSName = $InfoAppDir() & "\Data" & "\MyNewChart.xls" If fso.fileexists(WordName) Then fso.deletefile WordName If fso.fileexists(XLSName) Then fso.deletefile XLSName Set xlsapp = CreateObject("Excel.Application") Set xlsBook = xlsapp.Workbooks.Add Set xlsdoc = xlsBook.Worksheets.Add xlsdoc.name = "Production Data" Set xlschart = xlsBook.Charts.Add xlschart.name = "Production Chart" xlsapp.visible = True strPathToMDB = $InfoAppDir() & "\Data" & "\MyDB.mdb" strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & strPathToMDB & ";" Set db = CreateObject ("ADODB.Connection") db.open strConn If $MyReportLine = 1 Then strSQL = "Select * From Table1" ' read from table 1 $FixTable = "Table1" End If If $MyReportLine = 2 Then strSQL = "Select * From Table2" ' read from table 2 $FixTable = "Table2" End If Set rs = db.Execute (strSQL) $line_total = 0 $line_good = 0 $line_marginal = 0 $line_bad = 0 With xlsdoc row_val = 1 ' Add Column headers .Range("A" & CStr(row_val)).Value = "Production ID" .Range("C" & CStr(row_val)).Value = $myProdName[$MyReportLine] row_val = 3 ' Add Column headers .Range("A" & CStr(row_val)).Value = "Time" .Range("B" & CStr(row_val)).Value = "Total" .Range("C" & CStr(row_val)).Value = "Good" .Range("D" & CStr(row_val)).Value = "Marginal" .Range("E" & CStr(row_val)).Value = "Bad" row_val = 4 While Not rs.EOF ' Fill cells with values to build chart .Range("A" & CStr(row_val)).Value = CStr(rs("Time")) $line_total = $line_total + rs("Total") .Range("B" & CStr(row_val)).Value = CInt(rs("Total")) $line_good = $line_good + rs("Good")

A4

InduSoft Web Studio

Using Office Automation (Windows XP)

IWS Training Guide

.Range("C" & CStr(row_val)).Value = CInt(rs("Good")) $line_marginal = $line_marginal + rs("Marginal") .Range("D" & CStr(row_val)).Value = CInt(rs("Marginal")) $line_bad = $line_bad + rs("Bad") .Range("E" & CStr(row_val)).Value = CInt(rs("Bad")) row_val = row_val +1 rs.MoveNext Wend End With db.close Set db = Nothing ' Set chart parameters Set xlsSeries = xlschart.SeriesCollection With xlschart .ChartType = xlLine ' Set type of chart we want (XL Line) .SetSourceData(xlsdoc.Range("A4:E" & row_val-1)) ' Range from where the chart will be built Set xlsAxisCategory = .Axes (, xlPrimary) xlsAxisCategory.Item(xlCategory).HasTitle = True xlsAxisCategory.Item(xlCategory).AxisTitle.Characters.Text = "Time" xlsAxisCategory.Item(xlCategory).HasMajorGridlines = True xlsAxisCategory.Item(xlCategory).HasMinorGridlines = False Set xlsAxisValue = .Axes(, xlPrimary) xlsAxisValue.Item(xlValue).HasTitle = True xlsAxisValue.Item(xlValue).AxisTitle.Characters.Text = "Widgets Production - Line #" &_ $MyReportLine xlsAxisValue.Item(xlValue).HasMajorGridlines = True xlsAxisValue.Item(xlValue).HasMinorGridlines = False .PlotArea.Interior.ColorIndex = 2 .ChartArea.Interior.ColorIndex = 2 .ChartArea.Interior.PatternColorIndex = 1 xlsSeries.Item(1).Name = "Total Production" xlsSeries.Item(2).Name = "Total Good" xlsSeries.Item(3).Name = "Total Marginal" xlsSeries.Item(4).Name = "Total Bad" .Location(xlLocationAsNewSheet) xlsBook.SaveAs(XLSName) End With Dim app, doc, myRange, mydoc, vert_pos Set app = CreateObject ("Word.Application") Set doc = app.Documents.Add app.Visible = True ' Set up Report Page With app.ActiveDocument.PageSetup .LineNumbering.Active = False .Orientation = wdOrientPortrait .TopMargin = InchesToPoints(0.5) .BottomMargin = InchesToPoints(0.5) .LeftMargin = InchesToPoints(0.7) .RightMargin = InchesToPoints(0.7) .Gutter = InchesToPoints(0) .HeaderDistance = InchesToPoints(0.5) .FooterDistance = InchesToPoints(0.5) .PageWidth = InchesToPoints(8.5)

InduSoft Web Studio

A5

IWS Training Guide

Using Office Automation (Windows XP)

.PageHeight = InchesToPoints(11) .FirstPageTray = wdPrinterDefaultBin .OtherPagesTray = wdPrinterDefaultBin .SectionStart = wdSectionNewPage .OddAndEvenPagesHeaderFooter = False .DifferentFirstPageHeaderFooter = False .VerticalAlignment = wdAlignVerticalTop .SuppressEndnotes = False .MirrorMargins = False End With ' Fill the document with appropriate information Set myRange = app.ActiveDocument.Range With myRange .ParagraphFormat.Alignment = wdAlignParagraphLeft .Font.Name = "Arial" .Font.Size = 11 .bold = False .InsertAfter "My Company, Inc" & vbCrLf .InsertAfter "Production Report" & vbCrLf .InsertAfter Now() & vbCrLf & vbCrLf .InsertAfter "Production ID : " & $myProdName[$MyReportLine] &vbCrLf &vbCrLf .InsertAfter "Total Number Produced = " & $line_total & vbCrLf .InsertAfter "Total Number Good = " & $line_good & vbCrLf .InsertAfter "Total Number Marginal = " & $line_marginal & vbCrLf .InsertAfter "Total Number Bad = " & $line_bad & vbCrLf End With ' Format the document myRange.SetRange app.ActiveDocument.Paragraphs(1).Range.Start, app.ActiveDocument.Paragraphs(3).Range.End With myRange .ParagraphFormat.Alignment = wdAlignParagraphCenter End With myRange.SetRange app.ActiveDocument.Paragraphs(1).Range.Start, app.ActiveDocument.Paragraphs(1).Range.End With myRange .Font.Size = 24 .bold = True End With myRange.SetRange app.ActiveDocument.Paragraphs(2).Range.Start, app.ActiveDocument.Paragraphs(3).Range.End With myRange .Font.Size = 14 End With myRange.SetRange app.ActiveDocument.Paragraphs(11).Range.Start, app.ActiveDocument.Paragraphs(11).Range.End vert_pos = myRange.Information(wdVerticalPositionRelativeToPage) With doc .Shapes.AddOLEObject , XLSName, , , , , , , CStr(vert_pos +25), "400", "320" End With doc.SaveAs WordName End If Set doc = Nothing

A6

InduSoft Web Studio

Using Office Automation (Windows XP)

IWS Training Guide

Set app=Nothing Set xlsapp = Nothing

InduSoft Web Studio

A7

Appendix B. Application Notes


Application Note AN-00-0001 Using the Div & Add and Max & Min Parameters in a Main or Standard Driver Sheet Application Note AN-00-0002 Dynamically Loading Pictures on a Screen using an ActiveX Control and VBScript Application Note AN-00-0003 Using the Radio Button and Check Box Objects Application Note AN-00-0004 Using XML in InduSoft Web Studio Application Note AN-00-0005 Manipulating Collections, Folders and Files with InduSoft Web Studio Built-in Functions Application Note AN-00-0006 Manipulating Collections, Folders and Files with VBScripts FileSystemObject Application Note AN-00-0007 Using InduSoft Web Studio with TouchScreen PCs

InduSoft Web Studio

B1

Вам также может понравиться