IWS_Training_Guide_v.. - FF-Automation
IWS_Training_Guide_v.. - FF-Automation
IWS_Training_Guide_v.. - FF-Automation
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
InduSoft Web Studio<br />
Advanced <strong>Training</strong><br />
Course<br />
Part B<br />
www.InduSoft.com<br />
877.463.8763
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Copyright<br />
Copyright © 2007 by InduSoft ® . All rights reserved worldwide.<br />
No part of this publication may be reproduced or transmitted in any form or by any means without written authorization from InduSoft.<br />
The information contained within this document is subject to change without notice. InduSoft does not assume responsibility for any errors<br />
or inaccuracies that may occur in this publication.<br />
InduSoft is a registered trademark of InduSoft. CEView is a trademark of InduSoft. Windows, Windows XP, Windows 2000, and Windows<br />
NT are registered trademarks of Microsoft Corp. in the United States and other countries. Other brand or product names are trademarks or<br />
registered trademarks of their respective owners.<br />
PN: IND-TG/TG-001<br />
ii<br />
InduSoft Web Studio
Contents<br />
CHAPTER 19. <strong>IWS</strong> FILE/DATABASE CONFIGURATION............................................................................19–1<br />
USING THE <strong>IWS</strong> PROPRIETARY FILE FORMAT......................................................................................... 19–1<br />
<strong>IWS</strong> PROPRIETARY FILE AND DATABASE FORMAT FOR ALARM HISTORY.................................................. 19–3<br />
<strong>IWS</strong> PROPRIETARY FILE AND DATABASE FORMAT FOR EVENT HISTORY ................................................. 19–5<br />
<strong>IWS</strong> PROPRIETARY FILE AND DATABASE FORMAT FOR TREND HISTORY .................................................. 19–7<br />
USING THE BUILT-IN ADO.NET INTERFACE ............................................................................................ 19–8<br />
CONFIGURING THE DEFAULT DATABASE............................................................................................... 19–12<br />
CONFIGURING A TASK OR OBJECT DATABASE ...................................................................................... 19–15<br />
PRIMARY AND SECONDARY DATABASES............................................................................................... 19–16<br />
LINKING TO A REMOTE DB PROVIDER WITH STUDIO DATABASE GATEWAY.............................................. 19–17<br />
STUDIO DATABASE GATEWAY.............................................................................................................. 19–18<br />
CHAPTER 20. USING ODBC DATABASE SOURCE NAMES (DSN) ..........................................................20–1<br />
USING A DATABASE WITH A DSN ........................................................................................................... 20–4<br />
CHAPTER 21. ALARMS.................................................................................................................................21–1<br />
ALARM WORKSHEETS ........................................................................................................................... 21–2<br />
ALARM/EVENT CONTROL....................................................................................................................... 21–5<br />
EXERCISE: CREATING AN ALARM GROUP AND ALARM SCREEN................................................................ 21–7<br />
EXAMPLE: DISABLING ALARMS............................................................................................................. 21–14<br />
EXERCISE: ADDING AN ALARM/EVENT CONTROL DISPLAY..................................................................... 21–15<br />
CHAPTER 22. DATA LOGGING & TREND DISPLAY ..................................................................................22–1<br />
CONFIGURING THE TREND TASK ............................................................................................................ 22–1<br />
CONVERTING TREND HISTORY FILES ..................................................................................................... 22–4<br />
TREND CONTROL OBJECT ..................................................................................................................... 22–5<br />
Trend Control Development Interface............................................................................................ 22–5<br />
Trend Control Runtime Interface.................................................................................................... 22–6<br />
EXERCISE: CREATING AN ONLINE TREND ............................................................................................... 22–7<br />
Decreasing the Save Frequency Using the Scheduler ................................................................ 22–12<br />
USING AN EXTERNAL TEXT FILE........................................................................................................... 22–13<br />
USING AN EXTERNAL DATABASE.......................................................................................................... 22–17<br />
CHAPTER 23. EVENT MANAGER ................................................................................................................23–1<br />
EXERCISE: CONFIGURING EVENT RETRIEVAL ......................................................................................... 23–2<br />
CHAPTER 24. GRID OBJECT .......................................................................................................................24–1<br />
EXAMPLE: USING THE GRID OBJECT WITH EXCEL ................................................................................. 24–11<br />
CHAPTER 25. VBSCRIPT..............................................................................................................................25–1<br />
VBSCRIPT LIMITATIONS IN <strong>IWS</strong> ............................................................................................................. 25–2<br />
DI<strong>FF</strong>ERENCES BETWEEN VBSCRIPT AND VBA ........................................................................................ 25–3<br />
VBSCRIPT LANGUAGE OVERVIEW.......................................................................................................... 25–4<br />
VBSCRIPT FUNCTIONALITY.................................................................................................................... 25–4<br />
VBSCRIPT ELEMENTS........................................................................................................................... 25–4<br />
VARIABLE DATA TYPES AND SUBTYPES.................................................................................................. 25–5<br />
DATA SUBTYPE IDENTIFICATION............................................................................................................. 25–5<br />
DATA SUBTYPE CONVERSION................................................................................................................ 25–6<br />
VARIABLE NAMING RULES & CONVENTIONS............................................................................................ 25–6<br />
VARIABLE SCOPE.................................................................................................................................. 25–6<br />
VBSCRIPT CONSTANTS......................................................................................................................... 25–7<br />
InduSoft Web Studio<br />
iii
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Contents<br />
DECLARING VBSCRIPT VARIABLES AND CONSTANTS .............................................................................. 25–7<br />
VBSCRIPT KEYWORDS.......................................................................................................................... 25–7<br />
OPERATORS ......................................................................................................................................... 25–8<br />
OPERATOR PRECEDENCE...................................................................................................................... 25–9<br />
FUNCTIONS......................................................................................................................................... 25–10<br />
STATEMENTS...................................................................................................................................... 25–14<br />
VBSCRIPT OBJECT COMMANDS........................................................................................................... 25–17<br />
VBSCRIPT USER-DEFINED CLASS OBJECTS......................................................................................... 25–18<br />
EXAMPLE: USING VBSCRIPT USER-DEFINED CLASS OBJECTS .............................................................. 25–22<br />
VBSCRIPT OBJECTS AND COLLECTIONS............................................................................................... 25–23<br />
COM OBJECTS AND COLLECTIONS...................................................................................................... 25–33<br />
VBSCRIPT CONFIGURATION AND OPERATION IN <strong>IWS</strong>............................................................................ 25–37<br />
GLOBAL PROCEDURES........................................................................................................................ 25–38<br />
GRAPHICS SCRIPT .............................................................................................................................. 25–39<br />
SCREEN SCRIPTS ............................................................................................................................... 25–40<br />
COMMAND DYNAMIC ........................................................................................................................... 25–42<br />
ACTIVEX EVENTS................................................................................................................................ 25–43<br />
BACKGROUND TASK STARTUP SCRIPT ................................................................................................. 25–44<br />
BACKGROUND TASK SCRIPT GROUPS.................................................................................................. 25–45<br />
SCOPE OF VBSCRIPT PROCEDURES AND VARIABLES............................................................................ 25–47<br />
ACCESSING <strong>IWS</strong> TAGS AND <strong>IWS</strong> BUILT-IN FUNCTIONS.......................................................................... 25–49<br />
ACCESSING ACTIVEX OBJECTS FROM VBSCRIPT ................................................................................. 25–52<br />
INTELLISENSE..................................................................................................................................... 25–54<br />
VBSCRIPT WITH WEB THIN CLIENTS .................................................................................................... 25–56<br />
EXERCISE: USING VBSCRIPT WITH SCREENS....................................................................................... 25–57<br />
EXERCISE: USING VBSCRIPT & SCRIPT WORKSHEETS ......................................................................... 25–58<br />
EXERCISE: USING VBSCRIPT............................................................................................................... 25–61<br />
CHAPTER 26. DATABASES..........................................................................................................................26–1<br />
CHAPTER 27. CONFIGURING THE DATABASE .........................................................................................27–1<br />
CHAPTER 28. SQL – THE LANGUAGE OF DATABASES ..........................................................................28–1<br />
SQL NOMENCLATURE........................................................................................................................... 28–2<br />
SQL LANGUAGE DERIVATIVES............................................................................................................... 28–3<br />
SQL OPERATORS ................................................................................................................................. 28–4<br />
SQL DATATYPES................................................................................................................................ 28–12<br />
CONSTRAINTS AND KEYS..................................................................................................................... 28–14<br />
DDL SCHEMA STATEMENTS ................................................................................................................ 28–15<br />
DML QUERY STATEMENTS.................................................................................................................. 28–22<br />
JET SQL ........................................................................................................................................... 28–41<br />
TRANSACT-SQL ................................................................................................................................. 28–42<br />
EXAMPLES USING A SQL QUERY WITH <strong>IWS</strong> TAGS ................................................................................ 28–43<br />
CHAPTER 29. ACCESSING DATABASES WITH VBSCRIPT .....................................................................29–1<br />
ADO OVERVIEW ................................................................................................................................... 29–2<br />
RELATIONAL DATABASES SUPPORTED BY ADO ...................................................................................... 29–4<br />
DATABASE TERMINOLOGY ..................................................................................................................... 29–5<br />
DATA TYPE MAPPING............................................................................................................................ 29–6<br />
THE ADO CONNECTION OBJECT ........................................................................................................... 29–9<br />
THE ADO COMMAND OBJECT.............................................................................................................. 29–16<br />
THE ADO RECORDSET OBJECT .......................................................................................................... 29–18<br />
Using the Recordset Object ......................................................................................................... 29–23<br />
THE STREAM OBJECT ......................................................................................................................... 29–29<br />
USING THE ADOX OBJECT MODEL...................................................................................................... 29–30<br />
ADOCE AND ADOXCE ...................................................................................................................... 29–34<br />
iv<br />
InduSoft Web Studio
Contents<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
ADOVBS CONSTANTS........................................................................................................................ 29–37<br />
EXERCISE: USING ADO WITH VBSCRIPT.............................................................................................. 29–48<br />
EXERCISE: USING ADOX TO CREATE AN BLANK ACCESS DATABASE...................................................... 29–49<br />
CHAPTER 30. READING & WRITING XML USING VBSCRIPT...................................................................30–1<br />
PERSISTING DATA IN XML FORMAT USING ADO..................................................................................... 30–1<br />
USING THE XMLDOM........................................................................................................................... 30–3<br />
CHAPTER 31. ACTIVEX CONTROLS AND .NET ASSEMBLIES ................................................................31–1<br />
EXERCISE: INSERTING AN ACTIVEX CONTROL ........................................................................................ 31–6<br />
SYSTEM.COLLECTIONS.......................................................................................................................... 31–8<br />
CHAPTER 32. WEB THIN CLIENTS..............................................................................................................32–1<br />
BUILDING A SIMPLE WEB THIN CLIENT APPLICATION STEP BY STEP ........................................................ 32–3<br />
WEB THIN CLIENTS – THE UNDERLYING TECHNOLOGY ......................................................................... 32–11<br />
ISSYMBOL ACTIVEX CONTROL ............................................................................................................ 32–13<br />
WEB SERVER CONFIGURATION............................................................................................................ 32–16<br />
WEB TUNNELING GATEWAY CONFIGURATION ....................................................................................... 32–17<br />
WEB BROWSER CONFIGURATION......................................................................................................... 32–18<br />
DATA SERVER AND WEB CLIENT CONFIGURATION ................................................................................ 32–22<br />
EXAMPLE WEB SERVER/THIN CLIENT ARCHITECTURES......................................................................... 32–26<br />
SECURITY FOR WEB BASED APPLICATIONS .......................................................................................... 32–31<br />
PORT USAGE...................................................................................................................................... 32–36<br />
EXERCISE: VIEWING YOUR APPLICATION ON THE WEB.......................................................................... 32–37<br />
CHAPTER 33. WEB THICK CLIENTS ...........................................................................................................33–1<br />
Configuring the Server ................................................................................................................... 33–1<br />
Configuring the Client..................................................................................................................... 33–1<br />
CHAPTER 34. SYSTEM LEVEL REDUNDANCY..........................................................................................34–1<br />
CHAPTER 35. FTP .........................................................................................................................................35–1<br />
CHAPTER 36. SNMP......................................................................................................................................36–1<br />
CHAPTER 37. USING THE REMOTE AGENT ..............................................................................................37–1<br />
EXERCISE: CONFIGURING THE REMOTE AGENT ...................................................................................... 37–1<br />
DOWNLOADING A CEVIEW APPLICATION ................................................................................................ 37–3<br />
CHAPTER 38. RUNTIME CONFIGURATION ................................................................................................38–1<br />
APPENDIX A. VBSCRIPT EXAMPLES.......................................................................................................... A–1<br />
USING THE WSHSHELL OBJECT (WINDOWS XP)......................................................................................A–2<br />
USING THE WINDOWS SHELL (WINDOWS XP)...........................................................................................A–3<br />
USING THE WINMGMTS AND WMISERVICES OBJECT (WINDOWS XP)........................................................A–4<br />
USING CDO (WINDOWS XP) ...................................................................................................................A–1<br />
USING O<strong>FF</strong>ICE AUTOMATION (WINDOWS XP) ...........................................................................................A–2<br />
APPENDIX B. APPLICATION NOTES ........................................................................................................... B–1<br />
InduSoft Web Studio<br />
v
Chapter 19. <strong>IWS</strong> File/Database Configuration<br />
In this Chapter, we will look at how to configure database connections for Trends, Alarms, Events and the Grid<br />
Object. In subsequent chapters, we will cover the Trending, Alarm, Event and Grid Objects and Worksheets in<br />
further detail.<br />
<strong>IWS</strong> provides automatic database storage and retrieval for Trend data, Alarms, Events, and the Grid Object.<br />
This data can be stored in either the <strong>IWS</strong> proprietary database format (to local files), or to a relational<br />
database (local or remotely located) using the built-in ADO.NET interface. The Grid Object can only be used<br />
with the built-in ADO.NET interface (or with Class Objects or Text files).<br />
Using the <strong>IWS</strong> Proprietary File Format<br />
Trend Data, Alarm Data and Event Data can all be stored (and retrieved) in files on the local computer using the<br />
built-in <strong>IWS</strong> proprietary format. The advantage of the <strong>IWS</strong> proprietary database format is that the data is very<br />
compact and a 3 rd party database is not required.<br />
The following chart explains where the database configuration for each Task is located:<br />
Task<br />
Alarms<br />
Events<br />
Trend<br />
Interface<br />
• From the Main Menu Bar, select Project Settings, and then select the Options<br />
Tab. In the Alarm History and Events section, select the Proprietary option in the<br />
History Format combo box.<br />
• From the Main Menu Bar, select Project Settings, and then select the Options<br />
Tab. In the Alarm History and Events section, select the Proprietary option in the<br />
History Format combo box.<br />
• In a Trend Worksheet, select the Proprietary option in the History Format combo<br />
box.<br />
Notes:<br />
• Both the Alarms and Events must be saved in the same format (i.e. <strong>IWS</strong> Proprietary or to a Relational<br />
Database). If stored to a Relational Database, the Relational Databases can be different<br />
• Each Trend Worksheet can be individually configured to store data in the <strong>IWS</strong> Proprietary format or to<br />
a Relational Database.<br />
InduSoft Web Studio 19–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Contents<br />
Alarm Data files are stored in the \Alarm subfolder in the Application directory by default. The file format is Text<br />
(UNICODE), and <strong>IWS</strong> uses the vertical bar (pipe) character (|) to separate the fields. Alarm files have an .ALH<br />
file extension. The Alarm file name syntax is alYYMMDD.ALH, where<br />
al Alarm file prefix<br />
YY Last 2 digits of the year (e.g. 07 for 2007)<br />
MM Number of the current Month<br />
DD Number of the current Day<br />
There will be one Alarm history file created for each day. You can modify the Alarm History file path with the<br />
SetAlarmPath() function.<br />
Event Data files are also stored in the \Alarm subfolder in the Application directory. The file format is Text<br />
(UNICODE), and <strong>IWS</strong> uses the vertical bar (pipe) character (|) to separate the fields. Event files have an .EVT<br />
file extension. The Event file name syntax is evYYMMDD, where:<br />
ev Event file prefix<br />
YY Last 2 digits of the year (e.g. 07 for 2007)<br />
MM Number of the current Month<br />
DD Number of the current Day<br />
Trend Data files are stored in the \Hst subfolder in the<br />
Application directory. The file format is binary. The Trend file<br />
name syntax is WSYYMMDD, where:<br />
WS Trend Worksheet number in hexadecimal format<br />
(e.g. 01 for Trend001 Worksheet)<br />
YY Last 2 digits of the year (e.g. 07 for 2007)<br />
MM Number of the current Month<br />
DD Number of the current Day<br />
Alarm and Event data will be remain in the local computer’s file<br />
system for a predetermined period of time, according to the<br />
Historical Life Time settings. For Alarm and Event data, this<br />
parameter is set in the History Life Time field in the Alarm<br />
History and Events area of the dialog box accessed by<br />
Project Settings Option Tab. If the parameter is set<br />
to a value of 0, the historical data files are kept indefinitely. A<br />
positive value greater than 0 will determine the number of<br />
days the historical data files for Alarm and Event data is<br />
kept.<br />
The life of historical Trend data files is specified in the<br />
Advanced dialog box, accessed from the Trend Worksheet.<br />
In the History Life Time, a value in days is entered in the<br />
History Life Time field. If the value is greater than 0, this is<br />
the number of days that the Trend data is kept. If the value of<br />
this parameter is 0, the Trend data is kept indefinitely.<br />
An <strong>IWS</strong> built-in Function (HST2TXT) is available to convert<br />
binary historical Trend files into text files. While there is no<br />
corresponding function for the Alarm and Event historical<br />
data, this information can be displayed in an Alarm/Event<br />
Control Object, and can also be printed. Alarm and Event<br />
data files are text (Unicode) and can be opened by Notepad<br />
or other Microsoft and 3 rd party applications. The vertical bar<br />
character (|) separates the fields.<br />
19–2 InduSoft Web Studio
Contents<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
<strong>IWS</strong> Proprietary File and Database Format for Alarm History<br />
When you enable the alarm history file for a group, <strong>IWS</strong> saves the alarm events to a history database,<br />
according to the File Format configured for the Alarm History. Each Alarm Event is saved on a new line in the<br />
Alarm History file, separated by the vertical bar (pipe) character. The format of the Alarm History data saved in<br />
the history file or to a SQL relational database is described in the following table.<br />
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<br />
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<br />
..<br />
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<br />
Field<br />
Number<br />
Field Name Data Type Remarks<br />
P1 Version Number<br />
P2<br />
P3<br />
Al_Start_Time<br />
DateTime<br />
This field is created only when the File Format is<br />
Proprietary. Current version: 003<br />
Timestamp indicating when the alarm started.<br />
When the File Format is Proprietary, <strong>IWS</strong> saves the<br />
Date (MM/DD/YYYY) in one field and the Time<br />
(HH:MM:SS.MSS) in the next field.<br />
P4 Al_Tag String Tag Name that caused the Alarm<br />
P5 Al_Message String Alarm message<br />
P6 Al_Ack Number<br />
P7 Al_Active Number<br />
0: Indicates the alarm was acknowledged or does not<br />
require acknowledgment<br />
1: Indicates the alarm was not acknowledged<br />
0: Indicates the alarm is not active<br />
1: Indicates the alarm is active<br />
P8 Al_Tag_Value Number Tag value when the alarm event occurred<br />
P9 Al_Prev_Tag_Value Number<br />
P10 Al_Group Number Alarm Group Number<br />
P11 Al_Priority Number Alarm Priority Number<br />
P12 Al_Selection String Alarm Selection value<br />
P13 Al_Type Number<br />
P14 Al_Ack_Req Number<br />
P15<br />
P16<br />
Al_Norm_Time<br />
DateTime<br />
Tag value that occurred before the alarm event. This<br />
field only exists for Version >=3<br />
1: HiHi<br />
2: Hi(On)<br />
4: Lo(Off)<br />
8: LoLo<br />
16: Rate(Change)<br />
32: Deviation+<br />
64: Deviation-<br />
0: Requires acknowledgement (Ack)<br />
1: Does not require acknowledgement<br />
Timestamp indicating when the alarm was normalized.<br />
When the File Format is Proprietary, <strong>IWS</strong> saves the<br />
Date (MM/DD/YYYY) in one field and the Time<br />
(HH:MM:SS.MSS) in the next field.<br />
InduSoft Web Studio 19–3
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Contents<br />
Field<br />
Number<br />
P17<br />
P18<br />
Field Name Data Type Remarks<br />
Al_Ack_Time<br />
DateTime<br />
P19 Al_User String<br />
P20 Al_Comment String<br />
P21 Al_User_Full String<br />
P22 Al_Station String<br />
P23 Al_Deleted Number<br />
P24<br />
P25<br />
Last_Update<br />
DateTime<br />
P26 Bias Number<br />
Timestamp indicating when the alarm was<br />
acknowledged.<br />
When the File Format is Proprietary, <strong>IWS</strong> saves the<br />
Date (MM/DD/YYYY) in one field and the Time<br />
(HH:MM:SS.MSS) in the next field.<br />
User logged when the alarm event occurred. This field<br />
only exists for Version >=1<br />
Comment (optional) typed by the operator when the<br />
alarm was acknowledged. This field only exists for<br />
Version >=1<br />
Full name of the user logged when the alarm event<br />
occurred. This field only exists for Version >=2<br />
Name of the station (computer) where the alarm event<br />
occurred. This field only exists for Version >=2<br />
0: Alarm message was not deleted<br />
1: Alarm message was deleted<br />
This field is created only when the File Format is<br />
Database.<br />
Time Stamp when the register was created/modified.<br />
This field is used to synchronize the databases when<br />
using the Secondary Database in addition to the<br />
Primary Database. This field is created only when the<br />
File Format is Database.<br />
Difference (in minutes) from the Time Stamp columns<br />
and the GMT time. This field only exists for Version<br />
>=3<br />
Note:<br />
• When saving the History Alarms in a SQL Relational Database (File Format = Database), you can<br />
customize the name of the columns created in the database by editing the .APP file,<br />
as follows:<br />
[Alarm]<br />
=<br />
For example:<br />
[Alarm]<br />
Message=Alarm_Message<br />
Ack=Acknowledgment<br />
19–4 InduSoft Web Studio
Contents<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
<strong>IWS</strong> Proprietary File And Database Format For Event History<br />
Event log files are saved to a history database in the \Alarm subfolder by default. The information is saved<br />
according to the File Format configured for the Event History. Each Event log is saved on a new line in the<br />
Event History file, separated by the vertical bar (pipe) character. The format of the Event History data saved in<br />
the history file or to a SQL relational database is described in the following table.<br />
P1 | P2 | P3 | P4 | P5 | P6 | P7 | P8 | P9 | P10 | P11 | P12 | P13 | P14 | P15 | P16 | P17<br />
P1 | P2 | P3 | P4 | P5 | P6 | P7 | P8 | P9 | P10 | P11 | P12 | P13 | P14 | P15 | P16 | P17<br />
..<br />
P1 | P2 | P3 | P4 | P5 | P6 | P7 | P8 | P9 | P10 | P11 | P12 | P13 | P14 | P15 | P16 | P17<br />
Field Number Field Name Data Type Remarks<br />
P1 Version Number<br />
P2 Ev_Type Number<br />
P3<br />
P4<br />
Ev_Time<br />
DateTime<br />
This field is created only when the File Format is<br />
Proprietary. Current version: 002<br />
1: SECURITY SYSTEM<br />
2: DISPLAY<br />
3: RECIPE<br />
4: REPORT<br />
5: CUSTOM MESSAGES<br />
6: SYSTEM WARNING<br />
7: LOG TAGS<br />
P5 Ev_Info String Tag Name<br />
Timestamp indicating when the event occurred.<br />
When the File Format is Proprietary, <strong>IWS</strong> saves the<br />
Event Time in the following format: MM/DD/YYYY<br />
HH:MM:SS.MSS.<br />
P6 Ev_User String User logged when the event occurred.<br />
P7 Ev_User_Full String Full name of the user logged when the event occurred.<br />
P8 Ev_Message String Event message<br />
P9 Ev_Value Number Tag value when the event occurred<br />
P10 Ev_Prev_Value Number<br />
P11 Ev_Station String<br />
P12 Ev_Comment String<br />
Tag value that occurred before the event. This field<br />
only exists for Version >=2<br />
Name of the station (computer) where the event<br />
occurred.<br />
Comment (optional) typed by the operator when the<br />
event occurred. This field only exists for Version >=2<br />
P13 Event_Source String Name of the task that generated the event<br />
P14 Ev_Deleted Number<br />
0: Event message was not deleted<br />
1: Event message was deleted<br />
This field is created only when the File Format is<br />
Database.<br />
InduSoft Web Studio 19–5
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Contents<br />
Field Number Field Name Data Type Remarks<br />
P15<br />
P16<br />
Ev_Last_Update DateTime<br />
P17 Bias Number<br />
Time Stamp when the register was created/modified.<br />
This field is used to synchronize the databases when<br />
using the Secondary Database in addition to the<br />
Primary Database. This field is created only when the<br />
File Format is Database.<br />
Difference (in minutes) from the Time Stamp columns<br />
and the GMT time. This field only exists for Version<br />
>=2<br />
Note:<br />
• When saving the History Events in a SQL Relational Database (File Format = Database), you can<br />
customize the name of the columns created in the database by editing the .APP<br />
file, as follows:<br />
[EventLogger]<br />
=<br />
For example:<br />
[EventLogger]<br />
Event_Info=Information<br />
Message=Event_Message<br />
19–6 InduSoft Web Studio
Contents<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
<strong>IWS</strong> Proprietary File and Database Format for Trend History<br />
Trend Data files are saved to the \Hst subfolder to a binary file (<strong>IWS</strong> proprietary format), or to a SQL relational<br />
database. The fields saved in the History Trend file or SQL Relational database are described in the following<br />
table:<br />
Field Name Data Type Remarks<br />
TimeStamp<br />
<br />
Bias<br />
DateTime<br />
Number<br />
(Integer or Real format<br />
depending on the tag type)<br />
Number<br />
TimeStamp (Date and Time) when the data was<br />
saved.<br />
<strong>IWS</strong> will create one field (column) in the database<br />
for each tag configured in the Trend worksheet.<br />
Difference (in minutes) from the Time Stamp<br />
columns and the GMT time. This field only exists<br />
for Version >=2<br />
InduSoft Web Studio 19–7
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Contents<br />
Using the built-in ADO.NET Interface<br />
<strong>IWS</strong> provides a built-in ADO.NET interface for the Alarm, Event and Trend Tasks and the Grid Object, allowing<br />
simple configuration and use. ADO.NET is Microsoft’s ActiveX for Data Objects that operates under the<br />
Microsoft .NET framework. The diagram below shows how this works in an <strong>IWS</strong> environment.<br />
Built-in ADO.NET to Relational Databases<br />
The components are as follows:<br />
• <strong>IWS</strong> Application<br />
An <strong>IWS</strong> application uses the ADO.NET interface to execute SQL (Structured Query Language)<br />
commands to manipulate data in a relational database. Available ADO.NET commands include<br />
commands to connect to a particular Database, as well as to store and retrieve records. The Alarm,<br />
Event and Trend Tasks and the Grid Object all have a built-in ADO.NET interface to store and retrieve<br />
data from a relational database.<br />
• ADO.NET Providers<br />
The ADO.NET Provider (also known as a Data Provider) connects the client application via the<br />
ADO.NET API (applications programming interface) to the database. The ADO.NET providers can<br />
connect directly to certain databases (e.g. SQL Server, Oracle, MySQL), or through OLE-DB Providers<br />
or ODBC Providers. Data Providers include functions such as a SQL Query processor, a cursor engine<br />
(points to records in the database) and an interface to one or more databases<br />
• Database<br />
This is generally a relational database, although CSV files can be supported through the Microsoft JET<br />
OLE-DB Provider<br />
One of the first considerations when using a 3 rd party database to store Alarm, Event, Trend or other data is the<br />
particular Relational Database to be used. There are usual tradeoffs between cost and performance, as well as<br />
corporate standards that may need to be adhered to.<br />
19–8 InduSoft Web Studio
Contents<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Another consideration is the ADO.NET Provider to use. Several ADO.NET Providers are included with the<br />
Microsoft Operating System (e.g. Windows XP, 2000, Server 2003, or Vista) or the ADO.NET Provider may<br />
come from a 3 rd party. Some ADO.NET Providers provide connect directly to the database (usually for higher<br />
performance), while others connect to the Microsoft JET OLE-DB Provider or to ODBC. The following contains<br />
a partial list of ADO.NET Data Providers:<br />
ADO.NET Provider Database Supported Source<br />
.NET for SQL Server*<br />
Microsoft SQL Server<br />
Microsoft<br />
(Version 7 or later)<br />
.NET for Oracle<br />
Oracle<br />
Microsoft<br />
(Oracle Client 8.1.7 or later)<br />
.NET for OLE-DB (SQLOLEDB)* Microsoft SQL Server<br />
Microsoft<br />
(Prior to Version 7)<br />
.NET for OLE-DB (MSDAORA)* Oracle<br />
Microsoft<br />
(Oracle Client prior to 8.1.7)<br />
.NET for OLE-DB (Jet 4.0)* Microsoft Access, Excel, CSV Microsoft<br />
.NET for ODBC with SQL Server Microsoft SQL Server<br />
Microsoft<br />
Driver<br />
.NET for ODBC with Oracle Driver Oracle Microsoft<br />
.NET for ODBC with Access Driver Microsoft Access<br />
Microsoft<br />
Download Connector/Net 1.0 MySQL (.NET 1.1) www.mysql.com<br />
Download Connector/Net 5.0 MySQL (.NET 2.0) www.mysql.com<br />
* Required MDAC 2.6 or later<br />
Notes:<br />
• Use the .NET Framework Data Provider for SQL Server if using SQL Server version 7.0 or later<br />
• Use the .NET Framework Data Provider for OLE-DB when using SQL Server 6.5 or earlier, or a singletiered<br />
Microsoft Access database. Using Access for middle-tiered applications is not recommended.<br />
• Use the .NET Framework Data Provider for ODBC for single-tiered and middle-tiered applications that<br />
use ODBC data sources. Note that the ODBC Data Provider was not provided with .NET Framework<br />
version 1.0, but can be downloaded from the Microsoft website at<br />
http://msdn.microsoft.com/downloads.<br />
• Use the .NET Framework Data Provider for Oracle with single-tier and middle-tier applications using<br />
Oracle client software 8.1.17 and later.<br />
• Using a Microsoft Access database (with the Jet engine) as a data source for multi-threaded<br />
applications is not recommended. Microsoft recommends using SQL Server instead.<br />
• If you use Microsoft Excel as a database, you may want to periodically compact the database.<br />
• Microsoft recommends using the direct .NET Providers for SQL Server and Oracle when possible<br />
(based on the version of SQL Server or Oracle being used). These direct .NET Providers have a direct<br />
interface into the respective database and have been optimized for performance. These .NET<br />
Providers do not use OLE-DB or ODBC. This was done to improve transactional efficiency required by<br />
high-demand database server applications<br />
• In addition to Data Providers, Service Providers may be available from Database suppliers. Examples<br />
of Service Providers include:<br />
- Persistence Provider: allows saving of rowset data and metadata to a local file<br />
- Remoting Provider: allows access to remote databases<br />
• Microsoft has announced that they will be “deprecating” (obsoleting) certain legacy database<br />
interfaces, although they are still supported in the current MDAC release (MDAC 2.8). Microsoft wants<br />
you to use ADO.NET instead. The deprecated interfaces include:<br />
- ODBC Provider (MSDASQL)<br />
- Remote Data Services (RDS) Use SOAP instead<br />
- JET DAO (Data Access Objects) and Jet Replication Objects (JRO)<br />
InduSoft Web Studio 19–9
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Contents<br />
<strong>IWS</strong> can interface to virtually any Relational Database supported by a valid ADO.NET Provider, OLE DB<br />
Provider or ODBC Driver. Conformance tests were performed by InduSoft on the following databases:<br />
Database<br />
Microsoft SQL Server<br />
Microsoft Access<br />
Microsoft Excel<br />
MySQL<br />
Oracle<br />
Sybase<br />
Provider<br />
ADO.NET Provider for SQL Server<br />
ADO.NET Provider for OLE DB<br />
ADO.NET Provider for OLE DB<br />
ADO.NET Provider for OLE DB<br />
ADO.NET Provider for Oracle<br />
ADO.NET Provider for Sybase<br />
Conformance Test Table<br />
Notes:<br />
• A primary goal of ADO.NET is to provide a consistent interface between the application and a<br />
database, regardless of the database used. However, there will always be some database<br />
dependencies, such as supported data types and commands.<br />
• You will need to acquire the ADO.NET Provider (and possibly OLE-DB Provider or ODBC Provider)<br />
from either Microsoft, the Database supplier, or a 3 rd party.<br />
Relational Database are sets of information stored in tables with fields (columns) and registers (rows), and<br />
inherently support SQL commands to manipulate the data. A database typically has more than one table. Each<br />
table has its own fields (columns) and registers (rows). Typically, the fields are pre-defined and the application<br />
adds or reads one or more rows, according to the SQL query command.<br />
With the built-in ADO.NET interface provided by <strong>IWS</strong>, the Relational Database can be on the local computer or<br />
on a remote computer. This capability allows connection between an <strong>IWS</strong> application and an enterprise-level<br />
database.<br />
Although most applications typically link to only one type of database, <strong>IWS</strong> gives you the flexibility to link each<br />
task to a specific database supported by a Database Provider. Furthermore, by using this architecture, you do<br />
not need to worry about the specific characteristics of each database (it is mostly handled by the Database<br />
Provider for each database or by the Studio database gateway interface). Therefore, the application settings<br />
are mostly uniform, regardless of the specific database chosen by you, the end-user. For example, Alarms and<br />
19–10 InduSoft Web Studio
Contents<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Events could be logged to a remote database, while the Trend data can be stored locally in files using the <strong>IWS</strong><br />
proprietary format.<br />
The following chart explains where the database configuration for each Task is located:<br />
Item<br />
<br />
Alarms Task<br />
Events Task<br />
Trend Task<br />
Grid Object<br />
Interface<br />
You can specify a default database that will be used unless otherwise specified.<br />
To specify the default database:<br />
• From the Main Menu Bar, select Project Settings, and then select the<br />
Options Tab. Click on the Configure button in the Default Database<br />
section.<br />
• From the Main Menu Bar, select Project Settings, and then select the<br />
Options Tab. In the Alarm History and Events section, select the Database<br />
option in the History Format combo box. Click on the Alarms Database<br />
button.<br />
• From the Main Menu Bar, select Project Settings, and then select the<br />
Options Tab. In the Alarm History and Events section, select the Database<br />
option in the History Format combo box. Click on the Event Database<br />
button.<br />
• From the Event Settings dialog box in the Database Workspace<br />
• In a Trend Worksheet, select the Database option in the History Format<br />
combo box. Click on the Database Configuration button.<br />
• In the Grid Object dialog box, select the Database option from the Data<br />
Source combo box. Click on the Data button.<br />
When the Database Configuration dialog box initially appears, it will likely be set to use the Primary default<br />
database (as specified in the Default Database settings). If the Default database is used, the Alarm, Events<br />
and Trend Tasks, as well as the Grid Object will have default table names that will be used. The default settings<br />
are:<br />
Item<br />
Alarms<br />
Events<br />
Trend<br />
Grid Object<br />
Default Table Name<br />
AlarmHistory<br />
EventHistory<br />
TRENDGGG<br />
(GGG = Trend Worksheet Number<br />
e.g.: TREND001 for the Trend<br />
Worksheet 001)<br />
Name of the <strong>IWS</strong> application<br />
(without .App extension)<br />
Of course, the default table names can be changed.<br />
InduSoft Web Studio 19–11
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Contents<br />
Configuring the Default Database<br />
To configure the Default Database, we need to access the Default Database Configuration dialog box:<br />
• From the Main Menu Bar, select Project Settings, and then select the Options Tab.<br />
• Click on the Configure button in the Default Database section.<br />
The Default Database Configuration dialog box has the following settings and options:<br />
• Database Combo Box<br />
Allows you to specify settings for the default Primary Database or the default Secondary Database.<br />
Secondary (redundant) databases will be covered in more detail later.<br />
• Connection String field<br />
This field defines the database which <strong>IWS</strong> will write to and read values from. The Connection String can<br />
be entered manually or the Connection String Wizard can be used.<br />
• User Name field<br />
User name used to connect to the database. The user name configured in this field must match the<br />
user name configured in the database.<br />
• Password field<br />
Password used to connect to the database. The password configured in this field must match the<br />
password configured in the database.<br />
• Retry Interval field<br />
If <strong>IWS</strong> is unable to connect to the database for any reason, it retries automatically to connect to the<br />
database after the number of seconds configured in this field have passed.<br />
• Advanced button<br />
Provides access to customize database connection settings.<br />
For most applications, the default values for these settings do<br />
not need to be modified. These settings include:<br />
– Milliseconds combo box: You can configure how the<br />
milliseconds will be saved when saving the date in the<br />
database. Each database saves the date in different<br />
formats; for example, some databases do not support<br />
milliseconds in a Date field. The following options are<br />
available:<br />
• Default: Uses the format pre-defined for the<br />
current database. The databases previously tested by InduSoft are previously configured<br />
with the most suitable option. When selecting Default, <strong>IWS</strong> uses the setting pre-configured<br />
for the current database type. If you are using a database that has not been previously<br />
19–12 InduSoft Web Studio
Contents<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
configured by InduSoft, the Default option attempts to save the milliseconds in a separate<br />
field.<br />
• Disable: Does not save the milliseconds at all when saving the date in the database.<br />
• Enable: Saves the milliseconds in the same field where the date is saved.<br />
• Separate Column: Saves the milliseconds in a separated column. In this case, the date is<br />
saved in one field (without the milliseconds precision) and the number of milliseconds is<br />
saved in a different column. This option is indicated where you want to save timestamps<br />
with the precision of milliseconds but the database that you are using does not support<br />
milliseconds for the Date fields.<br />
Note:<br />
• The default option for each database is configured in the StudioADO.ini file, located in the<br />
\BIN sub-folder where the <strong>IWS</strong> Program is located.<br />
– Save time difference check-box: When this option is checked (default), <strong>IWS</strong> saves the Time<br />
Zone configured in the computer where the application is running in each register of the<br />
database (Bias field). This option must be enabled to avoid problems with daylight savings<br />
time.<br />
– Database Gateway: Specifies the Host Name/IP Address where the Studio database gateway<br />
will be running. The TCP Port number can also be specified, but if you are not using the default,<br />
you will have to configure the Studio database gateway with the same TCP Port. See the<br />
Studio Database Gateway section for information about how to configure the Studio ADO<br />
Gateway.<br />
– Disable Primary Keys checkbox. Will disable <strong>IWS</strong> from using a primary key to speed up<br />
database access. This checkbox should be checked when using a database that does not<br />
support Primary Keys (e.g. Excel).<br />
Note:<br />
• The fields Table, Connection String, User Name, Password and Host name can have tags<br />
between curly brackets if you want to use dynamic values.<br />
• When using Microsoft Excel, you need to check the Disable Primary Keys checkbox<br />
The primary parameter that needs to be configured is the Connection String, which is different for every<br />
database. In the Default Database Configuration dialog box, enter a User Name and Password if required by<br />
the database.<br />
Click on the … button to access the Connection String wizard. This wizard will help you define a Connection<br />
String to your database. You do not need to use the Connection String Wizard, but if you do not know the<br />
Connection String, this can be a very useful tool.<br />
After pressing the … button, a Data Link Properties dialog box will appear. This dialog box has four tabs:<br />
• Provider<br />
Defines the Database Provider that can be used. The list of Database Providers depends on the<br />
Providers actually installed and available in the computer where you are running <strong>IWS</strong>. Consult Microsoft<br />
OS documentation or Database documentation for further information on the Provider settings for the<br />
database you are using.<br />
InduSoft Web Studio 19–13
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Contents<br />
• Connection<br />
Specifies the source of the data and any log on specific information. This dialog box changes based on<br />
the Provider used. A Test Connection button is usually available to test the connection to the database<br />
• Advanced<br />
Specifies Network Settings and Access Permissions<br />
• All<br />
Allows you to specify values for any Properties used. This dialog box will depend on the Provider used.<br />
The following are some typical settings to connect to a database:<br />
Microsoft Access<br />
Provider Microsoft Jet 4.0 OLE DB Provider<br />
Connection<br />
Advanced<br />
All<br />
Click on the … button to specify the Database (*.MDB).<br />
Specify any User Name and Password required.<br />
Nothing needs to be changed<br />
Nothing needs to be changed<br />
Microsoft Excel<br />
Provider Microsoft Jet 4.0 OLE DB Provider<br />
Connection<br />
Advanced<br />
All<br />
Click on the … button to specify the Database (*.MDB).<br />
Specify any User Name and Password required.<br />
Nothing needs to be changed<br />
Set the Extended Properties value to Excel 8.0, by selecting Extended Properties, then click<br />
the Edit Value… button. In the Property Value field, type Excel 8.0. If a header is used in the<br />
Excel file, then type Excel 8.0; Hdr=Yes in the Property Value field.<br />
Microsoft SQL Server<br />
Provider Microsoft OLE-DB Provider for SQL Server<br />
Connection<br />
Advanced<br />
All<br />
Click on the … button to specify the Database Server and the Database (Catalog).<br />
Specify any User Name and Password required.<br />
Nothing needs to be changed<br />
Nothing needs to be changed<br />
Oracle 8i/9i/10g<br />
Provider Oracle OLE-DB Provider for Oracle 8i, 9i or 10g<br />
Connection<br />
Advanced<br />
All<br />
Click on the … button to specify the Database Server and the Database (Catalog).<br />
Specify any User Name and Password required.<br />
Nothing needs to be changed<br />
Nothing needs to be changed<br />
19–14 InduSoft Web Studio
Contents<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Configuring a Task or Object Database<br />
You can specify a database for an Alarm, Event or Trend Task, or a Grid Object, that is different from the<br />
Application Default Database. The Database Configuration dialog box for each of these Tasks or Object can be<br />
accessed in the following manner:<br />
Item<br />
Alarms Task<br />
Events Task<br />
Trend Task<br />
Grid Object<br />
Interface<br />
• From the Main Menu Bar, select Project Settings, and then select the Options<br />
Tab. In the Alarm History and Events section, select the Database option in the<br />
History Format combo box. Click on the Alarms Database button.<br />
• From the Main Menu Bar, select Project Settings, and then select the Options<br />
Tab. In the Alarm History and Events section, select the Database option in the<br />
History Format combo box. Click on the Event Database button.<br />
• From the Event Settings dialog box in the Database Workspace<br />
• In a Trend Worksheet, select the Database option in the History Format combo<br />
box. Click on the Database Configuration button.<br />
• In the Grid Object dialog box, select the Database option from the Data Source<br />
combo box. Click on the Data button.<br />
Each of these items has a similar Database Configuration dialog box. To use a different database than the<br />
Application Default Database, do the following:<br />
• Uncheck the Use application default check box.<br />
• Configure the Connection String as was done for the<br />
Application Default Database, but specifying the new<br />
database you want to use for this item.<br />
• If you want to use a Table different from the default table<br />
name, uncheck the Use default name in the Table<br />
section of the dialog box. Specify the Table Name in the<br />
Name field.<br />
• If you want <strong>IWS</strong> to automatically create the Table<br />
specified in the Name field if it does not exist, leave the<br />
Automatically create check box checked.<br />
• The Table Name field is a combo box that can look into<br />
the Database to determine any existing tables. Click on<br />
the Refresh button and then click the down arrow on the<br />
Name combo box to see any existing Tables is the<br />
Database.<br />
• The Runtime section has Status and Reload fields that<br />
can have tag names. Status is an output defining the<br />
Status of the Database connection, and Reload is a trigger to reload values from the Database (e.g.<br />
can be used when a tag is used in the Connection String or User Name field and the tag(s) change<br />
value).<br />
Notes:<br />
• Both the Alarms and Events must be saved in the same format (i.e. <strong>IWS</strong> Proprietary or to a<br />
Relational Database). If stored to a Relational Database, the Relational Databases can be<br />
different<br />
• Each Trend Worksheet can be individually configured to store data in the <strong>IWS</strong> Proprietary<br />
format or to a Relational Database.<br />
InduSoft Web Studio 19–15
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Contents<br />
Primary and Secondary Databases<br />
<strong>IWS</strong> supports redundant systems. When configuring the database interface, you can configure the Primary<br />
Database and, optionally, a Secondary Database. The Secondary Database can be configured in the following<br />
modes:<br />
<br />
<br />
<br />
Disabled: In this mode, <strong>IWS</strong> saves data in the<br />
Primary Database only. If the Primary Database<br />
is unavailable for any reason, the data is not<br />
saved anywhere else. This option may cause<br />
loss of data if the Primary Database is not<br />
available.<br />
Redundant: In this mode, <strong>IWS</strong> saves data in<br />
both Primary and Secondary Databases. If one<br />
of these databases is unavailable, <strong>IWS</strong> keeps<br />
saving data only in the database that is<br />
available. When the database that was<br />
unavailable becomes available again, <strong>IWS</strong><br />
synchronizes both databases automatically.<br />
Store and Forward: In this mode, <strong>IWS</strong> saves<br />
data in the Primary Database only. If the<br />
Primary Database becomes unavailable, <strong>IWS</strong><br />
saves the data in the Secondary Database.<br />
When the Primary Database becomes available<br />
again, <strong>IWS</strong> moves the data from the Secondary<br />
Database into the Primary Database.<br />
Other than enabling the Secondary Database and specifying the mode, configuration of the Secondary<br />
Database is similar to the configuration of the Primary Database.<br />
By using a Secondary Database, you can increase the reliability of the system by using the Secondary<br />
Database as a backup when the Primary Database is not available. This architecture is particularly useful when<br />
the Primary Database is located in the remote station. In this case, you can configure a Secondary Database in<br />
the local station to save data temporarily if the Primary Database is not available (e.g. during a network failure).<br />
Notes:<br />
• The Primary and Secondary can be different types of databases. However, they must have the<br />
same fields.<br />
• Secondary database support is only available for Relational Databases, not with the <strong>IWS</strong><br />
Proprietary databases.<br />
19–16 InduSoft Web Studio
Contents<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Linking to a remote DB Provider with Studio Database Gateway<br />
Depending on the architecture of your project, the ADO.NET Provider for the SQL Relational Database may not<br />
be available in the same stations where <strong>IWS</strong> is running. This scenario is especially common when the<br />
application is run on the Windows CE operating system (currently, most Providers don not support the Windows<br />
CE operating system). In order to solve this problem, InduSoft designed a flexible solution that allows you to<br />
configure distributed systems, as illustrated in the picture below:<br />
The application is running in the Studio Application station where <strong>IWS</strong> (or CEView) is installed. The application<br />
can communicate with the Studio database gateway (running in a remote computer) via TCP/IP. The Gateway<br />
implements the interface with the Database through the Database Provider available in the computer where it is<br />
running.<br />
The Studio database gateway does not require complex configuration. Just copy the files STADOSvr.exe and<br />
StudioADO.ini from the \BIN sub-folder of <strong>IWS</strong> and paste them under any directory of the computer that will be<br />
used as the Gateway station and execute the STADOSvr.exe program. There are advanced settings associated<br />
with the Studio Database Gateway, but they should be changed only under special circumstances. See the<br />
topic “Studio Database Gateway” for information on how to configure the Studio Database Gateway advanced<br />
settings.<br />
Notes:<br />
• The Studio database gateway is a TCP/IP Server for the <strong>IWS</strong> application and it uses the TCP Port<br />
3997 by default. You can specify a different port number when executing the STADOSvr.exe<br />
program according to the following syntax: STADOSvr.exe . Example: STADOSvr<br />
3998<br />
• Be sure the TCP/IP Server is enabled during runtime (Project Status Execution Tasks. Be<br />
sure the TCP/IP Server is set to run automatically.<br />
InduSoft Web Studio 19–17
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Contents<br />
Studio Database Gateway<br />
The Studio Database Gateway is a TCP/IP server that interacts with databases using the Microsoft .NET<br />
Framework 1.1 or later. It can run on the same computer that is running the <strong>IWS</strong> application, or on a different<br />
computer. The Database Gateway Host in the Advanced Settings (see Database Configuration dialog) specifies<br />
whether the gateway will be running on the local computer or not. If you are using the local computer you<br />
should enter either localhost or 127.0.0.1 in the Host name. You do not need to worry about starting or<br />
stopping the gateway because it will be done automatically by <strong>IWS</strong> tasks. On the other hand, when running the<br />
gateway remotely, you need to start the gateway manually. To do so, copy the files StADOSvr.exe and<br />
StudioADO.ini from the <strong>IWS</strong> BIN folder to the remote computer, then execute the StADOSvr.exe.<br />
The gateway can be started multiple times for different TCP/IP port numbers. The default port number is 3997,<br />
and it is changed by specifying the desired port number in the command prompt (e.g. StADOSvr 1111). When<br />
running the StADOSvr, it will add the following icon to the tray bar:<br />
By right clicking on the tray bar icon, the following options will display:<br />
The hide option defines whether the debug window will be displayed or not. If you de-select it, the following<br />
window will display:<br />
Any failure that occurs during operations with databases will be displayed both in this window and also in the<br />
<strong>IWS</strong> LogWin window (be sure Database Messages are enabled). The messages are reported by exceptions<br />
generated by the ADO.NET Provider. (For troubleshooting answers, please consult the ADO.NET provider<br />
documentation.)<br />
19–18 InduSoft Web Studio
Contents<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
The Studio Database Gateway has Advanced Settings that are configured in the StudioADO.ini file. If you are<br />
having problems interfacing with a specific database, you will probably need to change some of these settings<br />
or add new providers to the file. The following parameters are available:<br />
Parameter Range of Values Description<br />
SaveMSec<br />
Assembly<br />
ConnectionClass<br />
AdapterClass<br />
CommandBuilderClass<br />
Provider<br />
ColumnDelimiterPrefix<br />
ColumnDelimiterSuffix<br />
ValueString<br />
1 - Disable<br />
2 - Enable<br />
3 - Separate Column<br />
Any string that contains a<br />
.Net Framework assembly<br />
Any connection class inside<br />
the assembly<br />
Any data adapter class<br />
inside the assembly<br />
Any command builder class<br />
inside the assembly<br />
Name of the provider<br />
Any character or group of<br />
characters.<br />
Any character or group of<br />
characters.<br />
Any string<br />
ValueAddNumber 0 or 1<br />
BoolType<br />
Any string representing a<br />
valid data type for the<br />
database<br />
This setting specify the default behavior for the<br />
provider when saving milliseconds. The default<br />
can be changed on the Advanced Settings in<br />
the Database Configuration Dialogs.<br />
Assembly option for all providers. The<br />
assembly has all the classes required to<br />
interface with the database. Most of the<br />
providers are inside the System.Data<br />
assembly.<br />
The Connection Class is the one that<br />
implements the System.Data.IDbConnection<br />
interface.<br />
The Data Adapter class is used on operations<br />
where updates to the database are necessary.<br />
It must be compatible with the connection class<br />
specified and it should implement<br />
IDbDataAdapter.<br />
The Command Builder class is also responsible<br />
for updates on databases. It must be<br />
compatible with the connection class.<br />
One of the parameters in the connection string<br />
is the "Provider". The Studio ADO Gateway<br />
compares the value on the connection string<br />
with the value for this parameter in each<br />
provider and define the proper one to be used.<br />
Specify a character that will be placed before<br />
column names on SQL statements<br />
Specify a character that will be placed after<br />
column names on SQL statements<br />
This value indicates how constant values are<br />
identified on SQL statements. For Microsoft<br />
SQL databases for instance, the value should<br />
be @Value, for ODBC question mark ()<br />
Indicates whether a sequential number should<br />
be added to the ValueString to identify the<br />
parameter or not. For Microsoft SQL database<br />
this parameter should have the value 1,<br />
because parameters are identified by using<br />
@Value1, @Value2 …, @ValueN. For ODBC<br />
this parameter should be 0.<br />
When trying to create columns to store boolean<br />
values, the data type specified on this<br />
parameter will be used. You need to make sure<br />
that the data type specified is able to save<br />
boolean values.<br />
InduSoft Web Studio 19–19
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Contents<br />
Parameter Range of Values Description<br />
IntegerType<br />
Real Type<br />
String Type<br />
Any string representing a<br />
valid data type for the<br />
database<br />
Any string representing a<br />
valid data type for the<br />
database<br />
Any string representing a<br />
valid data type for the<br />
database<br />
When trying to create columns to store integer<br />
values, the data type specified on this<br />
parameter will be used. You need to make sure<br />
that the data type specified here is able to store<br />
32 bit values.<br />
When trying to create columns to store real<br />
values, the data type specified on this<br />
parameter will be used. You need to make sure<br />
that the data type specified here is able to store<br />
64 real values.<br />
When trying to create columns to store string<br />
values, the data type specified on this<br />
parameter will be used. You need to make sure<br />
that the data type specified is able to save the<br />
number of characters that you are willing to<br />
save on your application.<br />
A single section called [Providers] has all the parameters inside it. The default values are specified in the<br />
beginning of the file, using the prefix “Default” in each parameter as shown below:<br />
[Providers]<br />
DefaultSaveMSec=3<br />
DefaultAssembly=System.Data<br />
DefaultConnectionClass=System.Data.OleDb.OleDbConnection<br />
DefaultDataAdapterClass=System.Data.OleDb.OleDbDataAdapter<br />
DefaultCommandBuilderClass=System.Data.OleDb.OleDbCommandBuilder<br />
DefaultColumnDelimiterPrefix=[<br />
DefaultColumnDelimiterSuffix=]<br />
DefaultValueString=Value<br />
DefaultValueAddNumeber=1<br />
DefaultTypeBool=INTEGER<br />
DefaultTypeInteger=INTEGER<br />
DefaultTypeReal=REAL<br />
DefaultTypeString=VARCHAR(255)<br />
DefaultTypeTimeStamp=DATETIME<br />
The next item on the file lists the amount of providers:<br />
Count=5<br />
The providers are identified by the “Provider” parameter followed by a number. When connecting to a database,<br />
the Provider parameter in the connection string is compared to the provider’s identification, in order to<br />
determine which provider will be used. If there is no provider with the value on the connection string, all the<br />
default values are assumed. Besides its identification, each provider can have its own value per each<br />
parameter. Again, if no value is specified, the default is used. Below is an example with five providers:<br />
Provider1=MICROSOFT.JET.OLEDB<br />
SaveMSec1=3<br />
Provider2=SQLOLEDB<br />
ConnectionClass2=System.Data.SqlClient.SqlConnection<br />
DataAdapterClass2=System.Data.SqlClient.SqlDataAdapter<br />
CommandBuilderClass2=System.Data.SqlClient.SqlCommandBuilder<br />
19–20 InduSoft Web Studio
Contents<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Provider3=MSDASQL<br />
ConnectionClass3=System.Data.Odbc.OdbcConnection<br />
DataAdapterClass3=System.Data.Odbc.OdbcDataAdapter<br />
CommandBuilderClass3=System.Data.Odbc.OdbcCommandBuilder<br />
Provider4=SQLOLEDB<br />
Assembly4=System.Data.OracleClient.OracleClient<br />
ConnectionClass4=System.Data.OracleClient.OracleConnection<br />
DataAdapterClass4=System.Data.OracleClient.OracleDataAdapter<br />
CommandBuilderClass4=System.Data.OracleClient.OracleCommandBuilder<br />
Provider5=ASAPROV<br />
Assembly5=iAnywhere.Data.AsaClient<br />
ConnectionClass5=iAnywhere.Data.AsaClient.AsaConnection<br />
DataAdapterClass5=iAnywhere.Data.AsaClient.AsaDataAdapter<br />
CommandBuilderClass5=iAnywhere.Data.AsaClient.AsaCommandBuilder<br />
InduSoft Web Studio 19–21
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Contents<br />
Notes<br />
19–22 InduSoft Web Studio
Chapter 20. Using ODBC Database Source Names (DSN)<br />
ODBC, short for Open Database Connectivity, is a standard software API method for using relational database<br />
management systems (RDBMS). The goal of ODBC is to allow SQL (Structured Query Language) queries to<br />
take place on the database independent of the programming language used. An ODBC implementation<br />
consists of three (3) components:<br />
1. The Application (in this case, the <strong>IWS</strong> application)<br />
2. A Core ODBC Library<br />
3. A database Driver<br />
The Core ODBC library is provided by the Operating System (e.g. Windows XP) and interprets commands sent<br />
by the application to the database (through the Driver). The Driver is specific to a database, and only needs to<br />
know how to attach to the Core ODBC library.<br />
Almost every database in existence can be interfaced via ODBC. Microsoft now ships ODBC with every version<br />
of Windows (except Windows CE which does not support ODBC). In order to use this capability, you must use<br />
Microsoft .NET Framework 1.1 or higher.<br />
Note:<br />
• The Microsoft .NET Framework 2.0 is automatically installed with <strong>IWS</strong> v.6.1 Service Pack 3<br />
The connection between the Application and the Database starts by defining a DSN, or Database Source<br />
Name. This is structure to define the connection to the Database, including the protocol, host, port and<br />
database. This connection is defined in detail at the Operating System Services level, not at the Application (or<br />
VBScript) level.<br />
Note:<br />
• A DSN (e.g. System DSN) must be specified by the Operating System<br />
To configure a DSN (e.g. Windows XP Pro), you click on the Start button, select Control Panel, and then<br />
Administrative Tools. Next, click on the Data Sources icon. This opens the ODBC Data Source Administrator<br />
dialog box.<br />
Note that there are three different type of DSN’s:<br />
• System DSN<br />
In general, you should use a System DSN. This type of DSN is not dedicated to a specific user, and is<br />
available to all users on the local computer. The data source is local to the computer.<br />
• File DSN<br />
This type of DSN can be shared among all users who have the same driver(s) installed. The data source<br />
is not user-dedicated and need not be local to the computer.<br />
• User DSN<br />
This type of DSN is only available to the current user and the data source is local to the computer.<br />
InduSoft Web Studio 20–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Contents<br />
To add a new System DSN, select the System DSN tab and click on the Add button. A new dialog box will<br />
appear, allowing you to select the driver for the ODBC DSN you are creating.<br />
20–2 InduSoft Web Studio
Contents<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Once you have selected the driver, click the Finish button. A new dialog box will appear that allows you to<br />
specify the various Database connection parameters (e.g. the Connection parameters for and ODBC DSN to<br />
MySQL 5.0).<br />
The Test button allows you to test the connection to the Database using the Connection parameters specified.<br />
Notes:<br />
• ODBC can be used with all Microsoft Windows Operating Systems except Windows CE<br />
• ODBC allows you to connect to a wide variety of Database Servers.<br />
• ODBC is an older technology, and is slower than an OLE-DB interface to a Database Server. You<br />
should use OLE-DB or a native ADO.NET Provider whenever possible instead of ODC.<br />
• Microsoft Access does not support File DSNs. You must use a System DSN.<br />
InduSoft Web Studio 20–3
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Contents<br />
Using a Database with a DSN<br />
Now that you have created a DSN, there are two ways you can use this DSN in an <strong>IWS</strong> application. The first is<br />
with native <strong>IWS</strong> Objects (Alarm, Trend, Event, and Grid). The second way is with VBScript.<br />
<strong>IWS</strong> Application<br />
TCP/IP<br />
InduSoft Web Studio<br />
Database Gateway<br />
SQL Relational<br />
Database<br />
ADO ODBC<br />
ODBC<br />
Drivers Provider<br />
<strong>IWS</strong> Connection to a SQL Relational Database via ODBC for Alarm, Trend, Event and Grid Objects<br />
Using a DSN with Alarm, Trend, Event and Grid Objects<br />
To use a database with a ODBC DSN connection for the <strong>IWS</strong> native Alarm, Trend, Event and Grid Objects, you<br />
need to configure this via the Default Database Configuration. This is done by selecting Project Settings <br />
Options Default Database Configure button.<br />
When you press this button, it opens up a Database Configuration Dialog that allows you to provide connection<br />
strings that will connect to an ODBC DSN. The connection string can be built automatically by clicking on the<br />
Browse button (…).<br />
When the Data Link Window displays, you should select the option Microsoft OLE DB Provider for ODBC<br />
Drivers as shown below:<br />
20–4 InduSoft Web Studio
Contents<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
By clicking the Next button the following window will display:<br />
Select the DSN (Data Source Name) that you want to connect, any User Name and Password, as well as the<br />
initial Catalog to connect to, and then click OK. If you want to specify the user name and password in the<br />
InduSoft Web Studio 20–5
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Contents<br />
Database Configuration dialog instead of being prompted, remember to check the Allow saving password<br />
checkbox.<br />
You can click on the Test Connection button to verify a valid connection to the database.<br />
Using a DSN with VBScript<br />
To connect to a DSN with ADO in VBScript, the following illustrates a typical connection string:<br />
Dim oConn<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
oConn.Open (“DSN=myDB;”)<br />
There are additional connection string parameters that can be specified, see the Chapter Accessing<br />
Databases with VBScript.<br />
20–6 InduSoft Web Studio
Contents<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Notes<br />
InduSoft Web Studio 20–7
Chapter 21.<br />
Alarms<br />
Alarming is a key component of any HMI/SCADA system. WS supports On-line Alarms as well as Historical<br />
storage and retrieval of Alarms. The Alarm Worksheet, found in the Alarms folder in Tasks tab of the<br />
Workspace, configures which Tags are used for alarming, and the values that will trigger an Alarm. The<br />
Alarm/Event Control Object is used to display Alarms (historical and on-line) as well as Events.<br />
The types of Alarms are:<br />
– HiHi<br />
Alarm limit when Tag value is too high; generates an alarm message when the tag value is equal to or<br />
greater than the HiHi Limit value.<br />
– Hi<br />
Alarm limit when Tag value is high; generates an alarm when the tag value is equal to or greater than<br />
the Hi Limit value.<br />
– Lo<br />
Alarm limit is when Tag value is low; generates an alarm when the tag value is lower than or equal to<br />
the Lo Limit value.<br />
– LoLo<br />
Alarm limit is too low; generates an alarm when the tag value is lower than or equal to the LoLo Limit<br />
value.<br />
– Rate<br />
Determines the speed of the variation rate for a tag. If the variation speed is higher than the established<br />
one in this field, generate an alarm. The speed can be determined per second, minute, or hour.<br />
– Deviation+<br />
Deviation for a higher value; generate an alarm when an augmentation in the tag value is equal to or<br />
higher than the established limit.<br />
– Deviation–<br />
Deviation for a lower value; generate an alarm when a diminution in the tag value is equal to or higher<br />
than the established limit.<br />
Using the Tag Properties dialog box, you can set a Deadband Value around the HiHi, HI, Lo and LoLo Alarm<br />
limits. You can also specify a Deviation Setpoint, with Deviation+, Deviation- and Deviation Deadband<br />
limits.<br />
Deadband Value & Time<br />
HiHi<br />
Rate<br />
Deviation+<br />
Deviation-<br />
Hi<br />
Deviation<br />
Setpoint<br />
Lo<br />
LoLo<br />
When the Tag crosses an Alarm Threshold, it is called Activated. When the Tag value leaves the Alarm state,<br />
it is called Normalized. When the User acknowledges the Alarm, it is called Acknowledged.<br />
InduSoft Web Studio 21–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Alarm Worksheets<br />
Alarm Worksheets<br />
You first need to specify the Tags used for Alarms in an Alarm Worksheet, entered in the Alarms folder in the<br />
Tasks tab of the Workspace. The Alarm Group Number is 1-999 and is specified in the number in the Alarm<br />
Worksheet, e.g. ALARMxxx.ALR where xxx=Alarm Group Number. The Alarm Group Number is used for<br />
runtime filtering of Alarms by Group Number.<br />
Alarms can be On-line only or On-line & Historical (i.e. Alarms will be saved to a disk database such as the WS<br />
Proprietary Database or a Relational Database). The Alarm/Event Control Object is used to display either Online<br />
Alarms or Historical Alarms.<br />
Once an Alarm is Activated, it will be shown in the On-line Alarm/Event Control Object in the color specified in<br />
the Alarm Worksheet (default is Red). At this point, the Alarm can either be Acknowledged (in which case it will<br />
now be displayed in the Acknowledgment color – default is Green) or it can remain in the Activated state until it<br />
returns to a Normalized value (in which case it will be displayed in the Normalization color – default is light<br />
Blue). Once an On-line Alarm has been Acknowledged and Normalized, it will be removed from the On-Line<br />
Alarm Display. Historical Alarms, however, will retain every Alarm state for the Tag.<br />
In addition to the settings in the Alarm Worksheet, you can specify additional Tag Properties for<br />
alarming. Tag Properties are accessed by selecting the Tag (e.g. from the Tag Datasheet View) and<br />
clicking on the Tag Properties dialog Box.<br />
The Tag Properties dialog box is where the Deadband Value is set, as well as the Deviation Setpoint and the<br />
Deviation Deadband. This is the only dialog box where these Properties are set. All other Alarm Properties (e.g.<br />
Limits) can be specified in the Alarm Worksheet.<br />
A Deadband value around an Alarm limit is very useful when the Alarm is used for analog values (e.g. from a<br />
sensor) that are susceptible to some level of noise or digitization variance. Having a Deadband Value<br />
eliminates multiple Alarms triggering.<br />
For example. if a Tag has a Hi Alarm limit of 80 and a Deadband Value of 5, WS will generate an Alarm when<br />
the Tag value is >= 80. The Alarm is Normalized when the Tag value returns to a value < 75. If the Lo Alarm is<br />
set to 20, the Alarm will Activate when the Tag value is 25.<br />
21–2 InduSoft Web Studio
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Tag Properties – Alarm Properties<br />
In addition to the Hi, HiHi, Lo, LoLo and Rate Alarms, the Deviation+ and Deviation- Alarms are supported.<br />
These Alarms work around a Deviation Setpoint, defined by a Tag inserted in the Deviation Setpoint field as<br />
shown above. A Deviation Deadband can also be defined. Using the settings as shown above, with the Tag v5<br />
set to a value of 50, the following results will occur-<br />
Deviation+ Alarm occurs when Tag v4 value >= 61<br />
Deviation+ Alarm Normalizes when Tag v4 value
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Alarm Worksheet<br />
Advanced Settings Dialog Box<br />
The Activation field, which contains either a value or an WS tag, specifies, in seconds, the amount of time<br />
each alarm in the Alarm Group must remain continuously in its alarm condition before becoming active. This<br />
option is useful to avoid generating alarms on intermittent conditions (e.g.: noise). If this field is left in blank, the<br />
alarm becomes active as soon as its condition is true.<br />
The Normalization field, which contains either a value or an WS tag, specifies, in seconds, the amount of time<br />
each alarm in the Alarm Group must remain continuously out from its alarm condition before becoming<br />
normalized. This option is useful to avoid normalizing alarms on intermittent conditions (e.g.: noise). If this field<br />
is left in blank, the alarm becomes normalized as soon as its condition is no longer true.<br />
The Time Stamp/Value field is a combo-box that lets you select the type of time stamp to be maintained by the<br />
Tag for the last significant Alarm activity, along with the value of the Tag at that time. You can select the type of<br />
activity that updates the time stamp:<br />
• Activation/Norm (default): The time when the dead band ended — that is, when the alarm becomes<br />
activated or normalized.<br />
• Last Tag Change: The time when the value of the tag last changed during the dead band.<br />
• Start Condition: The time when the dead band started.<br />
The Email Settings button opens a dialog<br />
box that allows you to specify settings for<br />
email messages that can be sent when<br />
Alarms occur. Email (SMTP) setting must<br />
be configured prior to use of the Alarm<br />
Emails. Attachments are not allowed in this<br />
dialog, but attachments can be emailed<br />
using WS built-in functions.<br />
21–4 InduSoft Web Studio
Alarm/Event Control<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Alarm/Event Control<br />
To display Alarms, either On-line or Historical Alarms, we need to use the Alarm/Event Control<br />
tool. This tool is found in the Active Objects Toolbar. When you select the Alarm/Event Control tool,<br />
you can place an Alarm/Event Control Object on your screen. An Alarm/Event Control Object looks<br />
something like the following:<br />
By double-clicking on the Alarm/Event Control Object, you can open the Object Properties dialog box as shown.<br />
The Type combo-box allows you to select what type of Alarms or Events are being displayed. The choices are:<br />
• Alarm On-line<br />
Displays current Alarms. When an Alarm is Normalized and Acknowledged, it will disappear from this<br />
display.<br />
• Alarm History<br />
Retrieves Alarms from the historical Alarm Database.<br />
• Alarm History + Event<br />
Retrieves Alarms and Events from the historical Alarm Database and historical Event Database<br />
• Event<br />
Displays current Events<br />
The Fonts button allows you to specify the Font for the<br />
Alarm/Event Control Object.<br />
The Columns button opens a Columns dialog box that allows<br />
you to specify the columns to be displayed in the Alarm/Event<br />
Control.<br />
InduSoft Web Studio 21–5
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Alarm/Event Control<br />
The Filters button opens a Filters dialog that allows you to specify filtering parameters, controlling which alarms<br />
will be visible during runtime. Alarm filtering can be used to allow the operator to focus on high-priority alarms,<br />
or alarms with some logical grouping (e.g. by location, type,<br />
etc.). Some of the key Alarm filters are:<br />
• Alarm Group<br />
The Alarm Group corresponds to the Alarm<br />
Worksheet number, starting with 1. If Group 0 is<br />
specified, this means that all Alarm Groups are to be<br />
used. You can specify one or more Alarm Groups<br />
(e.g. 1, 3, 5-8). A string Tag can be used in this field<br />
to change the Alarm Group at runtime.<br />
• Alarm Priority<br />
The Alarm Priority From and To fields are used to<br />
display Alarms in a given priority range. The Alarm<br />
Priority is specified in the Alarm Worksheet. Numeric<br />
tags or values can be used in these fields.<br />
• Alarm Selection<br />
The Alarm Selection field corresponds to the text<br />
typed in the Selection field in the Alarm Worksheet.<br />
This can be a string Tag.<br />
• Type<br />
This field allows you to enter the Alarm type to filter by (e.g. HiHi, Hi, Lo, LoLo)<br />
• State<br />
This field allows you to enter the Alarm State which can be used to filter the Alarm display.<br />
• Tagname, Message, Username<br />
You can sort based on the Tag name, the Message, or the User Name (log on name of the User)<br />
The Advanced button opens an Advanced dialog box.<br />
• Ack All Trigger<br />
Used to specify a Tag that will Acknowledge all Alarms.<br />
• Ack Trigger<br />
Used to specify a Tag with will Acknowledge the last<br />
(the top) Alarm.<br />
• Run-time dialog triggers<br />
Specifies Tags that will open Columns or Filters dialog<br />
boxes at runtime, allowing changes to be made.<br />
• Total Items<br />
Can use an integer Tag in this field to return the total<br />
Alarms remaining after filtering the Alarms<br />
• Selected Tag<br />
Can use a string Tag in this field to return the text<br />
name of a Tag that is associated with the Alarm. The<br />
Tag name can be used as a string Pointer tag to<br />
acknowledge the specific alarm.<br />
• Navigation Triggers<br />
Can specify Tags (associated with objects such as<br />
buttons) that can navigate the Alarm list.<br />
21–6 InduSoft Web Studio
Alarm/Event Control<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Creating an Alarm Group and Alarm Screen<br />
In this exercise, we will develop an Alarm Group and Alarm Screen that generated Alarms based on the level of<br />
the tanks used in the TankDemo screen.<br />
Create the following tags:<br />
Tag Name Size Type<br />
SelAlarm 0 String<br />
TotAlarms 0 Integer<br />
TotUnAck 0 Integer<br />
Select the Tasks tab of the Workspace and then right-click on the Alarms folder.<br />
Select Insert from the pop-up menu to open an Alarms Worksheet.<br />
Complete the Alarms Worksheet as follows:<br />
Opening an Alarm Worksheet<br />
ALARM001.ALR Worksheet<br />
InduSoft Web Studio 21–7
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Alarm/Event Control<br />
Click the Advanced button<br />
Complete the Advanced dialog box as follows:<br />
Advanced Dialog<br />
Click OK to close the Advanced dialog box<br />
Save and Close the Alarms Worksheet<br />
Next, we will create an On-Line Alarm display.<br />
Open the Alarms.scr Screen<br />
Click the Alarm/Event Control tool and create an Alarm/Event Control object on the screen.<br />
Double-click the Alarm/Event Control object to open the Object Properties dialog.<br />
Make sure the Type is set to Alarm Online<br />
Object Properties: Alarm<br />
Click the Advanced button in the Object Properties dialog box to configure the Advanced Settings for the<br />
Alarm/Event Control<br />
21–8 InduSoft Web Studio
Alarm/Event Control<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Configure the Advanced dialog box as follows<br />
Advanced Dialog<br />
Click OK to close the Advanced dialog box. Close the Object Properties dialog.<br />
Create three (3) buttons on the Alarms.scr Screen with captions as follows:<br />
Alarm Acknowledgement Buttons<br />
InduSoft Web Studio 21–9
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Alarm/Event Control<br />
The first button will toggle the value of the internal Tag AckAll, to acknowledge all alarms that occurred.<br />
Give the button the caption Ack All Alarms, add the Command property to the button, and configure the<br />
command as shown<br />
Configuring the Ack All Alarms Button<br />
The second button will toggle the value of the internal tag AckAlr, to acknowledge the last alarm that<br />
occurred. Give the button the caption Ack Last, add the Command property to the button, and configure<br />
the command as shown:<br />
Configuring the Ack Last Alarm Button<br />
The third button will toggles the Ack Tag Field of the Tag which caused the Alarm. When the User clicks on<br />
any individual Alarm, the (string) name of the Tag that caused the Alarm will be returned in the SelAlarm tag<br />
(as specified in the Advanced dialog of the Alarm/Event Control). This string Tag can be used as a pointer<br />
to the actual Tag that caused the Alarm. By toggling the Ack field of the Tag, it will acknowledge the<br />
individual Alarm. Give the button the caption Ack Selected Alarm, add the Command property, and<br />
configure the command as shown:<br />
Close the button Object Properties dialog box.<br />
Configuring the Ack Selected Alarm Butto<br />
21–10 InduSoft Web Studio
Alarm/Event Control<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Now, we will add a Historical Alarm display<br />
Make sure the Alarms.scr Screen is open<br />
Click the Alarm/Event Control tool and create an Alarm/Event Control object on the screen.<br />
Double-click the Alarm/Event Control object to open the Object Properties dialog.<br />
Position the Alarm/Event Control below the On-line Alarm/Event Control<br />
Make sure the Type is set to Alarm History<br />
Alarm History Object Properties<br />
Now, we will finish the Alarm Screen.<br />
Add a Text object with the Caption Total Alarms = ######. Add the Text I/O Property, and specify the Tag<br />
as TotAlarms.<br />
Add a Text object with the Caption Total Unacknowledged = ######. Add the Text I/O Property, and<br />
specify the Tag as TotUnAck.<br />
Add a Text object above the On-Line Alarm/Event Control object, with the caption On-Line Alarms<br />
Add a Text object above the Historical Alarm/Event Control object, with the caption Historical Alarms<br />
InduSoft Web Studio 21–11
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Alarm/Event Control<br />
The finished Alarms.scr should look similar to the following:<br />
Save and Close the Screen<br />
The following table is provided to illustrate how the WS Alarms task counts alarm messages for the Total<br />
Alarms and Total UnAck field totals:<br />
Alarm<br />
State<br />
Acknowledgement<br />
State<br />
Counted for<br />
Total Alarms Tag<br />
Counted for<br />
Total UnAck Tag<br />
Active<br />
Normalized<br />
Unacknowledged Yes Yes<br />
Acknowledged Yes No<br />
Unacknowledged Yes Yes<br />
Acknowledged No No<br />
21–12 InduSoft Web Studio
Alarm/Event Control<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Notes:<br />
• When using Alarm Worksheets, before changing the Group Name field, you should first save the Alarm<br />
worksheet. Otherwise, you can lose alarm settings in an unsaved worksheet.<br />
• In the Alarm Worksheet Advanced settings dialog, it is recommended to use unique Tag names for the<br />
Total Alarms and Total UnAck fields for each Alarm worksheet.<br />
• When configuring the Alarm Worksheet, if you did not select the Summary option, the alarms for this<br />
group will not appear in the alarm objects in the screens or printer during execution.<br />
• When configuring the Alarms Worksheet, the Printer check-box should not be used with DeskJet or<br />
LaserJet printers because they will spend one entire leaf of paper for each alarm message. These<br />
printers are not able to print one line and then wait for the next printing command.<br />
• Alarm messages can contain any system tag using the following syntax:<br />
message {tag_name}<br />
• The Selection field must have a string with a maximum of 7 characters (additional characters will be<br />
ignored).<br />
• When using the Alarm Email function, you must be connected to the Internet (manually or using an<br />
automatic dial-up function) and you must have executed the WS built-in function CNFEmail to configure<br />
the SMTP server, user name, password, and domain before trying to send an email.<br />
InduSoft Web Studio 21–13
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Example: Disabling Alarms<br />
Example: Disabling Alarms<br />
There are times when you may want to disable an alarm triggered by a tag or group of tags. This can easily be<br />
accomplished by manipulating the tag’s AlrDisable field during runtime. The AlrDisable field is R/W, and if the<br />
field is set to 0, any alarm associated with the tag is enabled. This means that if an alarm condition occurs, an<br />
Alarm will be generated If the field is set to 1, any alarm associated with the tag is disabled. This means that if<br />
an alarm condition occurs, an Alarm will not be generated.<br />
You can read or manipulate (set) the AlrDisable filed by the following syntax:<br />
From an <strong>IWS</strong> Math Script<br />
Tag<br />
AlrStatus<br />
Expression<br />
TagName->AlrDisable //returns the current Alarm disable status<br />
TagName->AlrDisable 0 //enables Alarms from this tag<br />
TagName->AlrDisable 1 //disables Alarms from this tag<br />
From VBScript<br />
$AlrStatus = $TagName-> AlrDisable<br />
$TagName->AlrDisable = 0<br />
$TagName->AlrDisable = 1<br />
//returns the current Alarm disable status for this tag<br />
//enables Alarms from this tag<br />
//disables Alarms from this tag<br />
21–14 InduSoft Web Studio
Exercise: Adding an Alarm/Event Control Display<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Adding an Alarm/Event Control Display<br />
Open the Header.scr Screen<br />
Add an Alarm/Event Control Object<br />
Double click on the Alarm/Event Control to open the Object Properties dialog box<br />
In the Type field, select Alarm History + Event<br />
Save and Close the Header.scr Screen<br />
InduSoft Web Studio 21–15
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Adding an Alarm/Event Control Display<br />
Notes<br />
21–16 InduSoft Web Studio
Chapter 22.<br />
Data Logging & Trend Display<br />
In this Chapter, we will cover Data Logging (using the Trend Task) and Trend Display (using the Trend Control<br />
Object placed on a Screen). These two items (Data Logging & Trend Display) are normally used together, but<br />
do not have to be. Data Logging can occur without the data being used in a Trend Display, and the Trend<br />
Display (Trend Control Object) can be used with historical data from a database.<br />
Configuring the Trend Task<br />
The Trend Task is used to log <strong>IWS</strong> Tag data to a database. The Trend Task defines which data is logged and<br />
where it is logged to. Data can be logged to local files (will have a *.hst file extension) using the <strong>IWS</strong> proprietary<br />
format, or can be logged to a database using the built-in ADO database interface.<br />
Like other Tasks, the Trend Task consists of one or more worksheets that are sequentially numbered starting<br />
with 1. You can add a new Trend Worksheet by doing the following:<br />
• Click on the Tasks tab in the Workspace in the development environment<br />
• Position you mouse cursor over the Trend folder and click the right mouse button.<br />
• Select the Insert option<br />
As an alternative, you can select File New from the Main Menu Bar, or click on the New icon in the Standard<br />
Toolbar, and select Trend Worksheet.<br />
The Header parameters are:<br />
• Description<br />
A description of the worksheet, for documentation purposes only<br />
• History Format<br />
Allows you to define where the Trend Data is to be saved, in a file using the <strong>IWS</strong> Proprietary format or<br />
in a Database. If Proprietary is selected, the Database Configuration button is grayed out.<br />
• Database Configuration<br />
Opens a Database Configuration dialog box. See the Chapter on <strong>IWS</strong> Database Configuration for<br />
more details.<br />
InduSoft Web Studio 22–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Configuring the Trend Task<br />
• Advanced<br />
Allows you to enter settings for Batch, Disk Space Control and Disabling of the data logging.<br />
• Save on Trigger check box<br />
This check box should be checked if you want to log (save) data when the Tag in the Trigger field<br />
toggles (changes) value<br />
Note:<br />
• If you want to save data based on a time base, then you should check the Save on Trigger<br />
check box and UNCHECK the Save on Tag Change check box.<br />
• The time base for a Trigger Tag can be specifed in the Scheduler Task.<br />
• Trigger field<br />
This field is used to enter the Tag used to Trigger the data logging function if the Save on Trigger<br />
check box is checked.<br />
• Save on Tag Change check box<br />
This check box, if checked, will save all the tags in the Trend Worksheet whenever any of the tags in<br />
the Worksheet change value.<br />
The Trend Advanced Settings dialog box, configured to store data to a Batch File using <strong>IWS</strong> Proprietary<br />
format, is shown below.<br />
The Batch Pane has the following settings:<br />
• Start/Stop<br />
Insert a Tag into this field to trigger the starting or stopping of data logging to the Batch File. If the Tag<br />
value is 0, the data logging will be stopped. If the Tag value is 0, data logging will start (continue<br />
logging).<br />
If History Format = Proprietary<br />
If History Format = Database<br />
Data will be logged into the Batch File specified<br />
Data will be logged into a new Record (row) in the Database in a<br />
Table specified in the Database Configuration dialog<br />
22–2 InduSoft Web Studio
Configuring the Trend Task<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
• Name<br />
This field can be a string value or a string Tag (configured in curly braces, e.g. {strTag}).<br />
If History Format = Proprietary<br />
Name should be a name of a file where the Batch data will be<br />
logged. File should have a *.HST file extension. Format of the<br />
Name should be [Path], where<br />
Path is an optional Path name. Will default to the Application<br />
folder.<br />
FileName is the Batch History file.<br />
Note:<br />
• The Batch Name can use one or more Tags in the Path\FileName field. Tags must be<br />
enclosed in curly braces. E.g. C:\MyBatch\{BatchName} {BatchNumber}.hst<br />
.<br />
If History Format = Database<br />
The Name value will be stored in the Batch_Name field of the<br />
BatchHistory Table.<br />
• Delete<br />
Enter a Tag in this field. When the tag toggles (changes value), the Batch will be deleted.<br />
If History Format = Proprietary<br />
If History Format = Database<br />
Batch History File will be deleted<br />
Will set the Delete field in the BatchHistory Table to True, but the<br />
data will be remain. The Trend Control Object will only view Batch<br />
data that has the Delete Field set to 0 (False).<br />
• Existent<br />
Enter a Tag in this field. It will receive a value of 1 (True) if the Batch specified in the Name field<br />
already exists, otherwise it will receive a value of 0 (False).<br />
• Description<br />
This field is only used when History Format = Database. This field can contain a string or a string Tag<br />
enclosed in curly braces. When the tag in the Stop/Start field changes to True (non-zero value), the<br />
Record (row) added to the BatchHistory Table in the Database will display the string value in this field.<br />
• Save Data Even if Batch is Not Running check box<br />
This check box will determine when data is saved to the Batch file or database. If Unchecked, the<br />
historical data will only be logged when the Tag in the Stop/Start field is True (i.e. a non-zero value).<br />
The Disk Space Control Pane has the following settings:<br />
• History life time (Days)<br />
Specifies how many days to keep the history file on the disk. After the specified period. <strong>IWS</strong> will<br />
automatically erase the file. This option is for the History Format = Proprietary only. If a value of 0,<br />
the files will not be erased.<br />
• Compress after (Days)<br />
Specifies the number of days to keep the trend history file (*.hst) on the disk before compressing the<br />
file. This option is for the History Format = Proprietary only. If a value of 0, the files will not be erased.<br />
• Disable All Data Saving<br />
Enter a Tag in this field. When the value of this Tag is True (0), the Trend Task will stop recording for<br />
this Worksheet.<br />
InduSoft Web Studio 22–3
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Converting Trend History Files<br />
The Body Parameters have the following fields:<br />
• Tag Name field<br />
Enter the name of a Tag to be logged in this field.<br />
• Deadband field.<br />
This option is only when the Save on Tag Change check box is checked. The value in this field defines<br />
the amount the Tag needs to change value (either up or down) in order for the tag to be logged to the<br />
database.<br />
• Field field.<br />
When the History Format = Database option is selected, this field will appear. It is used to define the<br />
Field (Column) in a database where the Tag will be stored. If this field is left blank, the name of the Tag<br />
will be used as the Field Name. If you use an Array Tag or Class tag, the Array Index square brackets [<br />
and ] as well as the Class Name/Class Member separator, the . character (period), will be replaced by<br />
the underscore character _ . E.g.:<br />
MyArray[1] MyArray_1<br />
MyClass.Member MyClass_Member<br />
MyClass[3].Member <br />
MyClass_3_Member<br />
Note:<br />
• Historical Data stored in a file using the <strong>IWS</strong> Proprietary format can be displayed by the Trend<br />
Control Object.<br />
• Historical Data stored by a Trend Worksheet into a Database can be displayed by the Trend<br />
Control Object or by the Grid Object.<br />
• Once you log data to a File (using the <strong>IWS</strong> Proprietary format), DO NOT add or remove tags,<br />
otherwise the data will be incorrectly read.<br />
• Use the Scheduler to define time bases (other than Second or Minute).<br />
• Be mindful of the storage requirements if you log several tags at a high data rate.<br />
• Be mindful of network bandwidth requirements when logging to a remote database<br />
• You can store up to 240 tags in a single Trend Worksheet. You can have up to 999 Trend<br />
Worksheets.<br />
.<br />
Converting Trend History Files<br />
Trend History Files stored in the <strong>IWS</strong> proprietary format are binary files and cannot be read by simple text<br />
editors. <strong>IWS</strong> provides a built-in function Hst2Txt that can be called to convert the binary file into a text file. The<br />
Hst2Txt function can be called at a command level using the Windows CMD command processor.<br />
<strong>IWS</strong> provides a function to convert text-based historical data files to <strong>IWS</strong> proprietary format binary files. This<br />
function, Txt2Hst.exe, can only be called from the Windows CMD command processor.<br />
22–4 InduSoft Web Studio
Trend Control Object<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Trend Control Object<br />
The Trend Control Object is used to display data points (values) from different data sources in a graphic format.<br />
The main features provided by the Trend Control object are:<br />
• Display of multiple pens simultaneously<br />
• Support for different Data Sources, such as Tag, Batch, Database and Text File<br />
• Capability to generate X/Y graphs from the configured data sources<br />
• Simultaneous display of an unlimited number of data points. This feature might be limited by the<br />
hardware used since available memory and performance will vary.<br />
• Built-in toolbar, which provides interfaces for the user to interact with the Trend Control object during<br />
the runtime<br />
• Built-in legend, which displays the main information associated to each pen linked to the object<br />
• Zooming and auto-scaling tools<br />
• Horizontal and vertical orientation<br />
Trend Control Development Interface<br />
Although the Trend Control object supports flexible configurations to meet the specific needs of your<br />
application, most of the settings are set by defaults based on the most common interfaces. Therefore, in many<br />
cases, you will only configure data points (displayed during the runtime), which can be done easily by clicking<br />
the Points button from the Object Property window.<br />
Click the Trend Control tool to add it to your application screen. Double-click on the object to launch its Object<br />
Properties dialog window:<br />
Trend Control Object Properties Dialog<br />
The settings in the Trend Control Object Properties dialog box are:<br />
• Border<br />
Specifies a border line Type (style) by clicking on None, Solid, Dashed, Etched, Raised or Sunken. You<br />
can also select the color of the border line with the color box to the right of the Type field.<br />
• Fill<br />
If Fill radio button is selected, you can choose a background color for the Trend Control object from the<br />
color box. If you select the No Fill radio button, the background of the Trend Control object will be<br />
transparent.<br />
• Axes<br />
Allows you to configure the settings for the X and Y axis.<br />
InduSoft Web Studio 22–5
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Trend Control Object<br />
• Data Sources<br />
Allows you to define the Data Sources to be used by the Trend Control Object. You can have one or<br />
more Data Sources.<br />
• Legend<br />
Lets you choose whether to show an embedded legend during the runtime, and if so, which fields to<br />
display in it.<br />
• Toolbar<br />
Lets you choose whether to show an embedded toolbar during the runtime, and if so, which buttons (or<br />
Tags) that trigger actions to display in it.<br />
• Advanced<br />
Lets you configure additional options, such as runtime triggers and custom point selection.<br />
Trend Control Runtime Interface<br />
When enabled, some embedded interfaces can help you to interact with the Trend Control during the runtime:<br />
• The Toolbar option lets you choose whether to show an embedded toolbar during the runtime, and if<br />
so, which buttons that trigger actions to display in it.<br />
• The Legend option lets you choose whether to show an embedded legend during the runtime, and if<br />
so, which fields to display in it.<br />
• Using the Scroll bar, you can slide through the X-axis values, according to the period configured for<br />
this scale.<br />
• Using the Time bar, you can modify the Duration, as well as the Start Date/Time and/or the End<br />
Date/Time, for the data displayed on the object. Changing these values will affect the tags associated<br />
with the X-axis scale (if any).<br />
Toolbar<br />
Legend<br />
Scroll<br />
Time<br />
Embedded Interfaces in the Trend Control Object<br />
22–6 InduSoft Web Studio
Exercise: Creating an Online Trend<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Creating an Online Trend<br />
The online trend you create in this exercise will graph the temperatures of the tanks in real-time, updated every<br />
second. While the application runs, trend data are saved to an internal history file, so the trend graph can be<br />
scrolled to display any period in the trend history.<br />
CREATING A TREND WORKSHEET<br />
First, you must create a Trend worksheet specifying the Tags that will be saved to the history file and made<br />
available to any Trend Control objects in the application:<br />
Create a new Trend worksheet by right-clicking on the Trend folder (in the Tasks tab of the Workspace)<br />
and selecting Insert:<br />
Inserting a Trend Worksheet<br />
Notes:<br />
• You can also create new worksheets using the New dialog, which is accessed by selecting File<br />
New or by pressing the Ctrl+N keyboard shortcut.<br />
• The Trend Worksheet is used to define where & how the data is to be logged. The Trend<br />
Control Object is used to define how the data is to be displayed.<br />
Configure the Trend worksheet as shown:<br />
Save and Close the Worksheet<br />
Configuring the TREND001.TRD Worksheet<br />
InduSoft Web Studio 22–7
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Creating an Online Trend<br />
CREATING THE TREND SCREEN<br />
Next, we will open the TrendData.scr Screen and add a Trend Control object. This will be used to display the<br />
trend data.<br />
Open the TrendData.scr Screen<br />
Click on the Trend Control tool icon in the Active Objects toolbar and add a Trend<br />
Control Object on the screen. Open its Object Properties dialog:<br />
Trend Control Object Properties Dialog<br />
Because of the large number of properties available on a Trend Control Object, the properties are divided<br />
among secondary dialogs.<br />
Click the Axes button to open the Axes dialog:<br />
Trend Control Object Properties — Axes Dialog<br />
The X-axis of the trend graph will be standard Date/Time, but its format must be adjusted.<br />
22–8 InduSoft Web Studio
Exercise: Creating an Online Trend<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
In the X Axis area, click the Scale Format button to open the Format: Date-Time dialog:<br />
X Axis — Format: Date-Time<br />
Change Number of Labels to 4, and then click OK to close the Format: Date-Time dialog and return to<br />
the Axes dialog.<br />
The Y-axis format must also be adjusted.<br />
In the Y Axis area, click the Format button to open the Format: Numeric dialog:<br />
Y Axis — Format: Numeric<br />
Change Number of Labels to 4, click OK to close the Format: Numeric dialog and return to the Axes<br />
dialog.<br />
By default, multiple trend data points are each displayed in their own sections of the trend graph. However, in<br />
this exercise the data points should be displayed together in the same section, so that they can be compared as<br />
they progress.<br />
In the Y Axis area, click the Multiple Sections checkbox to deactivate it (it should be unchecked).<br />
Click OK to close the Axes dialog and return to the Object Properties dialog.<br />
InduSoft Web Studio 22–9
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Creating an Online Trend<br />
Next, the data points themselves must be configured.<br />
In the Object Properties dialog, click the Points button to open the Points dialog:<br />
Trend Control Object Properties — Points Dialog<br />
Configure three data points as follows…<br />
Point 1:<br />
Label: Tank 1 Temp<br />
Color: Black<br />
Data Source: Tag<br />
Tag/Field: tank[1].Temperature<br />
Min: 0<br />
Max: 100<br />
Point 2:<br />
Label: Tank 2 Temp<br />
Color: Dark Red<br />
Data Source: Tag<br />
Tag/Field: tank[2].Temperature<br />
Min: 0<br />
Max: 100<br />
Point 3:<br />
Label: Tank 3 Temp<br />
Color: Dark Green<br />
Data Source: Tag<br />
Tag/Field: tank[3].Temperature<br />
Min: 0<br />
Max: 100<br />
22–10 InduSoft Web Studio
Exercise: Creating an Online Trend<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
When you are done, the Points dialog should look something like this:<br />
Points Dialog with Three Points Configured<br />
Click OK to close the Points dialog, and then close the Object Properties dialog.<br />
The finished TrendData screen should look something like this:<br />
Trend Online Screen<br />
Save and Close the Screen<br />
If you run the application now, the trend graph will display (in real-time) the simulated data generated by the<br />
field process simulator that you created in the previous chapter.<br />
InduSoft Web Studio 22–11
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Creating an Online Trend<br />
Decreasing the Save Frequency Using the Scheduler<br />
As it is now configured, the Trend worksheet saves to the history file and updates the trend graph every<br />
second. While this makes for a smooth graph, it also decreases system performance and generates extremely<br />
large history files.<br />
You can decrease the save frequency by reconfiguring the Save On Trigger field (on the Trend worksheet) with<br />
a different tag or expression. The field is currently configured with the Second tag, which is one of the standard<br />
Internal Tags in <strong>IWS</strong>. Every time the value of the tag changes — which is every second, of course — the save<br />
is triggered.<br />
You could easily reconfigure the Save On Trigger field with another Internal Tag (e.g. Minute, Hour, Month,<br />
and so on), but this may trigger saves too infrequently to be useful.<br />
To trigger saves at a nonstandard frequency, use the Scheduler:<br />
Create a new Tag in the Application database (review the procedure on page Error! Bookmark not defined. if<br />
necessary) with the following specifications:<br />
Name: TrendUpdate<br />
Size: 0<br />
Type: Boolean<br />
Description (optional)<br />
Scope: Local<br />
Open the Trend worksheet and reconfigure the Save On Trigger field with this new tag:<br />
Create a new Scheduler worksheet (in the Tasks tab of the Workspace), and then add the following line:<br />
Configuring the SCHED001.SCH Worksheet<br />
This line will cause TrendUpdate to toggle every 15 seconds. TrendUpdate was defined as a Boolean, and the<br />
expression changes the value of the tag to its opposite state: from FALSE to TRUE, then from TRUE to FALSE,<br />
and so on. Every time the value of the tag changes, a save is triggered.<br />
Save and close both worksheets.<br />
22–12 InduSoft Web Studio
Using an External Text File<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Using an External Text File<br />
The Trend Control can generate trend charts from any Text File that has the values organized in columns and<br />
rows. The columns should be separated from each other by special characters (usually the comma). Each<br />
sample (pair of values representing a point in the graph) is represented by a row (a line in the file). Suppose<br />
that the user wants to display a chart with the information in the following table:<br />
–X Value –Y1 Value –Y2 Value<br />
–0 –0 –10<br />
–1 –1 –20<br />
–2 –2 –30<br />
–3 –3 –40<br />
We have one variable that represents the X Axis and two variables (Y1 and Y2) that will represent different lines<br />
in the chart.<br />
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<br />
shown below:<br />
Creating a Text File Using Notepad.exe<br />
We strongly recommend that you save the file in the same folder where the application is. By doing so, you do<br />
not have to specify the entire path and your application will still work, even if it is copied to a different computer.<br />
InduSoft Web Studio 22–13
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Using an External Text File<br />
Once you have added the Trend Control to your screen, double click on the object to open then Object<br />
Properties and click on Axis. Change the Data Type of the X Axis to numeric, and set the ranges as shown in<br />
the picture below:<br />
Configuring the X Axis for Numeric Data<br />
Click Ok on this Window and then, in the Object Properties window, click on the Data Sources button. The<br />
following window will display:<br />
Trend Control Object Properties — Data Sources<br />
We need to create a data source in order to access to the text file. Click on the new button, specify the Data<br />
Source Name “MyTextFile” and then click Create. You should see the following information now:<br />
Creating a New Data Source (Text File)<br />
22–14 InduSoft Web Studio
Using an External Text File<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
On the X Axis field we need to indicate which column in our text file represents the X Axis. In our example we<br />
are using column zero, so enter with zero for this field, then click on the button Data Source Settings, the<br />
following Window will display:<br />
Specifying the Text File Name and Field Delimiter<br />
If you have copied the text file to the application folder, you only have to specify the file name, otherwise, enter<br />
with the complete path where the file is located (use the browse button as needed). Click Ok on this window<br />
and Ok again to finish the data source configuration and close the Data Source configuration Window.<br />
Now we need to define our Y1 and our Y2. They will be represented by points on our Trend Control. Double<br />
click on the Trend Control again to access the Object Properties window and then click on Points. Your next<br />
step is to define the points according to the following figure:<br />
Configuring the Data Points (Pens)<br />
After following these steps, run your application and you should see something similar to the figure below:<br />
InduSoft Web Studio 22–15
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Using an External Text File<br />
22–16 InduSoft Web Studio
Using an External Database<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Using an External Database<br />
The Trend Control can generate trend charts from any Relational Database that can be accessed through the<br />
ADO.Net technology. This Appendix illustrates how to access a Microsoft Access Database; if you are using<br />
another type of database, almost all the definitions will apply, however you will need to configure your<br />
connection on a different way. For information on how to configure other databases, please refer to the<br />
Appendixes in the Database Interface section of this manual.<br />
Suppose that you have an access database at your C drive named “mydata.mdb” and that you want to<br />
generate a chart based on the information in the following table:<br />
Table in a Relational Database<br />
The first step is to add the Trend Control to your screen. Now double click on the object to open then Object<br />
Properties and click on Data Sources. The following window will display:<br />
Trend Control Object Properties — Data Sources<br />
InduSoft Web Studio 22–17
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Using an External Database<br />
We need to create a data source in order to access to the database. Click on the new button, specify the Data<br />
Source Name “MyDB” and then click Create. You should see the following information now:<br />
Creating a New Data Source (Database)<br />
Change the Source Type to Database and specify Time_Stamp in the X Axis field. Then click on the Data<br />
Source Settings button, the following window will display:<br />
Database Configuration Window<br />
22–18 InduSoft Web Studio
Using an External Database<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Uncheck the check box Use application default and click on the browse button<br />
connection string. The following window will display:<br />
in order to configure the<br />
Data Link Properties — Selecting a DB Provider<br />
Select the Microsoft Jet 4.0 OLE DB Provider and click Next. In the following window, you should specify the<br />
database path:<br />
Data Link Properties — Configuring the DB Connection<br />
InduSoft Web Studio 22–19
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Using an External Database<br />
Click Ok to finish the Connection String configuration. Now uncheck the option Use default name and select the<br />
table from your database as shown below:<br />
Selecting the Database Table<br />
Click Ok on this window and Ok again to finish the data source configuration and close the Data Source<br />
configuration window.<br />
Now we need to define Temperature and Pressure. They will be represented by points on our Trend Control.<br />
Double click on the Trend Control again to access the Object Properties window and then click on Points. Your<br />
next step is to define the points according to the following figure:<br />
Configuring the Data Points (Pens)<br />
22–20 InduSoft Web Studio
Using an External Database<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
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<br />
properly configure the start date/time as shown below:<br />
InduSoft Web Studio 22–21
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Using an External Database<br />
Notes<br />
22–22 InduSoft Web Studio
Chapter 23.<br />
Event Manager<br />
The Event Manager is used to log Events to either the WS proprietary database or to a relational database and<br />
is configured through the Event Settings dialog box. The types of events that can be logged include:<br />
• Security System Events<br />
When checked, any Security System event will be logged into the Event Database. Examples include<br />
user log on and log offs, password expired, invalid log on attempts, etc.<br />
• Display Change Events<br />
When checked, any Screen being opened or closed will be logged to the Event Database.<br />
• Recipe Events<br />
When checked, any Recipe function (e.g. Recipe Load or Recipe Save) will be logged to the Event<br />
Database<br />
• Report Events<br />
When checked, any Report function (printed or saved to a disk) will be logged to the Event Database<br />
• Custom Messages<br />
When checked, custom messages created by the User (via the WS built-in function SendEvent() will be<br />
logged to the Event Database.<br />
• System Warnings<br />
When checked, general system warnings will be logged to the Event Database. General System<br />
Warnings include:<br />
- Division by 0<br />
- Accessing an invalid array index<br />
- Errors that occur when sending an alarm email<br />
• Tag Events<br />
When checked, will allow you to log changes to a Tag’s value. The change in Tag value may or may not<br />
be the result of operator input and the logging of the Event is made whether the Tag triggers an Alarm<br />
or not.<br />
InduSoft Web Studio 23–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Configuring Event Retrieval<br />
Exercise: Configuring Event Retrieval<br />
Select the Database tab. Right-click the Event Settings icon, and select Open from the pop-up to open the<br />
Event Settings dialog:<br />
Selecting Event Settings<br />
Event Settings Dialog<br />
23–2 InduSoft Web Studio
Exercise: Configuring Event Retrieval<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Configure the parameters on the Event Settings dialog as follows:<br />
<br />
<br />
<br />
<br />
Enable event logger check-box: Enable (check) this box to enable event-logging.<br />
Disable field (optional): Type a tag into this field. If the tag value is other than 0 (0=false), WS<br />
automatically disables the Event Logger.<br />
Event Database… : Used to configure the Event Database (for relational databases)<br />
Security System check-box: Enable (check) this box to include security system events in the historic<br />
event file. WS logs the following security system events:<br />
- Log On / Log Off users<br />
- User created/removed using the CreateUser() or RemoveUser() functions<br />
- User blocked/unblocked using the BlockUser() or UnblockUser() functions<br />
- User blocked by the security system after several attempts to enter an invalid password<br />
- Password expired<br />
- Password modified<br />
- Invalid Log On attempt<br />
• Display check-box: Enable (check) this box to include screen Open and Close events in the historical<br />
event file.<br />
• Recipe check-box: Enable (check) this box to include recipe load, save, init, and delete events in the<br />
historical event file.<br />
• Report check-box: Enable (check) this box to include reports saved to disk or send to printer events in<br />
the historical event file.<br />
• Custom Messages check-box: Enable (check) this box to include events generated by the<br />
SendEvent(strEvent) function in the historical event file.<br />
• System Warning check-box: Enable (check) this box to include general system warnings (such as<br />
Division by zero, Attempted to access invalid array index, and so forth) in the historical event file.<br />
WS logs the following system warning events:<br />
- Errors that occur when sending alarms by email<br />
- Tag was blocked/unblocked<br />
- Division by zero<br />
- Connection/Disconnection of the remote security system<br />
• Tags check-box: Enable (check) this box to enable and log tag changes in the historical event file.<br />
Configure the tags you want to log in the Tags table as follows:<br />
- Tag Name column: Type the name of the tag you want to log in the event file.<br />
- Dead Band column: Type a value for comparing and filtering acceptable changes.<br />
For example, if you specify a Dead Band value = 5 for a tag value = 50 and the tag value changes<br />
to 52, the system will not register this variation in the event log file, because the variation is less<br />
than 5. However, if the tag value change is equal to or greater than 5, the system will save the new<br />
value to the history file.<br />
- Message column: Type a string (message) related to this tag change. You can specify tags in<br />
messages using the {tag name} syntax.<br />
The Tags parameter can be useful if you want to generate a log file of events that are not<br />
necessarily alarm conditions (for example, Motor On, Motor Off, and so forth).<br />
InduSoft Web Studio 23–3
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Configuring Event Retrieval<br />
Notes<br />
23–4 InduSoft Web Studio
Chapter 24.<br />
Grid Object<br />
The Grid Object allows you to view data in a tabular format on a Screen. Data contained in the Grid Object can<br />
be read from or written to several sources:<br />
• Databases<br />
Supports relational databases using a built-in interface to ADO.NET providers<br />
• Class Tags<br />
• Text File<br />
Text files supported include CSV, Tab delimited, or other character delimited files<br />
• Direct input<br />
The Grid Tool is located in the Active Objects toolbar. To insert a Grid Object onto a Screen, click<br />
on the Grid tool icon, place your mouse cursor on the Screen, then click and drag (while holding<br />
the left mouse button down). When you release the left mouse button, the Grid Object will be<br />
displayed on the Screen.<br />
Grid Object<br />
To configure the Grid Object, position your mouse on the Grid Object and either double-click the left mouse<br />
button, or click the right mouse button, to a access the Object Properties dialog box.<br />
Grid Object: Object Properties dialog<br />
box<br />
The first step in configuring the Grid Object is to select the Data Source type, using the combo box. The Data<br />
Source type options are:<br />
• Text File<br />
Displays data from a Text file, in ASCII or Unicode format<br />
• Class Tag<br />
Displays values from a Class Tag or Array of Class Tags. Each Class Member is a Field (column) of the<br />
Grid Object. Every Array index is one row in the Grid Object.<br />
• Relational Databases<br />
Displays data from a relational database, using ADO<br />
InduSoft Web Studio 24–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Configuring Event Retrieval<br />
Other settings in the Grid Object - Objects Properties Dialog Box are:<br />
• E-Sign<br />
When checked, user will be prompted to enter an electronic signature before entering or modifying data<br />
in the Grid Object<br />
• VK<br />
Selects a Virtual Keyboard. Can use the Default specified in the Project Settings Runtime<br />
Desktop dialog box, or you can specify a specific VB to be used.<br />
• Security<br />
Enter the security access level required for the Object & any Dynamic Property<br />
• Disable<br />
You can enter an expression in this field (i.e. <strong>IWS</strong> Tag & expression) to disable data input and operation<br />
by the user.<br />
• Highlight Color<br />
Specifies a background color for the selected row, during runtime<br />
• Text Color<br />
Selects a color for the Text in the selected row, during runtime<br />
• Win Color1<br />
Selects a background color for the odd rows<br />
• Win Color2<br />
Selects a background color for the even rows<br />
• Hint<br />
Displays a Hint when the mouse cursor passes over the Grid Object<br />
There are four (4) buttons in the middle of the Grid Object - Objects Properties Dialog Box. These are:<br />
• Fonts<br />
When clicked, a Fonts dialog box opens that lets you specify the font settings for Text in the Grid Object<br />
• Columns<br />
When clicked, a Columns dialog box opens that lets configure the Grid columns (e.g. a label, source of<br />
the column, type (text, numeric, etc.), column width, column alignment, input enabled/disabled, function<br />
key shortcut for sorting on the specified column). This dialog box will change somewhat, based on the<br />
Data Source type selected.<br />
• Data<br />
When clicked, a Data dialog box opens that lets you specify the Data Source for the Grid Object. This<br />
dialog box will change, based on the Data Source type selected.<br />
• Advanced<br />
When clicked, an Advanced Dialog box appears allowing you to specify advanced settings for the Grid<br />
Object.<br />
24–2 InduSoft Web Studio
Exercise: Configuring Event Retrieval<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Columns Dialog<br />
The Columns Dialog Box lets you configure the Grid Columns for the Data Source you have selected. The<br />
Columns Dialog Box is slightly different, based on the type of Data Source selected. The different dialog boxes<br />
are shown below.<br />
Columns Dialog Box for Text Files<br />
Columns Dialog Box for Class Tags<br />
Columns Dialog Box for Databases<br />
Settings for the Columns are:<br />
• Column<br />
The ID number used to define the position of the Column in the table.<br />
Note:<br />
• To insert or delete a row in the Column Dialog Box, click the right mouse button on a field and<br />
select Insert Line, Delete Line, Cut, Copy, Paste, or Insert Copied Cells. The ID number will<br />
be automatically updated.<br />
• Label<br />
Used to specify a Title for each column, displayed in the first row of the Grid Object.<br />
Notes:<br />
• A Tag (configured in curly braces) can be used in the Label field to modify during runtime<br />
• If Label is blank (i.e. “”), the width of the column is set to 0 during runtime. This will hide the<br />
column<br />
InduSoft Web Studio 24–3
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Configuring Event Retrieval<br />
• Member (used only for Class Tags)<br />
Specifies the Class Member to be used.<br />
• Field (used only for Databases)<br />
Specifies the name of the Field (Column) in the Database that the Grid Object is linked to.<br />
Notes:<br />
• If the Field is left blank, the Text in the Label Field will be used as the Database Field Name<br />
• You can configure a SQL Statement in the Field. You can also specify a string tag that<br />
contains a SQL Statement. Tags need to be configured between curly braces; e.g. {strTag}<br />
• Type<br />
A combo box that selects the type of interface that will be used in the column. The options are:<br />
Type Description<br />
Text<br />
Displays alphanumeric values<br />
Numeric Displays numeric values<br />
Picture Displays a picture from the data source (*.bmp or *.ico format). The picture<br />
will be automatically resized. CEView only supports *.ico format pictures.<br />
Check box Displays check box interface. If unchecked, value read from the file is 0,<br />
Null or False, otherwise the check box will be checked.<br />
Time Displays a time value in HH:MM:SS format. Only available when Data<br />
Source type is Database.<br />
Date<br />
Displays a date value in MM/DD/YY format. Only available when Data<br />
Source type is Database.<br />
Date/Time Displays a date and time value in MM/DD/YY HH:MM:SS format. Only<br />
available when Data Source type is Database.<br />
Note:<br />
• When using a database as the Data Source, be sure the Type for each column matches the<br />
type of the Field in the database. Otherwise, data may not be properly displayed.<br />
• Width<br />
Specifies the Column width in pixels<br />
• Align<br />
Aligns data in the Column. Options are Left, Right or Center<br />
• Input<br />
When checked, allows the user to enter data in a Column at runtime.<br />
Note:<br />
• If the Data Source is a database or file, you will need to specify a Save trigger (e.g. a Tag) to<br />
save the changes in the Grid Object to the Data Source.<br />
• Key<br />
Used to specify a shortcut key, or key combination, for sorting values in the Column.<br />
• Show ID Column<br />
If checked, shows the ID (number of the row)<br />
24–4 InduSoft Web Studio
Exercise: Configuring Event Retrieval<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
• Allow Sorting Columns<br />
If checked, allows sorting of Column values at runtime, either using the shortcut Key or clicking on the<br />
Label in the first Row<br />
Note:<br />
• This option is disabled if the Show Header option (i.e. show the header row) is not checked.<br />
This option is located in the Advanced Dialog Box.<br />
• Move Up and Move Down<br />
Allows the reordering of display Columns<br />
Note:<br />
• When the Data Source type is set to Class Tag and the Columns dialog is left blank, the Grid<br />
Object displays the values from all Class Members of the Class Tag using the default Column<br />
settings:<br />
Label Name of Class Member<br />
Type Text<br />
Width Minimum size to display name of the Class Member<br />
Align Center<br />
Input Enabled (checked)<br />
Key None<br />
InduSoft Web Studio 24–5
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Configuring Event Retrieval<br />
Data Dialog<br />
The Data Dialog Box allows you to specify the Data Source for the Grid Object. The Data Dialog Box is different<br />
for each type of Data Source. The different dialog boxes are shown below.<br />
Data Source = File Settings<br />
• File<br />
Enter the file name or click the … button to browse for the file. If the file is in the Application Folder, the<br />
Path can be eliminated.<br />
Note:<br />
• File name can be a string Tag configured between curly braces. E.g. {strTag}<br />
• Delimiters.<br />
Specifies the delimiter(s) used in the Data Source file.<br />
24–6 InduSoft Web Studio
Exercise: Configuring Event Retrieval<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Data Source = Class Tag Settings<br />
• Class Tag<br />
Enter the name of the main Class Tag (or Array Class Tag) source.<br />
Notes:<br />
• Specify only the Class Tag name. Do not specify the Class Tag with a Class Member.<br />
• If a Array Class Tag is used, the default index in the Array is 0. Another index can be specified.<br />
• Number of Items<br />
Specifies the number of Array indexes from an Array Class Tag that will be displayed<br />
• View<br />
Enter an <strong>IWS</strong> Tag into this field. When the Tag toggles (changes value), a dialog box will open (at<br />
runtime) that allows the user to show or hide each column or modify the Column position.<br />
Data Source = Database Settings<br />
This option opens the familiar Database Configuration dialog box. See the Chapter on <strong>IWS</strong> Database<br />
Configuration for additional information on how to configure the Database.<br />
Advanced Dialog<br />
When the Advanced button is pressed, an Advanced Dialog Box appears allowing you to specify Advanced<br />
settings for the Grid Object.<br />
The Advanced Dialog Box has several settings. These are:<br />
• User Enable<br />
Enter a Tag or numeric value into this field. If True (0), the User can select different rows of the Grid<br />
Object (by clicking the left mouse button) at runtime, or entering a value in the Row Number field.<br />
InduSoft Web Studio 24–7
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Configuring Event Retrieval<br />
• Selected Values<br />
Enter an Array Tag (and any initial index if other than 0) into this Field. The Array Tag will receive<br />
values from each Column of the selected row. If the values of the Array Tag are changed, the cells in<br />
the Grid Object will be updated.<br />
• Row Number<br />
Enter a Tag in this field. The Grid Object will return the number of the Row currently selected (at<br />
runtime), or the User can enter a positive numeric value to select a Row.<br />
• Reload<br />
Enter a Tag in this field. When the tag toggles, the Grid Object reloads data from the Data Source<br />
specified.<br />
• Condition<br />
This field can be used as a data filter expression (e.g. , or<br />
ColumnX > 200)<br />
Notes:<br />
• You can combine multiple conditions in the Condition field, using the same or different Columns.<br />
• You can use wildcards (* and ) in the Condition field<br />
• You can use a string Tag configured between curly braces, {strTag}, to change filtering conditions<br />
during runtime.<br />
• Column Name is the value specified in the Label field for Text File and Class Tag Data Sources<br />
• Column Name is the value specifed in the Field field for Database Data Sources.<br />
• Print<br />
Enter a Tag in this field. When the Tag value toggles, the (filtered) data in the Grid Object is sent to the<br />
default Printer.<br />
• Number of Rows<br />
Enter a Tag in this field. The Grid Object returns the number of Rows currently available in the Grid<br />
Object from the selected Data Source.<br />
• Save Trigger<br />
Enter a Tag in this field. When the Tag value toggles, the data source (Text File or Database) is<br />
updated with the current values of the Grid Object. Not used when the data source is a Class Tag<br />
(which is automatically updated when a cell in the Grid Object changes value).<br />
• Insert Trigger<br />
Enter a Tag in this field. If the Auto Refresh after Insert Trigger is check box is checked, when the<br />
Tag value toggles, the Database Table will be refreshed. A new row is added to the Table and values<br />
contained in the Array Tag configured in the Inserted Values field will be automatically inserted.<br />
• Inserted Values<br />
Enter an Array Tag in this field. If the Tag in the Insert Trigger field is toggled, the values contained in<br />
the Array Tag will be inserted.<br />
• Save on Data Change<br />
If checked, any change of values in the Grid Object will be updated to the Data Source (Text Files or<br />
Database only) during runtime. Not used when the data source is a Class Tag (which is automatically<br />
updated when a cell in the Grid Object changes value).<br />
• Enable Slider/Resize<br />
If checked, allows a slider to scroll through the Grid Object table during runtime.<br />
24–8 InduSoft Web Studio
Exercise: Configuring Event Retrieval<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
• Conditional Check Box<br />
If checked, the User cannot uncheck a check box used in the Grid Object during runtime unless all<br />
proceeding checkboxes in the same Column are already unchecked.<br />
Notes:<br />
• This option is useful to make a User follow a pre-defined sequence.<br />
• This field is not available when the Data Source is a Class Tag.<br />
• Show Header<br />
When this option is checked, the header of the Grid Object will be shown at runtime.<br />
• Show Grid Lines<br />
When this option is checked, the Grid Lines of the Grid Object will be shown at runtime.<br />
• Ext. Translation<br />
When this option is checked, the text displayed by the Grid Object can be used by the Translation Tool<br />
during runtime to switch to a different language at runtime.<br />
• Disable Tab to navigate through cells<br />
When this option is checked, the User cannot navigate through the cells using the Tab key. Only arrow<br />
keys can be used.<br />
Note:<br />
• This option is used when the Tab key is used to navigate to other Objects (e.g. Text I/O) on the<br />
Screen<br />
• Export<br />
This interface allows you to export data from the Grid Object to a Class Array Tag, regardless of the<br />
Data Source type selected. You must configure the following fields:<br />
Class Tag Specifies the name of the Class Array Tag to be used. Each row of the Grid Object will<br />
be exported to one array index of the Class Array Tag. The initial array index can be<br />
specified, if it is not then a default value of 0 will be used.<br />
Trigger Enter a Tag into this field. When the Tag toggles (changes) value, the data in the Grid<br />
Object is exported to the Class Array Tag configured in the Class Tag field.<br />
.<br />
Note:<br />
• The Export feature is a easy and powerful tool to transfer data between a Data Source (e.g.<br />
Text File or Database) and an <strong>IWS</strong> Class Tag.<br />
• The Grid Object can be hidden (using the visibility field of the Position Dynamic Property or<br />
setting the size to 0 using the Size Dynamic Property). Doing this allows you to take advantage<br />
of the Data Source to Class Tag Export feature while not occupying Screen space.<br />
InduSoft Web Studio 24–9
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Configuring Event Retrieval<br />
24–10 InduSoft Web Studio
Example: Using the Grid Object with Excel<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Example: Using the Grid Object with Excel<br />
The Grid Object allows a InduSoft Web Studio (<strong>IWS</strong>) application to read from and write to database files,<br />
including an Excel file. The Grid Object is just one method of accessing an Excel file using <strong>IWS</strong>. While using a<br />
Grid Object with Excel is straightforward, it does require some care in properly setting up the database and<br />
making sure columns are of the same type.<br />
Notes:<br />
• When using the Grid Object, make sure the Excel file exists in its specified location.<br />
• If <strong>IWS</strong> and a 3 rd party program both are accessing the Excel database file at the same time and the 3 rd<br />
party program changes a value in the database, the changed cell is not updated in the Grid Object. The<br />
Grid Object will no longer update this cell for reading or writing purposes.<br />
Example Database: “Production Schedule.xls”. This is an Excel database that contains a production build<br />
schedule that will be viewed by a Grid Object.<br />
Column 1 [A] heading: “Production Date”, format: mm/dd/yy<br />
Column 2 [B] heading “Customer”, format: text<br />
Column 3 [C] heading “Product”, format: text<br />
Column 4 [D] heading “Order Quantity”, format: numeric, no decimals<br />
Column 5 [E] heading “Production Start”, format: mm/dd/yy hh:mm:ss (custom)<br />
Column 6 [F] heading “Quantity Built”, format: numeric, no decimals<br />
Column 7 [G] heading “Production End”, format: mm/dd/yy hh:mm:ss (custom)<br />
InduSoft Web Studio 24–11
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Example: Using the Grid Object with Excel<br />
The following steps will configure the database from the Grid Object.<br />
Step 1 – Open the Indusoft Web Studio engineering environment and insert a grid object onto a display screen.<br />
First select (click) the Grid Object Tool and then place a Grid Object in the screen display worksheet. Don’t<br />
worry about the size, it will be adjusted later.<br />
Step 1a: Select<br />
Grid Object Tool<br />
Step 1b: Position<br />
Grid Object on the<br />
screen<br />
Step 2a: Double<br />
click the Grid<br />
Object.<br />
Step 2 – Double click on the Grid Object. In the Object Properties dialog box, select Database as the Data<br />
Source. Next, click on the Data button to get the Database Configuration dialog box. Make sure the database is<br />
set to primary and the Use application default box is unchecked.<br />
Step 2b: Select<br />
Database as the<br />
Data Source<br />
Step 2c: Click<br />
on Data button<br />
to configure the<br />
database<br />
Step 2d: Make sure<br />
the Use application<br />
default box is<br />
unchecked.<br />
Step 2e: Click on the<br />
browse button of the<br />
connection string<br />
24–12 InduSoft Web Studio
Example: Using the Grid Object with Excel<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Step 3 – Once you click on the browse button of the connection string, you will be need to setup various<br />
parameters that define the link between <strong>IWS</strong> and the database. Note the tabs on top to access various setup<br />
parameters. The first step is to define the database Provider for Excel. In this case, Excel uses the Microsoft Jet<br />
database engine and OLE-DB is the Data Provider. Select Microsoft Jet 4.0 OLE DB Provider and click next.<br />
Step 3: Select Microsoft Jet 4.0 OLE DB Provider.<br />
Then click next.<br />
Step 4b: click on the browse<br />
button of the database name.<br />
Step 4a: Define a user name and<br />
any password associated with the<br />
file. User name Admin with no<br />
password is the default.<br />
Step 4 – The next step is to define any user name and<br />
password associated with the file, then select the file that<br />
contains the database by clicking on the browse button.<br />
Step 5 – Select the Excel file from the appropriate<br />
directory.<br />
Step 5: Select your Excel<br />
database file from the appropriate<br />
directory. Click on the file name<br />
then click on Open.<br />
Note<br />
• Be sure to select All Files in the dropdown<br />
list of file types, otherwise only<br />
Microsoft Access files (*.MDB) will be<br />
shown<br />
InduSoft Web Studio 24–13
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Example: Using the Grid Object with Excel<br />
After the file has been opened, the filename and path will be in<br />
the database name field. The length of this field will depend on<br />
the path name.<br />
Note<br />
• Do not click on Test Connection at this time.<br />
There is one more step to be completed, then<br />
the Test Connection can be used. This can be<br />
done after step 6d.<br />
Step 6 – Click on the All tab in the Data Link Properties. This dialog box allows users to further define the Jet-<br />
OLE DB properties. The Extended Properties needs to be set to Excel 8.0, which supports the current version of<br />
Microsoft Excel 2003.<br />
Step 6a: Click on<br />
All tab<br />
Step 6b: Click on<br />
Extended Properties<br />
Step 6d: Enter Excel<br />
8.0 and click OK<br />
Step 6c: Click on the<br />
Edit Value button<br />
24–14 InduSoft Web Studio
Example: Using the Grid Object with Excel<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Step 6e: The connection between <strong>IWS</strong> and the<br />
database is now complete. Now, you can<br />
either:<br />
a) Test the connection by ckicking on the<br />
Connection tab, then press the Test<br />
Connection button. Then,<br />
b) Click OK to finish setting up Data Link<br />
properties<br />
Once Step 6e is completed, you have completed the data connection to the database. There is still one more<br />
step in the configuration, but the link to the database is complete. At this point, the connection string as shown in<br />
the Database Configuration dialog box (see dialog box under Step 2) will look something like this:<br />
Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\production schedule.xls; Extended Properties="Excel 8.0"<br />
The Data Source defines the path to your Excel database file, so this will vary according to the location of the<br />
files in your system.<br />
The file name can be defined using an <strong>IWS</strong> tag (type string) instead of a pre-defined path. This allows the <strong>IWS</strong><br />
application to specify a file. [Check this, what happens if change] The tag name must be enclosed in braces,<br />
i.e. {tag}.<br />
The Extended Property value that was set to Excel 8.0 allows access to Excel 2000, 2002 and 2003 files. The<br />
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<br />
header row, you need to put Excel 8.0;hdr=no into the Extended Properties field. The resultant connection string<br />
would appear similar to:<br />
Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\production schedule.xls; Extended Properties="Excel 8.0;<br />
hdr=no"<br />
Note:<br />
• The file name or entire path can be predefined or be an <strong>IWS</strong> tag<br />
InduSoft Web Studio 24–15
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Example: Using the Grid Object with Excel<br />
Step 7 – The final step in setting up the database interface for the Grid Object is to specify the Worksheet inside<br />
of the Excel database that is to be used.<br />
Step 7a: Enter the Worksheet name in<br />
the Excel database.<br />
Follow the example shown, i.e. the<br />
worksheet name is followed by a $, and<br />
the name with the $ is enclosed in<br />
square brackets. If you do not follow this<br />
format, you will get an error when<br />
accessing the Excel database.<br />
As mentioned in Step 6, you can used <strong>IWS</strong> tags (type string) to define the Excel Worksheet. If you plan to do<br />
this, be sure to enclose the tag name in curly braces, i.e. {tag}.<br />
Next Steps<br />
The next steps involve setting up the Columns and any Advanced Settings. See previous section.<br />
24–16 InduSoft Web Studio
Example: Using the Grid Object with Excel<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Notes<br />
InduSoft Web Studio 24–17
Chapter 25.<br />
VBScript<br />
Visual Basic Script Language (VBScript) is one of Microsoft’s scripting languages that is commonly associated<br />
with Server-side and Client-side web applications. However, Microsoft has opened up VBScript to developers<br />
and now VBScript can be found in a variety of applications. InduSoft has standardized on VBScript since it<br />
provides a significant subset of Microsoft Visual Basic’s functionality, and VBScript supports all of Microsoft’s<br />
operating system platforms including Windows CE, unlike VBA (Visual Basic for Applications) which cannot<br />
support the Windows CE runtime environment.<br />
VBScript is a programming language that is often viewed as a dialect of VBA (Visual Basic for Applications),<br />
although it is really its own language. The VBScript language attempts to balance flexibility, capability and ease<br />
of use. VBA is a subset of Visual Basic that was developed to automate Microsoft Office applications, whereas<br />
VBScript was originally developed to support Server-side and Client-side web applications. Although VBScript<br />
and VBA provide many of the same features, there are some differences between them, primarily due to the<br />
applications they were each developed to support.<br />
Using VBScript With InduSoft HMI/SCADA Applications<br />
InduSoft Web Studio (<strong>IWS</strong>) supports both the <strong>IWS</strong> Scripting Language (proprietary Scripting Language)<br />
using one or more Math worksheets, as well as VBScript (<strong>IWS</strong> Version 6.1 or later). Developers can use<br />
either scripting language or a combination of both. VBScript code is placed in one of several modules,<br />
based on the functionality to be performed and the scope of the code and its variables. This subject is<br />
covered more completely in the VBScript Configuration and Operation in <strong>IWS</strong> section.<br />
Examples of how VBScript can be used:<br />
• Execute a logic sequence or routine when opening or closing a screen, or while the screen is open<br />
• Execute a logic sequence in the background<br />
• Run a simple VBScipt code segment based on an <strong>IWS</strong> object’s command dynamic<br />
• Interaction with <strong>IWS</strong> Tags and control of <strong>IWS</strong> built-in functions<br />
• Manipulation of ActiveX Controls and ActiveX Control event handler<br />
• Simple file I/O (e.g. text files)<br />
• Database interfaces (e.g. via ADO.NET), especially where use of SQL is required<br />
• Interface to Windows Management Instrumentation (WMI) and Web Services (via WSDL)<br />
• Interface to Microsoft Office applications (e.g. Excel, Access, Word) and Microsoft Office<br />
components via OLE <strong>Automation</strong><br />
• Run on a Web Thin Client<br />
Where you should use <strong>IWS</strong> instead of VBScript<br />
• User Interface. <strong>IWS</strong> does not support Windows Scripting, which typically provides the User Interface<br />
for VBScript via Forms.<br />
• Device I/O (e.g. PLC communications). VBScript does not directly support serial or network<br />
communications. However, ActiveX Controls can be used.<br />
<strong>IWS</strong> implements Visual Basic Script Edition 5.6 or higher, and functions as the “host” for VBScript. <strong>IWS</strong><br />
provides an integrated development environment where the HMI/SCADA application developer can take<br />
advantage of the functionality and ease of use of VBScript, yet have access to all <strong>IWS</strong> tags and all built-in<br />
functions directly from VBScript. The diagram below illustrates the <strong>IWS</strong> architecture. Since VBScript is an<br />
interpreted language, the VBScript Engine parses the language at runtime and executes commands subject to<br />
InduSoft Web Studio 25–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
VBScript Limitations in <strong>IWS</strong><br />
limitations placed by the VBScript Host. InduSoft allows VBScript code to be located several areas in an <strong>IWS</strong><br />
application:<br />
• Global Procedures. This is an area for subroutines and functions that can be called by any other<br />
VBScript routine, or by a built-in <strong>IWS</strong> function (requires <strong>IWS</strong> Version 6.1 Service Pack 1 or later).<br />
• Graphic Script. Code in this area gets executed whenever any graphics (screens) are active.<br />
• Screen Script. This is where code is executed when an individual screen is active.<br />
• Command Dynamic. When an object has a Command Dynamic, one option is to run VBScript code.<br />
• ActiveX Events. A VBScript code segment can be run based on an ActiveX event<br />
• Background Task. VBScript code can be running as a background task. One or more VBScript groups<br />
are supported, allowing conditional processing of the various VBScript background tasks.<br />
In a Web Thin Client configuration, VBScripts associated with a screen can run either on the workstation<br />
runtime display or on a Web Thin Client station running Microsoft Internet Explorer. The VBScript routines that<br />
can execute on a Web Thin Client include those located in a Screen Script, a Command Dynamic, and an<br />
ActiveX Event. Since VBScript runs on all Microsoft operating system platforms, there are no limitations to<br />
VBScript running on any Microsoft compatible platform.<br />
VBScript Limitations in <strong>IWS</strong><br />
Microsoft initially developed VBScript to work with websites (web pages). In the web server environment,<br />
VBScript was designed to work with the Windows Scripting host and ASP, which provide file access and form<br />
generation. On the web client side, VBScript was designed to work with Microsoft Internet Explorer using HTML<br />
and DHTML, which provide display generation. So as a result of the initial design goals, VBScript does not have<br />
much in the way of built-in language support for Forms, File I/O, Communications or direct Printing control.<br />
Additionally, <strong>IWS</strong> has its own built-in web server and does not use ASP.<br />
By using <strong>IWS</strong> built-in functions, ActiveX controls and Microsoft Office Applications (or components), there are<br />
several methods for workarounds to these limitations as well as to extend VBScript’s capability.<br />
The following are some of VBScript’s limitations and workarounds.<br />
Item VBScript Workarounds<br />
Forms Does not support Use <strong>IWS</strong> objects for user interface, pass<br />
parameters to <strong>IWS</strong>. Can also use ActiveX<br />
Controls.<br />
File I/O Limited support directly Use Scripting Objects and/or <strong>IWS</strong> built-in<br />
functions. Can also use ActiveX Controls.<br />
Communications Does not directly support Use <strong>IWS</strong> built-in functions or 3 rd party ActiveX<br />
controls<br />
Printing Does not directly support Use Microsoft Office Applications or <strong>IWS</strong> built-in<br />
functions<br />
Charting/Graphing Does not directly support<br />
Use <strong>IWS</strong> trending, Microsoft Office Applications,<br />
Microsoft Office Components, or 3 rd party<br />
ActiveX controls<br />
DDE Does not support Supported in <strong>IWS</strong> built-in commands (not under<br />
Windows CE).<br />
25–2 InduSoft Web Studio
Differences between VBScript and VBA<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Differences between VBScript and VBA<br />
Since other HMI/SCADA products support VBA, it might be worth highlighting some of the key differences<br />
between VBScript and VBA. For HMI/SCADA applications, these differences are relatively minor. However,<br />
VBScript support for the Windows CE operating system is a major differentiator between the two products. For<br />
additional details or a complete listing of the differences, please reference the MSDN website at<br />
http://msdn.microsoft.com.<br />
Key differences between VBScript vs. VBA<br />
Item VBA VBScript<br />
Primary Purpose<br />
<strong>Automation</strong> of MS Office<br />
<strong>Automation</strong> of Web Services<br />
Applications<br />
Support for Windows CE No Yes<br />
Data Types<br />
Stronger Type Declaration. Many<br />
data types supported. (e.g. String,<br />
Integer, Date, Boolean)<br />
Typeless, uses Variant Type. The final<br />
data subtype will be determined at<br />
runtime based on use. Supports same<br />
data subtypes as VBA and VB (e.g.<br />
String, Integer, Date, Boolean, etc)<br />
Dimension Statement Dim Var as Type Dim Var<br />
(Cannot specify Type, but it is<br />
determined at runtime based on use)<br />
Class Block declaration Must use separate Class Module Class Block Declaration supported<br />
Object<br />
Clipboard<br />
Not supported<br />
Collection<br />
Object Manipulation TypeOf Not supported<br />
Eval function Not supported Expression evaluation supported<br />
Execute function Not supported Allows interpreted code to be executed<br />
on the fly.<br />
RegExp No Allows creation of regular expressions<br />
Error Handling Several different types Supported but more limited<br />
Arrays Lower bound can be 0 Lower bound is 0<br />
File I/O Supported Not directly supported but VBScript can<br />
use FileSystemObject and can access<br />
<strong>IWS</strong> built-in I/O functions<br />
DDE Supported Not supported<br />
Financial functions Supported Not supported<br />
Strings Fixed length strings Variable length only<br />
Debugging Debug, Print, End, Stop Use MsgBox or <strong>IWS</strong> built-in functions<br />
Line labels Supported Not supported<br />
InduSoft Web Studio 25–3
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
VBScript Language Overview<br />
VBScript Language Overview<br />
This section contains a short summary of the VBScript Language. A more complete reference of the VBScript<br />
language can be found in VBScript Reference Manual.<br />
VBScript Functionality<br />
VBScript has inherited much of VB & VBA’s functionality including support for math operations, string<br />
manipulation, arrays, flow control, data conversion, procedures, COM objects, and date/time functions. Since<br />
VBScript was initially designed for Web applications, direct support for file I/O and user interface functions was<br />
not included. However, in a Windows XP/2000/NT/Server 2003/Vista environment, VBScript can use the<br />
FileSystemObject COM object (scrrun.dll) to manipulate local files and folders.<br />
VBScript does not support explicitly declared data types. This was eliminated to speed up the runtime<br />
performance of the VBScript Scripting Engine. All variables are type Variant and their subtype (e.g. Integer,<br />
Real, etc.) is determined at runtime.<br />
VBScript Elements<br />
There are several VBScript elements, but the most important ones are variables, constants and<br />
types. A variable is an item holding data that can change during the execution of the VBScript<br />
program. A constant is an item that holds data but cannot change during the execution of the<br />
VBScript program. The data that variables and constants hold can be classified into types.<br />
Note that with <strong>IWS</strong>, you can check the VBScript syntax for errors by choosing the Check VBScript<br />
command (right mouse click when in a VBScript interface). VBScript is always checked when saving<br />
the Script interface.<br />
The Check Script function can<br />
be invoked following a right<br />
mouse click when the cursor is<br />
on the VBScript Interface. Note<br />
that Comments are in Green,<br />
VBScript Functions and<br />
KeyWords are in Blue,<br />
Variables are in Black<br />
The VBScript elements include:<br />
• Variables (Type, Declaration, Scope)<br />
• Constants (Explicit, Implicit)<br />
• Keywords<br />
• Errors (Runtime, Syntax)<br />
• Operators<br />
• Functions and Procedures<br />
• Statements<br />
• Objects and Collections<br />
25–4 InduSoft Web Studio
Variable Data Types and Subtypes<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Variable Data Types and Subtypes<br />
All variables in VBScript are a data type called Variant. This means that you do not (and cannot) explicitly<br />
declare the variable type. In fact, with VBScript you do not need the Dim statement to allocate storage for a<br />
variable. At runtime, the Parser in the VBScript Scripting Engine determines the Variant data subtype to be<br />
used. These correspond to the more traditional classifications of data types (see chart below).<br />
Variant data subtypes<br />
Subtype Description<br />
Boolean Either True or False<br />
Byte Contains integer in the range 0 to 255<br />
Currency Floating-point number in the range -922,337,203,685,477.5808 to<br />
922,337,203,685,477.5807<br />
Date(Time) Contains a number that represents a date between January 1, 100 to December 31, 9999<br />
Double Contains a double-precision, floating-point number in the range -1.79769313486232E308 to<br />
-4.94065645841247E-324 for negative values; 4.94065645841247E-324 to<br />
1.79769313486232E308 for positive values<br />
Empty Uninitialized Variant<br />
Error Contains an error number used with runtime errors<br />
Integer Contains integer in the range -32,768 to 32,767<br />
Long Contains integer in the range -2,147,483,648 to 2,147,483,647<br />
Null A variant containing no valid data<br />
Object Contains an object reference<br />
Single Contains a single-precision, floating-point number in the range -3.402823E38 to -<br />
1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values<br />
String Contains a variable-length string that can be up to approximately 2 billion characters in<br />
length.<br />
The Parser’s choice of data subtype will depend on how the variable is used in a statement or function. Note<br />
that a variable’s subtype can change within a code segment.<br />
Data Subtype Identification<br />
If it is important to determine the Variant data subtype used at runtime, you may use any of the three<br />
categories of functions to determine the data subtype:<br />
• The VarType(variable) function which returns a code based on the Variant data subtype used<br />
• Various IsXxxx(variable) functions which return boolean values indicating whether the variable is of a<br />
specific data subtype.<br />
• A TypeName(variable) function which returns a string based indicating the data subtype<br />
Example:<br />
If varType(a) = vbInteger Then<br />
Msgbox “a is an Integer”<br />
EndIf<br />
InduSoft Web Studio 25–5
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Data Subtype Conversion<br />
Data Subtype Conversion<br />
VBScript provides several functions that convert a variable from one data subtype to another. Since VBScript<br />
uses the Variant data type, these functions are not generally required. However, when passing data between<br />
<strong>IWS</strong> (or CEView) and VBScipt, or calling built-in <strong>IWS</strong> functions from VBScript where variables need to be put<br />
into the proper argument format, these VBScript data subtype conversion functions can be very useful.<br />
Example: a = 4.2<br />
b = cInt (a) ‘ b is an Integer with a value of 4<br />
Variable Naming Rules & Conventions<br />
VBScript has four primary rules for naming. These are:<br />
1. Variable names must begin with an alpha character (a..z, A...Z) or an underscore character<br />
2. After the first character, the variable name can contain letters, digits and underscores<br />
3. Variable names must be less than 255 characters in length<br />
4. The variable name must be unique in the scope in which they are declared<br />
VBScript variable names are not case sensitive. Microsoft recommends following their naming convention for<br />
variables, which puts attaches different prefixes to the variable name based on the data subtype.<br />
Variable Scope<br />
Variables have “scope” which defines a variable’s visibility or accessibility from one procedure (or VBScript<br />
Interface) to another, which is principally determined by where you declare the variable. Generally, when you<br />
declare a variable within a procedure, only code within that procedure can access or change the value of that<br />
variable. This is called local scope and is for a procedure-level variable.<br />
If you declare a variable outside a procedure, you make it recognizable to all the procedures in your Script. This<br />
is a Script-level variable, and it has Script-level scope. However, as previously noted, InduSoft enforces certain<br />
restrictions on the scope of Variables and Procedures.<br />
25–6 InduSoft Web Studio
VBScript Constants<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
VBScript Constants<br />
VBScript supports both explicit and implicit constants. Constants should never be used as variable names.<br />
Explicit constants are defined by the programmer. Explicit constants have a defined value which, unlike a<br />
variable, is not allowed to change during the life of the script.<br />
Implicit constants are pre-defined by VBScript. VBScript implicit constants usually begin with a vb prefix.<br />
VBScript implicit constants are available to the VBScript programmer without having to define them. Other<br />
objects, such as those used by ADO.NET, also have implicit constants predefined, usually with different<br />
prefixes. However, the implicit constants for these objects may not be know to VBScript and if not, will have to<br />
be defined as an explicit constant.<br />
VBScript defines the following categories of implicit Constants:<br />
Intrinsic Constant Category<br />
Color Constants<br />
Comparison Constants<br />
Date and Time Constants<br />
Date Format Constants<br />
Days of Week Constants<br />
New Years Week Constants<br />
Error Constants<br />
VBScript Runtime Errors<br />
VBScript Syntax Errors<br />
Intrinsic Constant Category<br />
File Attribute Constants<br />
File Input/Output Constants<br />
MsgBox Constants<br />
MsgBox Function Constants<br />
SpecialFolder Constants<br />
String Constants<br />
Tristate Constants<br />
VarType Constants<br />
Locale ID (LCID)<br />
Declaring VBScript Variables and Constants<br />
VBScript does not require the explicit declaration of scalar variables, i.e. those variables with only one value<br />
assigned at any given time. Arrays, Objects (except Err) and Constants must be declared. While it may initially<br />
be convenient not to declare variables, any typing (spelling) errors of the variable or constant names may<br />
produce unexpected results at runtime.<br />
VBScript Keywords<br />
VBScript has many keywords. Keywords are merely the names or symbols used with built-in VBScript functions.<br />
Keywords are reserved, i.e. they may not be used by the programmer as names of variables or constants.<br />
VBScript keywords can be grouped into categories which include:<br />
• Constants & Literals<br />
• Operators<br />
• Functions<br />
• Statements<br />
• Objects<br />
InduSoft Web Studio 25–7
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Operators<br />
Operators<br />
VBScript defines various operators that perform operations based on the Variant subdata type(s). Arithmetic<br />
operators are used to perform operations on two or more numbers.<br />
Arithmetic<br />
Symbol Definition<br />
+ Add<br />
- Subtract<br />
* Multiply<br />
/ Divide<br />
\ Integer Divide<br />
^ Exponentiation<br />
MOD Modulus Division<br />
Comparison<br />
Symbol Definition<br />
< Less than<br />
Greater than<br />
>= Greater than or equal<br />
= Equal or assignment<br />
Not equal<br />
Logical<br />
Symbol<br />
AND<br />
OR, |<br />
XOR<br />
Eqv<br />
Imp<br />
Not<br />
Definition<br />
And<br />
Or<br />
Exclusive OR<br />
Equivalence<br />
Implication<br />
NOT<br />
String<br />
Symbol<br />
&, +<br />
Definition<br />
Concatenation<br />
Object<br />
Symbol<br />
Is<br />
Definition<br />
Is (compare)<br />
<strong>IWS</strong><br />
Symbol Definition<br />
$ Access to <strong>IWS</strong> Tags and Built-in functions<br />
25–8 InduSoft Web Studio
Operator Precedence<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Operator Precedence<br />
When several operations occur in an expression, each part is evaluated and resolved in a predetermined order<br />
called operator precedence. Parentheses can be used to override the order of precedence and force some<br />
parts of an expression to be evaluated before other parts. Operations within parentheses are always performed<br />
before those outside. Within parentheses, however, normal operator precedence is maintained.<br />
When expressions contain operators from more than one category, arithmetic operators are evaluated first,<br />
comparison operators are evaluated next, and logical operators are evaluated last. Comparison operators all<br />
have equal precedence; that is, they are evaluated in the left-to-right order in which they appear. Arithmetic and<br />
logical operators are evaluated in the following order of precedence:<br />
When multiplication and division occur together in an expression, each operation is evaluated as it occurs from<br />
left to right. Likewise, when addition and subtraction occur together in an expression, each operation is<br />
evaluated in order of appearance from left to right.<br />
The string concatenation operator (&) is not an arithmetic operator, but its precedence does fall in after all<br />
arithmetic operators and before all comparison operators. The Is operator is an object reference comparison<br />
operator. It does not compare objects or their values; it only checks to determine if two object references refer<br />
to the same object.<br />
Operator Precedence<br />
Arithmetic Comparison Logical<br />
Negation (-) Equality (=) Not<br />
Exponentiation (^) Inequality () And<br />
Multiplication and division (*, /) Less than () Xor<br />
Modulus arithmetic (Mod) Less than or equal to (=) Imp<br />
String concatenation (&, +) Is &<br />
InduSoft Web Studio 25–9
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Functions<br />
Functions<br />
VBScript contains a number of built-in functions (not to be confused with the Function Procedure). These<br />
functions may or may not have arguments. These functions are called in a statement and may return a result<br />
that can be assigned to a variable. VBScript’s functions are grouped as follows:<br />
Array Functions<br />
Array<br />
Functions<br />
Array<br />
Filter<br />
IsArray<br />
Join<br />
LBound<br />
Split<br />
UBound<br />
Description<br />
Returns a variant containing an array<br />
Returns a zero-based array that contains a subset of a string array based on a<br />
filter criteria<br />
Returns a Boolean value that indicates whether a specified variable is an array<br />
Returns a string that consists of a number of substrings in an array<br />
Returns the smallest subscript for the indicated dimension of an array<br />
Returns a zero-based, one-dimensional array that contains a specified number<br />
of substrings<br />
Returns the largest subscript for the indicated dimension of an array<br />
Data Conversion Functions<br />
Function Description<br />
Abs Returns the absolute value of a specified number<br />
Asc Converts the first letter in a string to its ASCII decimal representation<br />
CBool Converts an expression to a variant of subtype Boolean<br />
CByte Converts an expression to a variant of subtype Byte<br />
CCur Converts an expression to a variant of subtype Currency<br />
CDate Converts a valid date and time expression to the variant of subtype Date<br />
CDbl Converts an expression to a variant of subtype Double<br />
Chr Converts the specified ANSI code to a character<br />
CInt Converts an expression to a variant of subtype Integer<br />
CLng Converts an expression to a variant of subtype Long<br />
CSng Converts an expression to a variant of subtype Single<br />
CStr Converts an expression to a variant of subtype String<br />
Fix Returns the integer part of a specified number<br />
Hex Returns the hexadecimal value of a specified number<br />
Int Returns the integer part of a specified number<br />
Oct Returns the octal value of a specified number<br />
Round Returns a rounded number<br />
Sgn Returns the integer portion of a number<br />
25–10 InduSoft Web Studio
Functions<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Date and Time Functions<br />
Function Description<br />
CDate<br />
Converts a valid date and time expression to the variant of subtype Date<br />
Date<br />
Returns the current system date<br />
DateAdd Returns a date to which a specified time interval has been added<br />
DateDiff Returns the number of intervals between two dates<br />
DatePart Returns the specified part of a given date<br />
DateSerial Returns the date for a specified year, month, and day<br />
DateValue Returns a date<br />
Day<br />
Returns a number that represents the day of the month (between 1 and 31, inclusive)<br />
FormatDateTime Returns an expression formatted as a date or time<br />
Hour<br />
Returns a number that represents the hour of the day (between 0 and 23, inclusive)<br />
IsDate<br />
Returns a Boolean value that indicates if the evaluated expression can be converted to a<br />
date<br />
Minute<br />
Returns a number that represents the minute of the hour (between 0 and 59, inclusive)<br />
Month<br />
Returns a number that represents the month of the year (between 1 and 12, inclusive)<br />
MonthName Returns the name of a specified month<br />
Now<br />
Returns the current system date and time<br />
Second Returns a number that represents the second of the minute (between 0 and 59, inclusive)<br />
Time<br />
Returns the current system time<br />
Timer<br />
Returns the number of seconds since 12:00 AM<br />
TimeSerial Returns the time for a specific hour, minute, and second<br />
TimeValue Returns a time<br />
Weekday Returns a number that represents the day of the week (between 1 and 7, inclusive)<br />
WeekdayName Returns the weekday name of a specified day of the week<br />
Year<br />
Returns a number that represents the year<br />
Expression Functions<br />
Expressions Description<br />
Eval<br />
Evaluates an expression and returns the result<br />
RegExp<br />
Provides simple regular expression support.<br />
Format Functions<br />
Function Description<br />
FormatCurrency Returns an expression formatted as a currency value<br />
FormatDateTime Returns an expression formatted as a date or time<br />
FormatNumber Returns an expression formatted as a number<br />
FormatPercent Returns an expression formatted as a percentage<br />
I/O Functions<br />
Input/Output<br />
InputBox<br />
MsgBox<br />
LoadPicture<br />
Description<br />
Displays a prompt in a dialog box, waits for the user to input text or click a button, and<br />
returns the contents of the text box.<br />
Displays a message in a dialog box, waits for the user to click a button, and returns a<br />
value indicating which button the user clicked.<br />
Returns a picture object<br />
InduSoft Web Studio 25–11
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Functions<br />
Math Functions<br />
Function Description<br />
Abs Returns the absolute value of a specified number<br />
Atn Returns the arctangent of a specified number<br />
Cos Returns the cosine of a specified number (angle)<br />
Exp Returns e raised to a power<br />
Hex Returns the hexadecimal value of a specified number<br />
Int Returns the integer part of a specified number<br />
Fix Returns the integer part of a specified number<br />
Log Returns the natural logarithm of a specified number<br />
Oct Returns the octal value of a specified number<br />
Randomize Initializes the random-number generator<br />
Rnd Returns a random number less than 1 but greater or equal to 0<br />
Sgn Returns an integer that indicates the sign of a specified number<br />
Sin Returns the sine of a specified number (angle)<br />
Sqr Returns the square root of a specified number<br />
Tan Returns the tangent of a specified number (angle)<br />
Miscellaneous Functions<br />
Miscellaneous Description<br />
GetLocale Returns the current locale ID<br />
RGB<br />
Returns a whole number representing an RGB color value<br />
SetLocale Sets the current locale ID<br />
Script Engine Functions<br />
Script Engine ID<br />
ScriptEngine<br />
ScriptEngineBuildVersion<br />
ScriptEngineMajorVersion<br />
ScriptEngineMinorVersion<br />
Description<br />
Returns a string representing the scripting language in use<br />
Returns the build version number of the scripting engine in use<br />
Returns the major version number of the scripting engine in use<br />
Returns the minor version number of the scripting engine in use<br />
String Functions<br />
Function Description<br />
InStr Returns the position of the first occurrence of one string within another. The search begins at<br />
the first character of the string<br />
InStrRev Returns the position of the first occurrence of one string within another. The search begins at<br />
the last character of the string<br />
LCase Converts a specified string to lowercase<br />
Left Returns a specified number of characters from the left side of a string<br />
Len Returns the number of characters in a string<br />
LTrim Removes spaces on the left side of a string<br />
Mid Returns a specified number of characters from a string<br />
Replace Replaces a specified part of a string with another string a specified number of times<br />
Right Returns a specified number of characters from the right side of a string<br />
RTrim Removes spaces on the right side of a string<br />
Space Returns a string that consists of a specified number of spaces<br />
StrComp Compares two strings and returns a value that represents the result of the comparison<br />
String Returns a string that contains a repeating character of a specified length<br />
StrReverse Reverses a string<br />
Trim Removes spaces on both the left and the right side of a string<br />
UCase Converts a specified string to uppercase<br />
25–12 InduSoft Web Studio
Functions<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Variant Identification Functions<br />
Variant Description<br />
Function<br />
IsArray Returns a Boolean value indicating whether a variable is an array<br />
IsDate<br />
Returns a Boolean value indicating whether an expression can be converted to a date<br />
IsEmpty Returns a Boolean value indicating whether a variable has been initialized.<br />
IsNull<br />
Returns a Boolean value that indicates whether an expression contains no valid data<br />
(Null).<br />
IsNumeric Returns a Boolean value indicating whether an expression can be evaluated as a number<br />
IsObject Returns a Boolean value indicating whether an expression refers to a valid <strong>Automation</strong><br />
object.<br />
TypeName Returns a string that provides Variant subtype information about a variable<br />
VarType Returns a value indicating the subtype of a variable<br />
InduSoft Web Studio 25–13
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Statements<br />
Statements<br />
VBScript statements are used to perform fundamental operations such as decision making, repetition (looping)<br />
and assignments. Statements combined with Operators are the building blocks for more complex code.<br />
Multiple statements can appear on the same line as long as they are separated by a colon (:). For purposes of<br />
code readability, it is recommended to use one statement per line.<br />
Assignment Statements<br />
Many of VBScripts assignment statements have already been covered. For consistency purposes, they are<br />
listed here. Refer to the VBScript Users Manual for a more detailed description of their use.<br />
Assignment Statements<br />
Statement Description<br />
Const<br />
Declares constants for use in place of literal values<br />
Dim<br />
Declares variables and allocates storage space<br />
Erase<br />
Reinitializes the elements of fixed-size arrays, deallocates dynamic-array storage space.<br />
Option Explicit Forces explicit declaration of all variables in the script<br />
Private<br />
Declares private variables and allocates storage space<br />
Public<br />
Declares public variables and allocates storage space<br />
ReDim<br />
Declare dynamic array variables, allocates or reallocates storage space at procedural<br />
level<br />
Comment Statements<br />
Comment statements are used to provide documentation comments with the code.<br />
Comment Statements<br />
Comments Description<br />
Rem<br />
Includes explanatory remarks in a program<br />
‘ Includes explanatory remarks in a program (single quote)<br />
25–14 InduSoft Web Studio
Statements<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Control Flow Statements<br />
By default, VBScript sequentially moves (flows) through the script from statement to statement. As is typical<br />
with virtually all high-level programming languages, control flow statements can alter this flow by branching to<br />
other code sections based upon logic conditions, inputs, errors, etc.<br />
One of the most commonly used control flow statement is the If..Then..Else statement. This control flow<br />
statement takes the following format:<br />
{simple format} If condition Then statement(s) [Else elsestatement(s) ]<br />
{block format}<br />
If condition Then<br />
[statement(s)]<br />
[ElseIf condition-n Then<br />
[elseifstatement(s)]] . . .<br />
[Else<br />
[elsestatement(s)]]<br />
End If<br />
The condition can be a boolean constant or boolean variable, or a numeric or string expression that evaluates<br />
to True or False.<br />
Refer to the Appendix for a detail description of these functions.<br />
Control Flow Statements<br />
Function Description<br />
Do…Loop Repeats a block of statements while a condition is True or until a condition becomes True<br />
Execute Executes one or more specified statements<br />
Execute Global Executes one or more specified statements in the global namespace of a script<br />
Exit Do Exit a Do Loop Function. Transfers control to the statement following the Loop statement.<br />
Exit For Exit a For Loop Function (For…Next or For Each…Next loop). Transfers control to the<br />
statement following the Next statement.<br />
For...Next Repeats a group of statements a specified number of times<br />
For Each…Next Repeats a group of statements for each element in an array or collection<br />
If…Then…Else Conditionally executes a group of statements, depending on the value of an expression<br />
Select Case Executes one of several groups of statements, depending on the value of an expression<br />
While…Wend Executes a series of statements as long as a given condition is True<br />
With…End Executes a series of statements on a single object<br />
With<br />
InduSoft Web Studio 25–15
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Statements<br />
Procedure Statements<br />
There are two types of procedure statements; the Sub procedure and the Function procedure. Both of these<br />
procedure statements are intended to encapsulate a set of statements that provide functionality that can be<br />
repeatedly called, but the difference between the two is how arguments are passed and results returned.<br />
The Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub statements) that perform<br />
actions but don't return a value as part of the Sub name. A Sub procedure can take arguments (constants,<br />
variables, or expressions that are passed by a calling procedure). A resultant value or set of values can be<br />
returned through the arguments. If a Sub procedure has no arguments, its Sub statement must include an<br />
empty set of parentheses ().<br />
The Function procedure is a series of VBScript statements enclosed by the Function and End Function<br />
statements. A Function procedure is similar to a Sub procedure, but can also return a value in the Function<br />
name. A Function procedure can take arguments (constants, variables, or expressions that are passed to it by<br />
a calling procedure). If a Function procedure has no arguments, its Function statement must include an empty<br />
set of parentheses. A Function returns a value by assigning a value to its name in one or more statements of<br />
the procedure. The return type of a Function is always a Variant.<br />
Procedure Statements<br />
Function Description<br />
Call<br />
Transfers control to a Sub or Function procedure<br />
End Function Immediately exits a Function procedure<br />
End Sub Immediately exits a Sub procedure<br />
Exit Function Exit a Function, generally as a result of a condition<br />
Exit Sub Exit a Subroutine, generally as a result of a condition<br />
Function Declares the name, arguments, and code that form the body of a Function procedure<br />
GetRef Associates an event handler with a specific function<br />
Sub<br />
Declares the name, arguments, and code that form the body of a Sub procedure<br />
(Subroutine).<br />
25–16 InduSoft Web Studio
VBScript Object Commands<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
VBScript Object Commands<br />
VBScript includes several Functions and Statements that can be used to access objects, including their<br />
methods and properties. There are a large variety of objects available to VBScript, including user-defined<br />
objects, intrinsic objects and extrinsic objects.<br />
VBScript Object Functions<br />
Function Description<br />
CreateObject Creates and returns a reference to an <strong>Automation</strong> object<br />
GetObject Returns a reference to an <strong>Automation</strong> object from a file<br />
IsObject Returns a Boolean value indicating whether an expression references a valid<br />
<strong>Automation</strong> object.<br />
Object Statements<br />
Statement<br />
Class<br />
Exit Property<br />
For Each…Next<br />
Property Get<br />
Property Let<br />
Property Set<br />
Set<br />
Description<br />
Declares the name of a class, as well as a definition of the variables, properties,<br />
and methods that comprise the class<br />
Forces an exit from inside a Property Set function.<br />
Repeats a group of statements for each element in an array or a collection.<br />
Declares, in a Class block, the name, arguments, and code that form the body of<br />
a Property procedure that gets (returns) the value of a property<br />
Declares, in a Class block, the name, arguments, and code that form the body of<br />
a Property procedure that assigns (sets) the value of a property<br />
Sets a reference to an object<br />
Assigns an object reference to a variable or property, or associates a procedure<br />
reference with an event. Usually used to instantiate an object.<br />
Error Handling Statements<br />
Statement Description<br />
On Error<br />
Enables or disables error-handling<br />
Object & Collection Summary<br />
Objects & Collections Description<br />
Debug<br />
The Debug object is an intrinsic global object that can send an output to<br />
a script debugger, such as the Microsoft Script Debugger.<br />
Dictionary<br />
An associative array that can store any type of data. Data is accessed<br />
by a key.<br />
Drive<br />
An object that refers to a specific Drive<br />
Drives<br />
A collection of Drive objects.<br />
Err<br />
Contains information about the last run-time error. Accepts the Raise<br />
and Clear methods for generating and clearing run-time errors.<br />
File<br />
An object that refers to a specific File<br />
Files<br />
A collection of File objects.<br />
FileSystemObject An object model used to access the Windows file system<br />
Folder<br />
An object that refers to a specific Folder<br />
Folders<br />
A collection of Folder objects.<br />
Match<br />
Provides access to the read-only properties of a regular expression<br />
match.<br />
Matches<br />
Collection of regular expression Match objects.<br />
RegExp<br />
Provides simple regular expression support.<br />
Submatches<br />
A collection of regular expression submatch strings.<br />
TextStream<br />
An object that refers to a text File<br />
InduSoft Web Studio 25–17
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
VBScript User-Defined Class Objects<br />
VBScript User-Defined Class Objects<br />
To define a user-defined Class Object, you use the Class statement to declare a class. The End Class<br />
statement defines the termination of the Class. Together, these statements form a Class construct, or Class<br />
block. E.g.<br />
Class objName<br />
‘ Place the Class variables, Properties and Methods here<br />
End Class<br />
In this syntax, objName is the name given to the Class Object. The class object name must follow standard<br />
VBScript variable naming conventions. Class Objects are usually declared in the variable definition sections.<br />
You can have multiple Class blocks in a single VBScript file, but each block must contain the Class …End<br />
Class statements. Classes cannot be nested.<br />
Once you have defined the Class Object, you need to create an instance of the Class, similar to how other<br />
objects are created. When the Class Object is instantiated, memory is allocated for the Class Object. The Set<br />
statement is used with the New keyword to assign an instance of the class to a variable. With VBScript, this is<br />
the only time the New keyword is used (i.e. to instantiate a user-defined Class). E.g.<br />
Dim MyObj<br />
Set MyObj = New objName<br />
The Object name MyObj is the Object variable name, and must follow standard VBScript variable naming<br />
conventions. The Object variable name is a reference (address) of the Object stored in memory, it is not the<br />
Object itself.<br />
Inside the Class block, any Class variables, Properties, Methods and Events can be defined by the developer.<br />
The developer does not have to use all of the capabilities of the Class construct, i.e. Classes can be created<br />
without Methods or Properties. The design of the Class Object is completely up to the developer.<br />
Class variables are created within the Class structure by using the Dim, Public, or Private statements.<br />
Variables defined within the Class structure by any of these statements must follow the standard VBScript<br />
variable naming conventions. Variables can be simple variables or arrays. E.g.<br />
Class className<br />
Dim var1, var2<br />
Public var3, var4<br />
Private var5, var6<br />
End Class<br />
The choice of the Dim, Public, or Private statements determine whether the variable is accessible outside of<br />
the Class Object. Variables are public by default, i.e. they are accessible outside of the Class Object. Both the<br />
Dim and the Public statements create public variables, while the Private statement creates variables that are<br />
not public. As a general rule, it is good programming practice to make all Class variables private, since the<br />
developer will want to tightly control when these variables are changed.<br />
VBScript does not support Class-level Constants, i.e. named constants declared at the Class level. You cannot<br />
use the Const statement at the Class-level so that a constant can be used throughout a Class, but you can use<br />
the Const statement within a Property or Method. However, the constant will only have local scope within the<br />
Property or Method.<br />
Class Object variables are accessible to VBScript code outside the Class through Class Properties. Class<br />
Properties “wrap” the Private variables of a Class. Inside the Class block, the Properties are defined by<br />
Property Get [|Let|Set] … End Property statement(s). For VBScript code outside the Class, the Property is<br />
accessed by referencing the Object Name.Property.<br />
There are different type of Class Properties, depending on whether the Class variable is to be read, written to,<br />
or the Class variable is itself a Class Object. These Properties can be declared Public or Private.<br />
25–18 InduSoft Web Studio
VBScript User-Defined Class Objects<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Property Get<br />
The Property Get procedure is used to access (return) private variables inside of the Class structure<br />
that are used as a read-only Property, or the read portion of a read-write Property. For VBScript code<br />
outside the Class, this type of Class Object Property is generally assigned to a variable or used in a<br />
conditional expression. The Property Get procedure returns a value to the calling code, and is general<br />
not used with any arguments. [Note: VBScript will let you add arguments to the Property Get procedure,<br />
but if you do so you must add the additional argument to the corresponding Property Let or Property<br />
Set procedure, since Property Let/Property Set must have one more argument than the corresponding<br />
Property Get procedure. It is generally considered bad programming form to have arguments in the<br />
Property Get procedure].<br />
Property Let<br />
The Property Let procedure is used to access (assign) private variables inside of the Class structure<br />
that are used as a write-only Property or are the write portion of a read-write Property. For VBScript<br />
code outside of the Class, this type of Class Object Property is usually assigned by a variable or a<br />
constant.<br />
Property Set<br />
The Property Set procedure is exclusively used when the Class Object needs to store Properties that<br />
are object-based instead of numeric, date, boolean or string subtype variables. Property Set replaces<br />
the Property Let procedure. While Property Set and Property Let are functionally similar, there are two<br />
key differences:<br />
1. With the Property Set procedure, in the VBScript code segment (outside the Class block) you must<br />
use the syntax<br />
Set Object1.Property = Object2<br />
This is because VBScript does not let you use the assignment operator (=) to assign objects<br />
without the Set command.<br />
2. The Property Set procedure makes it clear that the Property is an object-based Property<br />
Example:<br />
Class FileSpec<br />
‘ Define a Class block<br />
Private master_file<br />
Private master_FSO<br />
Public Property Let FileName(strName) ‘ Define a Public Property to assign the file name<br />
master_file = strName<br />
End Property<br />
Public Property Get FileName ‘ Define a Public Property to retrieve a file name<br />
FileName = master_file<br />
End Property<br />
Public Property Set FSO(m_FSO)<br />
‘ Define a Public Property for an object<br />
Set master_FSO = m_FSO<br />
End Property<br />
End Class<br />
Rem Below is the VBScript code<br />
Dim objFSO<br />
‘ Declare variables and objects<br />
Dim objFilePointer, cur_file<br />
Set objFSO = CreateObject(“Scripting.FileSystemObject”) ‘ Instantiate the COM object<br />
Set objFilePointer = New FileSpec<br />
‘ Instantiate the Class Object<br />
objFilePointer.FileName = “Myfile.mdb” ‘Assigns “Myfile.mdb” as the file name<br />
cur_file = objFilePointer.FileName ‘Retrieves the current file name “Myfile.MDB”<br />
Set objFilePointer.FSO = objFso ‘Assigns an Object to the Property<br />
Set objFilePointer = Nothing ‘Keyword Nothing releases the object memory<br />
InduSoft Web Studio 25–19
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
VBScript User-Defined Class Objects<br />
A couple notes on the example above. The CreateObject command is used to instantiate an Object that is<br />
known at the system level (e.g. a COM object). Also, so far this example only shows how to assign and retrieve<br />
property values. It is generally the Method(s) that control the action an object performs, not the properties.<br />
A Property can be made read-only by only providing a Property Get procedure, or by declaring the Property Let<br />
procedure as Private instead of Public. A Property can be made write-only by only providing the Property Let<br />
procedure, or by declaring the Property Get procedure as Private instead of Public.<br />
Class Methods are really just Functions and Subroutines inside of a Class block. These functions and<br />
subroutines can be either Private or Public. If they are public, they will be accessible to a VBScript code<br />
segment outside of the Class block by referencing the obj.Method. If they are private, they will only be available<br />
to code within the Class block.<br />
An example of Class Methods is as follows:<br />
Class FileSpec<br />
Private master_file<br />
Private master_FSO Private master_file<br />
Private Sub Class_Initialize<br />
‘ Class Object initialization code<br />
‘ code goes here<br />
End Sub<br />
Private Sub Class_Terminate<br />
‘ Class Object termination code<br />
‘ code goes here<br />
End Sub<br />
Public Property Let FileName(strName) ‘ Define a Public Property to assign the file name<br />
master_file = strName<br />
End Property<br />
Public Property Get FileName ‘ Define a Public Property to retrieve a file name<br />
FileName = master_file<br />
End Property<br />
Public Property Set FSO(m_FSO)<br />
‘ Define a Public Property for an object<br />
Set master_FSO = m_FSO<br />
End Property<br />
Public Sub Delete<br />
‘Method to delete the master file<br />
master_FSO.DeleteFile (master_file)<br />
End Sub<br />
End Class<br />
Rem Below is the VBScript code<br />
Dim objFSO<br />
‘ Declare variables and objects<br />
Dim objFilePointer, cur_file<br />
Set objFSO = CreateObject(“Scripting.FileSystemObject”) ‘ Instantiate the COM object<br />
Set objFilePointer = New FileSpec<br />
‘ Instantiate the Class Object<br />
objFilePointer.FileName = “Myfile.mdb” ‘ Assigns “Myfile.mdb” as the file name<br />
cur_file = objFilePointer.FileName<br />
‘Retrieves the current file name “Myfile.MDB”<br />
Set objFilePointer.FSO = objFSO<br />
‘ Assigns an Object to the Property<br />
objFilePointer.Delete<br />
‘ Executes a Method to delete a file<br />
Set objFilePointer = Nothing ‘Keyword Nothing releases the object memory<br />
VBScript Class Objects automatically supports two type of Class Events; Class_Initialize and<br />
Class_Terminate Events. The code inside the Class_Initialize event executes once when an Object based on<br />
the Class is first instantiated. Any code put in this event is optional, and is typically used for initialization. Code<br />
inside the Class_Terminate event executes once just before the Object based on the Class is destroyed (i.e.<br />
Set to Nothing, or the Object goes out of scope). Usage is as follows:<br />
Class FileSpec<br />
Private master_file<br />
Private master_FSO Private master_file<br />
Private Sub Class_Initialize<br />
‘ Class Object initialization code<br />
25–20 InduSoft Web Studio
VBScript User-Defined Class Objects<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
‘ code goes here<br />
End Sub<br />
Private Sub Class_Terminate<br />
‘ Class Object termination code<br />
‘ code goes here<br />
End Sub<br />
Public Property Let FileName(strName) ‘ Define a Public Property to assign the file name<br />
master_file = strName<br />
End Property<br />
Public Property Get FileName ‘ Define a Public Property to retrieve a file name<br />
FileName = master_file<br />
End Property<br />
Public Property Set FSO(m_FSO)<br />
‘ Define a Public Property for an object<br />
Set master_FSO = m_FSO<br />
End Property<br />
End Class<br />
InduSoft Web Studio 25–21
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Example: Using VBScript User-Defined Class Objects<br />
Example: Using VBScript User-Defined Class Objects<br />
The previous section showed how to use User Defined Class Objects to perform certain functions. But you can<br />
also use VBScript User-Defined Class Objects to define memory structures similar to <strong>IWS</strong> Class Objects. For<br />
example:<br />
Class cTank<br />
Public Pressure<br />
Public Temperature<br />
Public Level<br />
Public Contents<br />
End Class<br />
Dim Tank(), i<br />
Const MaxTanks = 3<br />
ReDim Tank( MaxTanks)<br />
For i = 1 to MaxTanks<br />
Set Tank(i) = New cTank<br />
Next<br />
tank(1).contents = “Fructose”<br />
tank(2).contents = “Water”<br />
tank(3).contents = “Syrup”<br />
Notes:<br />
• The Scope of the VBScript variable is determined according to <strong>IWS</strong> rules.<br />
• Put the Class definition in the Variables section.<br />
• While VBScript variables (including VBScript Class Objects) do not consume <strong>IWS</strong> tags, they do<br />
consume memory. Class Objects are not overly efficient in their memory utilization, which may<br />
be an issue with Windows CE-based applications.<br />
25–22 InduSoft Web Studio
VBScript Objects and Collections<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
VBScript Objects and Collections<br />
VBScript has certain Objects and Collections that are inherent with VBScript. These include:<br />
• Debug<br />
• Err Object<br />
• Match Object & Matches Collections<br />
• Scripting Dictionary Object<br />
• Scripting FileSystemObject<br />
o Drive Object<br />
o File Object<br />
o FileSystemObject Collections<br />
o Folder Object<br />
• Regular Expression Object & Submatches Collection<br />
• TextStream Object<br />
VBScript Implicit Objects and Collections<br />
Objects & Collections<br />
Class Object<br />
Debug<br />
Err<br />
Match Object<br />
Dictionary<br />
Matches Collection<br />
RegExp Object<br />
SubMatches Collection<br />
Description<br />
Declares the name of a class, as well as a definition of the variables,<br />
properties, and methods that comprise the class<br />
The Debug object is an intrinsic global object that can send an output to a<br />
script debugger, such as the Microsoft Script Debugger.<br />
Contains information about the last run-time error. Accepts the Raise and<br />
Clear methods for generating and clearing run-time errors.<br />
An associative array that can store any type of data. Data is accessed by<br />
a key.<br />
Object & Collection Summary<br />
Objects &<br />
Collections<br />
Description<br />
Drive<br />
An object that refers to a specific Drive<br />
Drives<br />
A collection of Drive objects.<br />
File<br />
An object that refers to a specific File<br />
Files<br />
A collection of File objects.<br />
FileSystemObject An object model used to access the Windows file system<br />
Folder<br />
An object that refers to a specific Folder<br />
Folders<br />
A collection of Folder objects.<br />
Match<br />
Provides access to the read-only properties of a regular expression match.<br />
Matches<br />
Collection of regular expression Match objects.<br />
RegExp<br />
Provides simple regular expression support.<br />
Submatches<br />
A collection of regular expression submatch strings.<br />
TextStream<br />
An object that refers to a text File<br />
InduSoft Web Studio 25–23
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Err Object<br />
The VBScript Err object contains information about run-time errors.<br />
Err Object Properties<br />
Properties Description<br />
Description The descriptive string associated with an error.<br />
HelpContext A context ID for a topic in a Windows help file.<br />
HelpFile A fully qualified path to a Windows help file.<br />
Number A numeric value identifying an error.<br />
Source The name of the object or application that originally generated the error.<br />
Err Object Methods<br />
Properties Description<br />
Clear<br />
Clears all property settings.<br />
Raise<br />
Generates a run-time error.<br />
The properties of the Err object are set by the generator of an error-Visual Basic, an <strong>Automation</strong> object, or the<br />
VBScript programmer.<br />
The default property of the Err object is Number. Err.Number contains an integer and can be used by an<br />
<strong>Automation</strong> object to return an SCODE.<br />
When a run-time error occurs, the properties of the Err object are filled with information that uniquely identifies<br />
the error and information that can be used to handle it. To generate a run-time error in your code, use the<br />
VBScript Err Object Raise Method. The Err object's properties are reset to zero or zero-length strings ("") after<br />
an On Error Resume Next statement. The VBScript Err Object Clear Method can be used to explicitly reset<br />
Err.<br />
The Err object is an intrinsic object with global scope-there is no need to create an instance of it in your code.<br />
25–24 InduSoft Web Studio
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Scripting FileSystemObject<br />
The VBScript FileSystemObject object provides access to a computer's file system<br />
FileSystemObject Methods<br />
Method<br />
Description<br />
BuildPath<br />
Appends a name to an existing path.<br />
CopyFile<br />
Copies one or more files from one location to another.<br />
CopyFolder Recursively copies a folder from one location to another.<br />
CreateFolder Creates a folder.<br />
CreateTextFile<br />
Creates a specified file name and returns a TextStream object.<br />
DeleteFile<br />
Deletes a folder and its contents.<br />
DeleteFolder Deletes a folder and its contents.<br />
DriveExists Indicates the existence of a drive.<br />
FileExists<br />
Indicates the existence of a file.<br />
FolderExists<br />
Indicates the existence of a folder.<br />
GetAbsolutePathName Returns a complete and unambiguous path from a provided path<br />
specification.<br />
GetBaseName<br />
Returns the base name of a path.<br />
GetDrive<br />
Returns a Drive object corresponding to the drive in a path<br />
GetDriveName<br />
Returns a string containing the name of the drive for a path.<br />
GetExtensionName Returns a string containing the extension for the last component in a path.<br />
GetFile<br />
Returns a File object corresponding to the file in a path.<br />
GetFileName<br />
Returns the last component of a path that is not part of the drive<br />
specification.<br />
GetFolder<br />
Returns a Folder object corresponding to the folder in a specified path.<br />
GetParentFolderName Returns a string containing the name of the parent folder of the last<br />
component in a path.<br />
GetSpecialFolder Returns the special folder requested.<br />
GetTempName<br />
Returns a randomly generated temporary file or folder name.<br />
MoveFile<br />
Moves one or more files from one location to another.<br />
MoveFolder<br />
Moves one or more folders from one location to another.<br />
OpenTextFile<br />
Opens a file and returns a TextStream object<br />
FileSystemObject Properties<br />
Properties Description<br />
Drives A Drives collection of all Drive objects available on the local machine.<br />
Collections returned by FileSystemObject method calls reflect the state of the file system when the collection<br />
was created. Changes to the file system after creation are not reflected in the collection. If the file system might<br />
be changed during the lifetime of the collection object, the method returning the collection should be called<br />
again to ensure that the contents are current.<br />
Set fs = CreateObject("Scripting.FileSystemObject")<br />
Set a = fs.CreateTextFile("c:\testfile.txt", True)<br />
a.WriteLine("This is a test.")<br />
a.Close<br />
In the code shown above, the CreateObject function returns the FileSystemObject (fs). The CreateTextFile<br />
method then creates the file as a TextStream object (a) and the VBScript TextStream Object WriteLine<br />
Method writes a line of text to the created text file. The VBScript TextStream Object Close Method flushes<br />
the buffer and closes the file.<br />
Drive Object<br />
The Drive object provides access to the properties of a particular disk drive or network shared drive.<br />
InduSoft Web Studio 25–25
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Drive Object Properties<br />
Properties Description<br />
AvailableSpace The amount of space available to a user on the specified drive or network share.<br />
DriveLetter The drive letter of a physical local drive or network share<br />
DriveType A value indicating the type of a drive.<br />
FileSystem The amount of free space available to a user on the drive or network share.<br />
FreeSpace The amount of free space available to a user on the drive or network share.<br />
IsReady True if the drive is ready, False if not.<br />
Path<br />
The file system path for a drive.<br />
RootFolder A Folder object representing the root folder of a drive.<br />
SerialNumber The decimal serial number used to uniquely identify the disk volume.<br />
ShareName The network share name of a drive<br />
TotalSize The total space, in bytes, of a drive or network share<br />
VolumeName The volume name of a drive.<br />
The following code illustrates the use of the Drive object to access drive properties:<br />
Sub ShowFreeSpace(drvPath)<br />
Dim fs, d, s<br />
Set fs = CreateObject("Scripting.FileSystemObject")<br />
Set d = fs.GetDrive(fs.GetDriveName(drvPath))<br />
s = "Drive " & UCase(drvPath) & " - "<br />
s = s & d.VolumeName & vbCrLf<br />
s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)<br />
s = s & " Kbytes"<br />
Response.Write s<br />
End Sub<br />
25–26 InduSoft Web Studio
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
File Object<br />
The File object provides access to all the properties of a file.<br />
File Object Methods<br />
Properties<br />
Copy<br />
Delete<br />
Move<br />
OpenAsTextStream<br />
Description<br />
Copies a file from one location to another.<br />
Deletes a file.<br />
Moves a file from one location to another.<br />
Opens a file and returns a TextStream object.<br />
File Object Properties<br />
Properties<br />
Attributes<br />
DateCreated<br />
DateLastAccessed<br />
DateLastModified<br />
Drive<br />
Name<br />
ParentFolder<br />
Path<br />
ShortName<br />
ShortPath<br />
Size<br />
Type<br />
Description<br />
The attributes of a file.<br />
The date and time that the file was created.<br />
The date and time that the file was last accessed.<br />
The date and time that the file was last modified.<br />
The drive letter of the drive on which the file resides.<br />
The name of the file.<br />
The Folder object for the parent of the file.<br />
The file system path to the file.<br />
The short name used by programs that require 8.3 names.<br />
The short path use by programs that require 8.3 names.<br />
The size, in bytes, of a file.<br />
Information about the type of a file.<br />
The following code illustrates how to obtain a File object and how to view one of its properties.<br />
Sub ShowFileInfo(filespec)<br />
Dim fs, f, s<br />
Set fs = CreateObject("Scripting.FileSystemObject")<br />
Set f = fs.GetFile(filespec)<br />
s = f.DateCreated<br />
Response.Write s<br />
End Sub<br />
InduSoft Web Studio 25–27
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Folder Object<br />
The VBScript Folder object provides access to all the properties of a folder.<br />
Folder Object Methods<br />
Properties Description<br />
Copy Copies a folder from one location to another.<br />
Delete Deletes a folder.<br />
Move Moves a folder from one location to another.<br />
CreatTextFile Creates a file and returns a TextStream object.<br />
Folder Object Properties<br />
Properties<br />
Attributes<br />
DateCreated<br />
DateLastAccessed<br />
DateLastModified<br />
Drive<br />
Files<br />
IsRootFolder<br />
Name<br />
ParentFolder<br />
Path<br />
ShortName<br />
ShortPath<br />
Size<br />
SubFolders<br />
Description<br />
The attributes of a folder.<br />
The date and time a folder was created.<br />
The date and time that the folder was last accessed.<br />
The date and time that the folder was last modified.<br />
The drive letter of the drive on which the folder resides.<br />
A Files collection of all File objects in the folder.<br />
True if this is the root folder of a drive.<br />
The name of the folder.<br />
The Folder object for the parent of the folder.<br />
The file system path to the folder.<br />
The short name used by programs that require 8.3 names.<br />
The short path used by programs that require 8.3 names.<br />
The size, in bytes, of all files and subfolders contained in a folder<br />
A Folders collection containing all the folders in a Folder object<br />
The following code illustrates how to obtain a Folder object and how to return one of its properties:<br />
Sub ShowFolderInfo(folderspec)<br />
Dim fs, f, s,<br />
Set fs = CreateObject("Scripting.FileSystemObject")<br />
Set f = fs.GetFolder(folderspec)<br />
s = f.DateCreated<br />
Response.Write s<br />
End Sub<br />
Examples<br />
Const OverWrite = TRUE<br />
Const DeleteRdOnly = True<br />
SourceFile = “C:\data\MyData.MDB”<br />
SourceFiles = “C:\data\*.MDB”<br />
DestPath = “C:\Backup”<br />
DeleteFile = “C:\backup\Mydata.MDB”<br />
DeleteFiles = “C:\backup\*.MDB)<br />
Set objFS = CreateObject(“Scripting.FileSystemObject”)<br />
‘ Copy a single file to a new folder, overwrite any existing file in destination folder<br />
objFS.CopyFile (SourceFile, DestPath, OverWrite)<br />
‘ Copy a set of files to a new folder, overwrite any existing files in destination folder<br />
objFS.CopyFile (SourceFiles, DestPath. OverWrite)<br />
25–28 InduSoft Web Studio
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
‘ Delete a file<br />
objFS.DeleteFile(DeleteFile)<br />
‘ Delete a set of files in a folder<br />
objFS.DeleteFile(DeleteFiles, DeleteRdOnly)<br />
‘ Move a file to a new folder<br />
objFS.MoveFile(SourceFile, DestPath)<br />
‘ Move a set of files to a new folder<br />
objFS.MoveFile(SourceFiles, DestPath)<br />
‘ Rename a file<br />
objFS.MoveFile(SourceFile, “C:\data\MyData041406.MDB”)<br />
‘ Verify if a file exists<br />
If objFS.FileExists (SourceFile) Then<br />
Set objFolder =objFS.GetFile(SourceFile)<br />
MsgBox “File Exists “ & objFolder<br />
Else<br />
MsgBox “File does not exist”<br />
End If<br />
‘ Will display “File Exists “ and Path + File<br />
InduSoft Web Studio 25–29
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
VBScript Drives Collection<br />
Read-only collection of all available drives. Removable-media drives need not have media inserted for them to<br />
appear in the Drives collection.<br />
Drives Collection Object Properties<br />
Properties Description<br />
Count<br />
Returns the number of items in a collection. Read-only<br />
Item<br />
Returns an item on the specified key. Read/Write<br />
The following code illustrates how to get the Drives collection and iterate the collection using the For<br />
Each...Next statement:<br />
Sub ShowDriveList<br />
Dim fs, d, dc, s, n<br />
Set fs = CreateObject("Scripting.FileSystemObject")<br />
Set dc = fs.Drives<br />
For Each d in dc<br />
s = s & d.DriveLetter & " - "<br />
If d.DriveType = Remote Then<br />
n = d.ShareName<br />
Else<br />
n = d.VolumeName<br />
End If<br />
s = s & n & vbCrLf<br />
Next<br />
Response.Write s<br />
End Sub<br />
VBScript Files Collection<br />
Collection of all File objects within a folder.<br />
Files Collection Object Properties<br />
Properties Description<br />
Count<br />
Returns the number of items in a collection. Read-only<br />
Item<br />
Returns an item on the specified key. Read/Write<br />
The following code illustrates how to get a Files collection and iterate the collection using the For Each...Next<br />
statement:<br />
Sub ShowFolderList(folderspec)<br />
Dim fs, f, f1, fc, s<br />
Set fs = CreateObject("Scripting.FileSystemObject")<br />
Set f = fs.GetFolder(folderspec)<br />
Set fc = f.Files<br />
For Each f1 in fc<br />
s = s & f1.name<br />
s = s & vbCrLf<br />
Next<br />
Response.Write s<br />
End Sub<br />
25–30 InduSoft Web Studio
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
VBScript Folders Collection<br />
Collection of all Folder objects contained within a Folder object.<br />
Folders Collection Methods<br />
Properties Description<br />
Add<br />
Adds a new Folder to a Folders collection<br />
Folders Collection Properties<br />
Properties Description<br />
Count<br />
Returns the number of items in a collection. Read-only<br />
Item<br />
Returns an item on the specified key. Read/Write<br />
The following code illustrates how to get a Folders collection and how to iterate the collection using the For<br />
Each...Next statement:<br />
Sub ShowFolderList(folderspec)<br />
Dim fs, f, f1, fc, s<br />
Set fs = CreateObject("Scripting.FileSystemObject")<br />
Set f = fs.GetFolder(folderspec)<br />
Set fc = f.SubFolders<br />
For Each f1 in fc<br />
s = s & f1.name<br />
s = s & vbCrLf<br />
Next<br />
Response.Write s<br />
End Sub<br />
InduSoft Web Studio 25–31
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
TextStream Object<br />
The VBScript TextStream object facilitates sequential access to a file<br />
TextStream Object Methods<br />
Properties Description<br />
Close<br />
Closes an open stream.<br />
Read<br />
Reads a specified number of characters from a stream.<br />
ReadAll<br />
Reads an entire stream.<br />
ReadLine Reads an entire line from a stream.<br />
Skip<br />
Skips a specified number of characters when reading a<br />
stream.<br />
SkipLine<br />
Skips the next line when reading a stream.<br />
Write<br />
Writes a specified string to a stream.<br />
WriteBlankLines Writes a specified number of newline characters to a stream.<br />
WriteLine Writes a specified string and newline character to a stream.<br />
TextStream Object Properties<br />
Properties Description<br />
AtEndOfLine True if the file pointer is before the end-of-line marker.<br />
AtEndOfStream True if the file pointer is at the end of the stream<br />
Column<br />
The column number of the current character in the<br />
stream.<br />
Line<br />
The current line number of the stream.<br />
VBScript TextStream Object<br />
Description: The VBScript TextStream object<br />
Usage: oTextStream.{property | method}<br />
Return: Depends on Property or Method used<br />
Remarks<br />
Example: In the following code, a is the TextStream object returned by the CreateTextFile method on the<br />
FileSystemObject:<br />
Set fs = CreateObject("Scripting.FileSystemObject")<br />
Set a = fs.CreateTextFile("c:\testfile.txt", True)<br />
a.WriteLine("This is a test.")<br />
a.close<br />
25–32 InduSoft Web Studio
COM Objects and Collections<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
COM Objects and Collections<br />
In addition to user-defined Class Objects and VBScript Objects and Collections, there are many different COM<br />
Objects (and Object Collections) and other system objects based on COM technology that are accessible from<br />
VBScript. These Objects include:<br />
• ActiveX Controls inserted on an <strong>IWS</strong> Screen (via Insert OCX tool)<br />
• ActiveX Controls instantiated via VBScript<br />
• ADODB and ADOX Objects and Collections<br />
• Microsoft Office OLE <strong>Automation</strong> (Word, Excel, Access, Outlook & Components)<br />
• WMI<br />
• WSH<br />
• WSDL<br />
• XMLDOM<br />
ActiveX Controls Inserted On An <strong>IWS</strong> Screen<br />
InduSoft Web Studio (<strong>IWS</strong>) serves as an ActiveX control container, which is a parent program that supplies the<br />
environment for an ActiveX control to run. Through the <strong>IWS</strong> development interface (insert OCX tool), one or<br />
more ActiveX controls can be added to a screen. The OCX (ActiveX Control) must first be registered, if it was<br />
not already done so as part of the installation of the ActiveX control. <strong>IWS</strong> provides a Register Controls tool<br />
(under Tools on the toolbar) to allow registration of ActiveX controls, and to verify if a control has already been<br />
registered.<br />
After the OCX is inserted on the screen, <strong>IWS</strong> will assign the control a name. This name can be changed in the<br />
Object Properties dialog box, accessed by double clicking on the control in the <strong>IWS</strong> development environment,<br />
but the name of the control must be unique from any other control used by the current <strong>IWS</strong> application. In the<br />
Object Properties dialog box, the Configuration button will provide access to the Properties, Methods and<br />
Events accessible for this ActiveX control. In the Configuration dialog box, there is a tab for Events, which allow<br />
for the execution of a VBScript code segment if an Event is triggered for the ActiveX control. In the Properties<br />
and Methods tabs, parameters, triggers, <strong>IWS</strong> tags, etc. can be tied to the various Properties and Methods.<br />
Microsoft Slider Control 6.0<br />
Configure the Control’s Properties,<br />
Methods & Events<br />
Select to input VBScript code<br />
segments for the ActiveX<br />
Control Events<br />
InduSoft Web Studio 25–33
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
COM Objects and Collections<br />
Interaction with the ActiveX control from VBScript is accomplished through VBScript code placed in a Screen<br />
Script that is associated with the screen where the ActiveX control is placed. By entering a right mouse click on<br />
a blank portion of the screen, and selecting Screen Script, the Screen Script is accessed. For ActiveX Objects<br />
placed on the screen, you do not need to instantiate the Object in VBScript, <strong>IWS</strong> has already taken care of this.<br />
You simply need to reference the ActiveX control by its name, found in the Object Properties dialog box. Note:<br />
when referring to the name from VBScript, with <strong>IWS</strong> 6.1 SP1, the ActiveX control name was case<br />
sensitive. With SP2, it is no longer case sensitive. From the VBScript screen interface, you can access the<br />
ActiveX control’s Properties and Methods. Events are not accessible from the VBScript Screen Script interface.<br />
The Active<br />
Notes:<br />
• You must use the VBScript Screen Script interface for the screen which contains the ActiveX<br />
control in order to access the ActiveX control’s Properties and Methods. You cannot access the<br />
ActiveX control’s Properties and Methods from another Screen Script, or from any other<br />
VBScript interface in <strong>IWS</strong>.<br />
• From VBScript, you can only access the ActiveX control’s Properties and Methods. VBScript<br />
code segments for Events that are triggered by the ActiveX control can be entered, but these<br />
VBScript code segments must be entered from the Configuration dialog box (i.e. Object<br />
Properties Configuration Events).<br />
• When the ActiveX control is referenced from the VBScript Screen Script interface, the ActiveX<br />
control’s name is case-sensitive with SP1. This was corrected in SP2.<br />
• You do not need to instantiate the ActiveX control. <strong>IWS</strong> has already taken care of this. Simply<br />
refer to the ActiveX control name followed by a “.” and then the Property or Method.<br />
• In the VBScript Screen Script interface, place the cursor in a code segment area (Subroutine)<br />
and press Ctrl –Space to invoke IntelliSense to see the VBScript statements and functions, as<br />
well as the ActiveX controls available for this Script Interface.<br />
• Once you enter the ActiveX control object name, when you type a period (“.”), Intellisense will<br />
display a list of available Properties and Methods for the ActiveX control referenced.<br />
ActiveX Controls Instantiated from VBScript<br />
ActiveX controls can be instantiated from VBScript by using the CreateObject and referencing the Program ID<br />
(ProgID) of the ActiveX object, although the ActiveX object will not show up on the <strong>IWS</strong> screen if the script<br />
segment is associated with a Screen.<br />
ADODB and ADOX Objects and Collections<br />
ADODB is the database wrapper for ADO.NET, or ActiveX Data Objects for Microsoft’s .NET Framework.<br />
ADO.NET is Microsoft’s database interface technology that provides an API to database client applications (i.e.<br />
<strong>IWS</strong> and VBScript), supporting a common interface to access and manipulate data contained in a wide variety<br />
of database servers from different vendors. From the database client side, there is a level of abstraction<br />
provided by the API that enables interaction (e.g. database access and manipulation) to various vendor’s<br />
databases with virtually no code changes, except for the connection string to the database Provider (an object<br />
that interacts with the physical database). There are various ADODB Objects and Collections available to the<br />
developer.<br />
ADOX are Microsoft’s ActiveX Data Object Extensions for Data Definition Language (database schema<br />
creation, modification and deletion) and Security. It is a companion set of Objects to the core ADO.NET objects.<br />
25–34 InduSoft Web Studio
COM Objects and Collections<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Microsoft Office <strong>Automation</strong><br />
VBScript can access the various Microsoft Office <strong>Automation</strong> COM servers. These include:<br />
• Microsoft Access (“Access.Application”)<br />
• Microsoft Excel (“Excel.Application”)<br />
• Microsoft Word (“Word.Application”)<br />
• Microsoft Outlook (“Outlook.Application”)<br />
• Microsoft Graph<br />
• Microsoft Excel Chart (“Excel.Chart”)<br />
To instantiate a Excel and a Word Application, for example, we would use the following VBScript statements:<br />
Set objXL = CreateObject(“Excel.Application”)<br />
Set objWrd = CreateObject(“Word.Application”)<br />
Once the Microsoft Office COM object is instantiated, the VBScript Programmer can access the various<br />
Properties and Methods. Using VBScript, objects can be moved from one Microsoft application to another.<br />
WMI<br />
Windows Management Instrumentation, or WMI, is a set of extensions to the Windows Driver Model that<br />
provide an interface from a program (such as VBScript) into various components of the Windows operating<br />
system to retrieve information and notification. Using WMI and VBScript, management of Windows-based PCs<br />
and Servers can be accomplished either locally or remotely. WMI is based on the Common Information Model<br />
(CIM), allowing a uniform methodology of managing various Windows components. WMI is available to all .NET<br />
applications and is supported under Windows 2000, XP or Server 2003, but not Windows CE at present.<br />
Examples of Microsoft Windows components accessible through WMI include:<br />
• Control Panel (can manipulate basic system settings and controls)<br />
• Device Manager (display and control hardware added to the PC, which drivers are used)<br />
• Event Viewer (view the system event log locally or remotely)<br />
• RegEdit (Windows Registry Editor)<br />
• Various applications (Notepad, Command.Com and Cmd.exe)<br />
• Windows Core Components<br />
Windows Script Host<br />
Windows Script Host, or WSH, is the successor to the Batch File first introduced for DOS. WSH automates<br />
system administration tasks, and supports multi-lingual scripting including VBScript. Scripts can be run locally,<br />
or on remote computers. There are several WSH objects including:<br />
• WScript Object (not available from <strong>IWS</strong>, since <strong>IWS</strong> is the host)<br />
• WshShell (allows scripts to work with the Windows Shell – e.g. read/write to registry, shortcuts, system<br />
administration tasks, running programs)<br />
• WshNetwork (manages network drives and printers)<br />
• WshController (runs scripts locally or remotely)<br />
InduSoft Web Studio 25–35
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
COM Objects and Collections<br />
WSDL<br />
Web Services Definition Language, or WSDL, is an XML-based language for describing network services as a<br />
set of endpoints operating on messages containing either document-oriented or procedure-oriented information.<br />
WSDL is frequently used in conjunction with SOAP (Simple Object Access Protocol, a simple XML-based<br />
protocol for applications to exchange information using HTTP). Common examples of WSDL are stock price,<br />
news services, weather information, currency conversion, etc.<br />
VBScript code in an <strong>IWS</strong> application can instantiate a SOAP client object through the following statement:<br />
Set oSOAP = CreateObject("MSSOAP.SoapClient")<br />
XMLDOM<br />
XMLDOM is the XML Document Object Model that defines a standardized approach for creating, accessing and<br />
manipulation XML documents. The DOM structures the XML document as a tree-like structure (the node), with<br />
each node having elements, attributes and text. There is a root element, which is the highest level element, and<br />
0 or more child (sibling) nodes. Each node can also have 0 or more child nodes.<br />
A VBScript code segment can be created in an <strong>IWS</strong> application to allow creation, accessing and manipulation<br />
of XML Documents. This allows passing of data between <strong>IWS</strong> and another computer in XML format. Note that<br />
in addition to XMLDOM, ADO.NET also supports XML databases.<br />
25–36 InduSoft Web Studio
VBScript Configuration and Operation in <strong>IWS</strong><br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
VBScript Configuration and Operation in <strong>IWS</strong><br />
<strong>IWS</strong> acts as the host application for the Microsoft VBScript Engine. This means that to write VBScript, you need<br />
to be in the <strong>IWS</strong> development (engineering) environment. It is important to note that there is no one central<br />
location where a VBScript interface is located inside an <strong>IWS</strong> application. The location of the VBScript interface<br />
(where the VBScript code gets placed) depends on the function the VBScript code is to perform and the scope<br />
of access to its Procedures and Variables. InduSoft has implement VBScript in this manner to simplify its use,<br />
and to be consistent with the <strong>IWS</strong> architecture as well as current licensing methods.<br />
VBScript is interpreted code. While it executes fairly efficiently, it is nevertheless interpreted and will never<br />
execute as efficiently as compiled code. This should not present any concern for HMI/SCADA applications since<br />
<strong>IWS</strong> is performing the real-time management of the tag database and key functions such as alarming, logging,<br />
etc. The interpreted nature of VBScript allows changes to be made quickly to an application. <strong>IWS</strong> supports<br />
dynamic, on-line configuration and this capability is maintained with the addition of VBScript support<br />
Developers familiar with <strong>IWS</strong> know that in the bottom left corner of the development window are tabs that<br />
provide access to the Database, Graphics, Tasks, and Communications Workspace folders containing the<br />
different application components. The developer will need to navigate among these different folders and<br />
application components when using VBScript.<br />
VBScript interfaces can be found in 6 different areas:<br />
• Database Workspace folder – Global Procedures<br />
• Graphics Workspace folder - Graphics Script<br />
• Graphic Screens – Screen Scripts<br />
• <strong>IWS</strong> Objects on a Screen – Command Dynamic<br />
• ActiveX Objects on a screen – ActiveX Events<br />
• Tasks Workspace folder – Background Startup Script and Background Script Groups<br />
Subfolders and Icons<br />
within a Workspace<br />
folders<br />
Tabs to access various<br />
Workspace folders<br />
InduSoft Web Studio 25–37
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Global Procedures<br />
The figure below shows the structure of the VBScript interfaces within a typical <strong>IWS</strong> project (application). Note<br />
that there are certain types of VBScript interfaces that have one instance (e.g. Global Procedures, Background<br />
Startup Tasks and Graphic Script) while others can have multiple instances (e.g. Background Script Groups,<br />
Screen Scripts, Command Dynamic and ActiveX Events).<br />
Global Procedures<br />
Global Procedures are located in the Database Worksheet folder. Global Procedures are shared by both the<br />
Graphics Module Scripts (Graphics Script and Screen Scripts) and the Background Task Scripts (Background<br />
Startup Script and Background Script Groups). Note that it this is only the Procedures that are shared, not the<br />
Variables. Other VBScript interfaces within the Graphic Module or Background Task do not share variables or<br />
procedures between them; they are independent of each other.<br />
Global Procedures Subfolder in<br />
Database Worksheet folder<br />
VBScript Interface<br />
25–38 InduSoft Web Studio
Graphics Script<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Notes:<br />
• Before executing the application, be sure to save (or close) the Screen after any VBScript is entered.<br />
Otherwise the changes might not be updated. This is true for all VBScript interfaces.<br />
Graphics Script<br />
The Graphics Script is located in the Graphics Worksheet folder. Procedures and Variables declared in the<br />
Graphics Script interface are available locally but are not accessible by any Screen Script interface, or from any<br />
other VBScript interface within <strong>IWS</strong>. Procedures and Variables declared in a Screen Script interface are not<br />
accessible by the Graphics Script. If common Procedure(s) are required, they should be put into the Global<br />
Procedures interface. Note that the Graphics Script is scanned (processed) by <strong>IWS</strong> before the Screen Scripts.<br />
The Graphics Script has three different pre-configured subroutines to execute VBScript code. These<br />
subroutines execute the VBScript contained in them based on the event state of the Graphics Module. These<br />
are:<br />
Graphics_OnStart<br />
Code contained within this subroutine is automatically executed just once when the Graphics Module is<br />
started. This is a good area to initialize variables or execute start-up code.<br />
Graphics_WhileRunning<br />
Code contained within this subroutine is automatically executed continuously while the Graphics<br />
Module is running. The rate at which this subroutine is called depends on the performance of the<br />
hardware platform and other tasks running at the time.<br />
Graphics_OnEnd<br />
Code contained within this subroutine is automatically executed just once when the Graphics Module is<br />
closed.<br />
Graphic Script Icon in<br />
Graphics Worksheet folder<br />
VBScript Interface<br />
InduSoft Web Studio 25–39
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Screen Scripts<br />
Notes:<br />
• Do not change the name of the pre-configured subroutines in the VBScript interface. Otherwise<br />
they many not properly execute.<br />
The Graphics Script operates for both the Server (the host processor where the <strong>IWS</strong> application is running) and<br />
Web Thin Clients (web browser interface using Microsoft Internet Explorer). For the Server, the Graphics<br />
module is the Viewer task (the display on the host processor), while the ISSymbol control is the Graphics<br />
module for Web Thin Clients.<br />
The operation of the Graphics Script on the Server is described above, and starts when the application is<br />
started on the Server, assuming there are one or more screens. But since Web Thin Clients can log on at any<br />
time after the Server is started, the functioning of the Graphics Script is different for Web Thin Clients and is<br />
independent of the operation of the Graphics Script on the host Server. Web Thin Client operation is as follows:<br />
• When a Web Thin Client logs on to the Server, following completion of the log on process, the<br />
Graphics_OnStart subroutine will be executed for the Web Thin Client. This will occur each time any<br />
new Web Thin Client logs on to the Server.<br />
• Following completion of the execution of the Graphics_OnStart subroutine, the Graphics_WhileRunning<br />
subroutine will be executed for as long as the Web Thin Client (browser) hosts the ISSymbol control<br />
(i.e. while an active network link exists and the ISSymbol is active in the browser).<br />
• When the Web Thin Client is shut down or when the ISSymbol control is no longer hosted by the<br />
browser, the Graphics_OnEnd subroutine is executed<br />
Screen Scripts<br />
Screen Scripts are associated with individual graphical screens. These screens can be for display on the host<br />
Server (where the <strong>IWS</strong> application is running), for a Web Thin Client, or both. Procedures and Variables<br />
declared in a Screen Script VBScript interface are not accessible by any other VBScript interface within <strong>IWS</strong>.<br />
However, the Screen Script interface can access procedures declared in the Global Procedures script interface.<br />
Screen subfolder in<br />
Graphics Worksheet folder<br />
VBScript Interface<br />
25–40 InduSoft Web Studio
Screen Scripts<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
There are two methods to access a Screen Script. The first is to select the desired<br />
Screen and have it displayed on the active <strong>IWS</strong> workspace. Then, perform a right<br />
mouse click while the cursor is located on the display screen. A pop-up menu will let<br />
you select the Screen Script (as shown at the right). When the Screen Script option<br />
is selected, the <strong>IWS</strong> workspace will display the Screen Script VBScript interface.<br />
Notice the Screen Script VBScript interface looks very similar to the Graphics Script<br />
interface. The differences between the Screen Script and the Graphics Script are:<br />
• There is only one Graphics Script. The Graphics Script is activated when the<br />
Graphics Module starts<br />
• You can have multiple Screen Scripts. There is one Screen Script available<br />
per Screen, but you can have multiple screens.<br />
The second method to access a Screen Script is to select the desired Screen and<br />
have it displayed on the active <strong>IWS</strong> workspace. Then from the top toolbar, select<br />
View. A pull-down menu (as shown at the right) will have the Screen Script option<br />
available. By selecting this option, you will activate the Screen Script VBScript<br />
interface.<br />
The Screen Script interface has three predefined subroutines. These are:<br />
Screen_OnOpen<br />
Code contained within this subroutine is automatically executed just once<br />
when the Screen is opened.<br />
Screen_WhileOpen<br />
Code contained within this subroutine is automatically executed continuously<br />
while the Screen is open. The rate at which this subroutine is called depends<br />
on the performance of the hardware platform and other tasks running at the<br />
time.<br />
Screen_OnClose<br />
Code contained within this subroutine is automatically executed just once<br />
when the Screen is closed.<br />
Pop-Up Menu<br />
Pull-down Menu<br />
The execution of the Screen Script subroutines on the Server executes independently from the execution on<br />
Web Thin Clients.<br />
Notes:<br />
• Do not change the name of the pre-configured subroutines in the VBScript interface.<br />
Otherwise they many not properly execute.<br />
• Before executing the application, be sure to save (or close) the Screen after any VBScript is<br />
entered. Otherwise it might not be updated. This is true for all VBScript interfaces.<br />
• The Graphic Script is scanned (processed) by <strong>IWS</strong> before the Screen Scripts are processed.<br />
InduSoft Web Studio 25–41
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Command Dynamic<br />
Command Dynamic<br />
A Command Dynamic is associated with a specific object on a Screen, and allows one or more actions to take<br />
place when an event occurs with the specific object. A typical use is a button (perhaps a rectangle) that is<br />
placed on the screen. When an operator selects on the button (via mouse click or pressing a touchscreen over<br />
the object), this action is expected to initiate some action. That action may be to set/reset a PLC bit, jump to a<br />
different screen, whatever. The Command Dynamic allows the developer to chose what action to take.<br />
With Version 6.1, <strong>IWS</strong> adds new capability to the Command Dynamic interface. In addition to the <strong>IWS</strong> built-in<br />
language command, the Command Dynamic can now execute VBScript code. The steps to access the VBScript<br />
interface within a Command Dynamic are:<br />
1. Select the object on the Screen currently opened in the <strong>IWS</strong> workspace. If the object has a<br />
Command Dynamic associated with it, then right click on the object. Otherwise, click on the<br />
Command Dynamic icon (right) from the Mode toolbar and then right click on the object.<br />
2. Now, the Object Properties dialog box for the<br />
Command Dynamic will open. Click on the Config…<br />
button in the lower right corner of the dialog box.<br />
3. Select the event condition (e.g. On Down) where your<br />
want code to be execute and then select VBScript as<br />
the Type.<br />
4. Enter your VBScript code (variable declarations<br />
and executable statements).<br />
Within the Command Dynamic, you enter VBScript<br />
variables and executable statements subject to the<br />
following conditions:<br />
• Any variable declared in this interface will only<br />
have a local scope.<br />
• You cannot implement procedures (i.e.<br />
Subroutines or Functions) within this interface.<br />
Notwithstanding these restrictions, VBScript code within a<br />
Command Dynamic still has access to all Global<br />
Procedures.<br />
VBScript code within the Command Dynamic interface is<br />
executed whenever one or more of the selected event<br />
conditions (listed in the Command Dynamic configuration<br />
screen) occur for the selected object. The execution of<br />
the Command Object script on the Server executes independently from the execution on Web Thin Clients.<br />
Notes:<br />
• Before executing the application, be sure to save (or close) the Screen after any VBScript<br />
is entered. Otherwise it might not be updated. This is true for all VBScript interfaces.<br />
25–42 InduSoft Web Studio
ActiveX Events<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
ActiveX Events<br />
<strong>IWS</strong> is an ActiveX container, supporting ActiveX controls, generally inserted on a given graphical screen. With<br />
<strong>IWS</strong> Version 6.1, there is a VBScript interface to ActiveX Events so that an ActiveX object event can trigger a<br />
VBScript code segment.<br />
The steps to accessing the VBScript ActiveX Event interface are as follows:<br />
1. Select the ActiveX object on the Screen currently opened in the <strong>IWS</strong> workspace. Right click<br />
on the object to open its Object Properties dialog box. If you need to insert an ActiveX<br />
object, select the ActiveX Control icon from the Mode toolbar and<br />
then right click on the object<br />
In the lower right corner of the ActiveX<br />
Object Properties dialog box will be a<br />
Configuration button. Click this to open up<br />
the Configuration options dialog box.<br />
2. Click on the Events tab (as<br />
shown at the right).<br />
3. Click on the … button in the<br />
Script Column for the event<br />
you want to write VBScript for.<br />
This is the scripting interface for ActiveX Events. Be sure<br />
VBScript language is selected. You can now insert code that<br />
will execute when the selected ActiveX Event is triggered.<br />
Within the ActiveX Event interface, you enter VBScript<br />
variables and executable statements subject to the following<br />
conditions:<br />
• Any variable declared in this interface will only have<br />
a local scope.<br />
• You cannot implement procedures (i.e. Subroutines<br />
or Functions) within this interface.<br />
Notwithstanding these restrictions, VBScript code within the<br />
ActiveX Event interface still has access to all Global<br />
Procedures, as well as any procedures in the Screen Script<br />
for the same Screen where the ActiveX object is configured.<br />
InduSoft Web Studio 25–43
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Background Task Startup Script<br />
VBScript code within the ActiveX Event interface is executed whenever one or more of the selected Event<br />
conditions (listed in the Configuration dialog box) occur for the selected ActiveX object. The execution of the<br />
script on the Server executes independently from the execution on Web Thin Clients.<br />
Notes:<br />
• Before executing the application, be sure to save (or close) the Screen after any VBScript is<br />
entered. Otherwise it might not be updated. This is true for all VBScript interfaces.<br />
Background Task Startup Script<br />
In the Tasks Worksheet folder is the Script subfolder which will contain a default Startup Script icon and any<br />
Background Task Script Groups declared. To edit the Background Task Startup Script:<br />
1. Click on the Tasks Worksheet folder<br />
2. Click on the Script subfolder.<br />
Any VBScript code placed in this interface will execute when<br />
the Background Task module is started, which occurs when<br />
the <strong>IWS</strong> application is started. This code will only execute<br />
once, and is meant for initialization purposes.<br />
Variables and Procedures declared in the Background Task<br />
Startup Script are available to the Background Task Script<br />
Group, but are not available to any VBScript interfaces in the<br />
Graphic Module. Remember that the Background Task<br />
Group Startup Script can access the procedures declared in<br />
Global Procedures.<br />
Since the Background Task Startup Script has no interaction with a Graphics script, the only Server display I/O<br />
functions that can be implemented are MsgBox and InputBox functions.<br />
Since the Background Task Startup Script runs on the <strong>IWS</strong> Server, there is no effect with Web Thin Clients.<br />
25–44 InduSoft Web Studio
Background Task Script Groups<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Background Task Script Groups<br />
The Background Task Script Groups consist of one or more VBScript interface groups that run in the<br />
Background Task. By default, there are no Background Task Script Groups unless added by the developer.<br />
These Script Groups will execute in a background as long as their Execution Field is in a TRUE state.<br />
Background Task Script Groups have the following limitations:<br />
• Variables declared in a Background Task Script Group have a local scope for it’s specific Script Group<br />
only. Variables cannot be shared with other Script Groups, nor any other VBScript Interface.<br />
• Background Task Script Groups cannot declare their own Procedures (Subroutines and Functions).<br />
• The Execution Field of the Script Group will only support <strong>IWS</strong> tags or built-in functions. No support for<br />
VBScript variables or Procedures is provided in the Execution Field.<br />
However, the Background Task Script Groups can do the following:<br />
• Access Procedures and Variables within the Background Task Startup Script.<br />
• Access Procedures declared in Global Procedures.<br />
To create a new Script Group, right-click on the Script subfolder<br />
in the Tasks tab of the Workspace. Select the Insert option from<br />
the pop-up menu. Note that the Startup Script is already defined.<br />
To open (edit) an existing Script Group, simply click its icon in the<br />
Script subfolder of the Tasks workspace tab.<br />
The code configured in each Script Group is executed by the<br />
Background Task. <strong>IWS</strong> scans the Script Groups sequentially<br />
(based on the number of the group) and executes only the<br />
Groups in which the condition configured in the Execution Field of<br />
the Script Group is set to or is evaluated to be TRUE (a value<br />
different from 0).<br />
When any Script Group is saved during runtime (e.g. from an on-line configuration download), the Startup Script<br />
interface will be executed again, and the current value of the local variables contained in any Script Group will<br />
be reset, if any exist.<br />
InduSoft Web Studio 25–45
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Background Task Script Groups<br />
Since the Background Task Script Groups run on the <strong>IWS</strong> Server, there is no effect with Web Thin Clients.<br />
Notes:<br />
• The Execution Field of the Script Group only supports syntax as specified by the <strong>IWS</strong><br />
built-in language.<br />
• Before executing the application, be sure to save (or close) the Screen after any<br />
VBScript is entered. Otherwise it might not be updated. This is true for all VBScript<br />
interfaces.<br />
• If any Script Group is saved during runtime (i.e. on-line configuration), the Startup<br />
Script Group will be executed again and the current value of local variables will be<br />
reset<br />
25–46 InduSoft Web Studio
Scope of VBScript Procedures and Variables<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Scope of VBScript Procedures and Variables<br />
The following table summarizes the relationship between the <strong>IWS</strong> VBScript interface location and its<br />
Scope of Variables and Procedures. The table also defines where the Scripts are located<br />
Item<br />
Global<br />
Procedures<br />
Graphics Scripts<br />
Screen Scripts<br />
Command<br />
Dynamic<br />
ActiveX Events<br />
Scope of<br />
Procedures<br />
and Variables<br />
All Procedures are<br />
global, Variables are<br />
accessible only within<br />
Global Procedures<br />
(local)<br />
Procedures and<br />
Variables accessible<br />
within<br />
Graphics Script<br />
interface only. Can<br />
Call Global<br />
Procedures.<br />
Procedures and<br />
Variables accessible<br />
within Screen where<br />
the Script is written.<br />
Screen Script<br />
procedures<br />
accessible to ActiveX<br />
Events for ActiveX<br />
objects contained in<br />
the Screen. Can Call<br />
Global Procedures.<br />
Variables and<br />
Script accessible<br />
only in Object<br />
where the Script<br />
is configured.<br />
Can Call Global<br />
Procedures.<br />
Variables<br />
accessible only<br />
in Object where<br />
the Script is<br />
configured.<br />
Screen Script<br />
Procedures are<br />
accessible. Can<br />
Call Global<br />
Procedures.<br />
Execution Functionality Location/Access<br />
Procedures are<br />
accessible to any Script<br />
on the host Server<br />
Executes on host Server<br />
and/or Web Thin Client<br />
where any screen is<br />
displayed.<br />
Executes on host Server<br />
and/or Web Thin Client<br />
where the specific<br />
screen is displayed<br />
Executes on host<br />
Server and/or Web<br />
Thin Client where<br />
the screen with the<br />
specific Object is<br />
displayed<br />
Executes on host<br />
Server and/or Web<br />
Thin Client where<br />
the screen with the<br />
specific Object is<br />
displayed<br />
Declaration of<br />
Procedures<br />
(Functions and<br />
Subroutines) that are<br />
available globally<br />
Condition-based<br />
execution<br />
- Graphics Start<br />
- Graphics Open<br />
- Graphics Close<br />
Graphics Scripts<br />
execute before<br />
Screen Scripts<br />
Condition-based<br />
execution<br />
- Screen Start<br />
- Screen Open<br />
- Screen Close<br />
Execution of Script<br />
when Object<br />
condition is met<br />
Execution of Script<br />
when selected<br />
ActiveX Event<br />
occurs<br />
Database Workspace<br />
Folder<br />
Graphics Workspace<br />
Folder<br />
Within the Screen.<br />
Within Object<br />
(Command)<br />
Properties. The<br />
Screen that uses<br />
the Object must<br />
be open.<br />
Within the ActiveX<br />
object. The<br />
Screen that uses<br />
the Object must<br />
be open.<br />
InduSoft Web Studio 25–47
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Scope of VBScript Procedures and Variables<br />
Item<br />
Background<br />
Startup<br />
Script<br />
Background<br />
Script Groups<br />
Scope of<br />
Procedures<br />
and Variables<br />
Procedures and<br />
Variables<br />
accessible within<br />
the Script<br />
Group. Can Call<br />
Global<br />
Procedures.<br />
Accessible within<br />
Script Group only.<br />
Can Call Global<br />
Procedures.<br />
Execution Functionality Location/Access<br />
Executes on Server<br />
as a background<br />
task<br />
Executes on Server<br />
as a background<br />
task<br />
Declaration of<br />
Procedures and<br />
Variables that<br />
are available for<br />
Background<br />
Scripts<br />
Condition-based<br />
execution in<br />
background<br />
mode. Can have<br />
multiple Script<br />
pages.<br />
Tasks Workspace<br />
Folder<br />
Tasks Workspace<br />
Folder<br />
25–48 InduSoft Web Studio
Accessing <strong>IWS</strong> Tags and <strong>IWS</strong> Built-in functions<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Accessing <strong>IWS</strong> Tags and <strong>IWS</strong> Built-in functions<br />
When writing your code in a VBScript interface, you can access any tag from the <strong>IWS</strong> tags database or any<br />
function from the <strong>IWS</strong> built-in language by applying the "$" prefix to the tag/function name, as in the examples<br />
below:<br />
CurTime = $Time<br />
a = $MyTag<br />
$Open("main.scr")<br />
‘ Returns the value of the tag Time from the tags database<br />
‘ Sets a to the value of the <strong>IWS</strong> tag MyTag<br />
‘ Executes the Open() function to open the "main" screen<br />
<strong>IWS</strong> tags and built-in functions are accessible from any VBScript code segment, regardless where located. If<br />
the <strong>IWS</strong> function returns a value (e.g. error or status information), this can be assigned to a VBScript variable.<br />
<strong>IWS</strong> tags can be used as arguments in VBScript statements and functions.<br />
If an undefined name follows the “$”, when the programmer does a Check Script function or attempts to Save<br />
the script, <strong>IWS</strong> will ask the programmer if they want to define the <strong>IWS</strong> tag, and if so, prompt for the tag type.<br />
<strong>IWS</strong> supports the following application tag types:<br />
• Boolean (a Boolean (True/False) or digital value (0 or 1))<br />
• Integer (a 32-bit long-word signed integer type)<br />
• Real (a real number stored as a double precision word)<br />
• String (a string of characters of up to 1024 characters that holds letters, numbers, or special<br />
characters)<br />
• Class (a user-defined, compound tag)<br />
• Array (an array of values from 0 to 16,384)<br />
Passing variables between VBScript and <strong>IWS</strong> is straightforward but there are some conversion considerations<br />
that should be noted:<br />
<strong>IWS</strong> Boolean<br />
With VBScript, variable can be of the data subtype Boolean. VBScript defines keywords True and False for<br />
logical states True and False, respectively. In VBScript, False has a numeric value of 0, while True has a<br />
numeric value of -1. This is because Booleans are not actually stored as bits, but as 32-bit signed integers.<br />
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<br />
logical True.<br />
<strong>IWS</strong> objects that display <strong>IWS</strong>-defined boolean tags (e.g. Text I/O) will have the boolean values displayed as<br />
0 or 1 (0=False, 1=True), not as False or True. Consider the following VBScript code segment:<br />
$MyBool = True<br />
‘ Will be displayed as a “1” in an <strong>IWS</strong> object (*see below)<br />
$MyBool = False<br />
‘ Will be displayed as a “0” in an <strong>IWS</strong> object<br />
The value for True assumed by Boolean <strong>IWS</strong> tags depends on the value of the parameter<br />
BooleanTrueAboveZero that is located in the [Options] section of the .APP file. To access<br />
this parameter, you need to open the .APP file with a simple text editor such as Microsoft<br />
Notepad. For example:<br />
[Options]<br />
BooleanTrueAboveZero = 0 <strong>IWS</strong> Boolean tag set to value 1 (True) when value 0<br />
[Options]<br />
BooleanTrueAboveZero = 1 <strong>IWS</strong> Boolean tag set to value 1 (True) only when value > 0<br />
One item to watch for is the boolean NOT operator. With an <strong>IWS</strong> tag, even though the tag is of type<br />
Boolean, it is really stored internally as a 32-bit signed variable. If you NOT a 0, the lower bit is set to one<br />
but in reality all the bits are set to 1’s, meaning that with a variable that is a signed integer, the NOT of 0 is<br />
really -1. For example,<br />
a = CBool(Not(0))<br />
InduSoft Web Studio 25–49
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Accessing <strong>IWS</strong> Tags and <strong>IWS</strong> Built-in functions<br />
$c = a ‘ $c (<strong>IWS</strong> tag c) will display as -1<br />
One programming trick that can be used when attempting to toggle <strong>IWS</strong> Boolean Tags between 0 and 1 is<br />
either:<br />
$tag = Abs ($tag=0)<br />
‘ Either one of these statements will toggle the tag<br />
$tag = $If ($tag=0,1,0) ‘ between 0 and 1<br />
<strong>IWS</strong> Integer<br />
All <strong>IWS</strong> integer tags are stored as 32-bit values. VBScript has 3 different variant subtypes that are of<br />
interest. Bytes are 8-bit values that are positive whole numbers ranging from 0 to 255. Integers are 16-bit<br />
signed values that range from -32,768 to 32,767. Long Integers are 32-bit values that range from -<br />
2,147,483,648 to 2,147,483,647.<br />
When storing to an <strong>IWS</strong> integer tag, the conversion to a 32-bit signed integer type will be automatically<br />
made. For example:<br />
a = CInt (-30) ‘ a is a 16-bit signed integer with a value of -30<br />
$MyInt = a ‘ MyInt is a 32-bit signed integer with a value of -30<br />
b = CByte (-30)<br />
‘ Generates an error since Bytes are 0 to 255, not negative<br />
b = CByte (30) ‘ b is a 8-bit unsigned integer with a value of 30<br />
$MyInt = b ‘ MyInt is a 32-bt signed integer with a value of 30<br />
When converting from an <strong>IWS</strong> integer tag to an <strong>IWS</strong> tag, this is really not a problem since VBScript<br />
variables are type variant. For example:<br />
$MyInt = 400<br />
‘ Store a value larger than 255 (the Byte limit)<br />
a = CByte (10)<br />
‘ store as a byte subdata type<br />
a = $MyInt ‘ a will equal 400.<br />
<strong>IWS</strong> Strings<br />
In <strong>IWS</strong>, strings are up to 1024 in length, while VBScript strings can be virtually unlimited in length (limited by<br />
available memory only). During the conversion from a VBScript string variable to an <strong>IWS</strong> string, any<br />
characters beyond the first 1024 will be truncated. For example:<br />
a = “ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789”<br />
a = a & a & a & a & a & a & a & a & a & a ‘ String is 360 characters long<br />
a = a & a & a & a<br />
$MyStr = a<br />
‘ String is 1440 characters ling<br />
‘ Store string in <strong>IWS</strong> string<br />
‘ Result is truncated after 1024 characters<br />
In most cases, this string length difference is not of material significance. However, certain ActiveX Controls<br />
can be used for block transfer of data to real-world devices and strings are ideal for forming variable length<br />
data blocks. The string can then be parsed to extract the data of interest.<br />
<strong>IWS</strong> Classes<br />
<strong>IWS</strong> Classes are simply user-defined compound tags that can be made up of one or more <strong>IWS</strong> tag type.<br />
The <strong>IWS</strong> Classes and Tags are defined in the Database Worksheet. For example, if we define a <strong>IWS</strong> Class<br />
(under the Classes Folder in the Database worksheet ) called MyClass with the following elements<br />
MyClass<br />
Item1 Integer<br />
Item2 Integer<br />
Message String<br />
25–50 InduSoft Web Studio
Accessing <strong>IWS</strong> Tags and <strong>IWS</strong> Built-in functions<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Next, a Class tag is created (in the Application Tags Folder)<br />
Cls1 MyClass<br />
Finally, in VBScript, we can refer to the elements in the Class tag as follows:<br />
$Cls1.Item1 = 10<br />
$Cls1.Item2 = 20<br />
$Cls1.Message = “Hello World”<br />
<strong>IWS</strong> Arrays<br />
Using the Class example from above, if (in the Application Tags folder) we had declared the variable Cls1<br />
to have a size of 10, this would be an array with 11 elements. [Remember that the count starts at 0, not 1].<br />
In VBScript, we would refer to the elements in the Class array tag as follows:<br />
$Cls1[1].Item1 = 10<br />
$Cls1[1].Item2 = 20<br />
$Cls1[1].Message = “Hello World”<br />
We can also use a VBScript variable for the index of the Class array tag. For example:<br />
Dim i<br />
i = 1<br />
$Cls1[i].Item1 = 10<br />
$Cls1[i].Item2 = 20<br />
$Cls1[i].Message = “Hello World”<br />
Notes:<br />
• <strong>IWS</strong> tags can be added through the VBScript interface. Simply type a “$” followed by a<br />
valid <strong>IWS</strong> name, and when the Script is Saved, Closed or Check Script function invoked,<br />
the programmer will be prompted to create new <strong>IWS</strong> tag(s).<br />
• VBScript variables and <strong>IWS</strong> variables can be passed to each other.<br />
• Watch for string length differences with <strong>IWS</strong> (max. 1024 characters) versus VBScript (no<br />
limit).<br />
InduSoft Web Studio 25–51
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Accessing ActiveX Objects from VBScript<br />
Accessing ActiveX Objects from VBScript<br />
Any of the VBScript interfaces relating to a Screen (i.e. Screen Script, Command Dynamic, and/or ActiveX<br />
Events) can directly access the Properties and Methods of an ActiveX control (OCX) that is inserted on a<br />
screen.<br />
Using ActiveX Controls is fairly straight forward. First, the ActiveX controls must be registered (i.e. the<br />
Operating System Windows Registry must have an entry and Class ID (CLSID) established for the ActiveX<br />
Control). Usually when an ActiveX Control is installed in the PC, the installation program will register the<br />
ActiveX Control in the final stage of the installation process. If not, registration can be done with one of two<br />
methods:<br />
1. Use the Microsoft RegSvr32 command<br />
- Invoke the Microsoft Windows Run command<br />
- In the dialog box, type CMD, then OK<br />
- Type REGSVR32 “C:\\.OCX”, then Enter<br />
(Be sure path name is in quotes)<br />
- If the ActiveX Control registers properly, you will get a message indicated this<br />
- Close the dialog box<br />
2. Use the Register Controls utility provided by <strong>IWS</strong> (under Tools on the main toolbar)<br />
- Click on Tools, then Register Controls<br />
- On the dialog box that pops up, click on Register<br />
- Use the file navigator to locate the ActiveX Control that you want to register<br />
- Click on Open.<br />
- Click on Close in the Register Controls dialog box.<br />
You can also use the <strong>IWS</strong> Register Controls utility to verify that the ActiveX Control has been registered.<br />
Beware that the registered name and the file name may not be the same, and in many cases they are not. The<br />
best way to verify the control is properly registered is to examine the path of the registered Control.<br />
When the ActiveX Control has been registered, it can be inserted onto a display screen using either the OCX<br />
tool in the <strong>IWS</strong> toolbar or by using the Insert -> ActiveX Object from the top toolbar. A dialog box will appear<br />
with a scrolled list of ActiveX objects that are available. Insert the ActiveX object(s) that are appropriate for the<br />
application by clicking on OK. <strong>IWS</strong> will automatically assign a unique name to the ActiveX control. You can use<br />
this name or change it, the only requirement being that it must be unique from other ActiveX controls.<br />
Now that an ActiveX Control has been placed on the Screen, any VBScript interface associated with that screen<br />
can access the ActiveX Control. These VBScript interfaces are limited to the Screen Script, Command Dynamic<br />
for objects located on the same Screen, and ActiveX Event Handler for other ActiveX objects located on the<br />
same Screen.<br />
For example, Microsoft has an ActiveX scrollbar control called “MicrosoftFlatScrollBarControl 6.0 (SP6)”.<br />
Assuming this was inserted for the first time onto a Screen in an <strong>IWS</strong> application, <strong>IWS</strong> would likely name this<br />
Control “MicrosoftFlatScrollbarControl1”. For brevity, let us rename this to “MFSC1”. I could easily click on the<br />
ActiveX Control on the screen to access its Property Pages, Properties, Methods and Events.<br />
Note that Property Pages and Events are not accessible through the VBScript Interface, although a VBScript<br />
Interface is available with the ActiveX’s Event Handler. Only an ActiveX Control’s Properties and Methods are<br />
available from VBScript as implemented in <strong>IWS</strong>. By clicking on the object to get the Object Properties dialog<br />
box<br />
25–52 InduSoft Web Studio
Accessing ActiveX Objects from VBScript<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
ActiveX Control Name<br />
established by <strong>IWS</strong>. You<br />
can rename this Control.<br />
Use this interface to tie<br />
Properties and Methods to<br />
<strong>IWS</strong> tags.<br />
To access the ActiveX Control’s Properties and Methods from VBScript, you simply type the name of the<br />
Control, followed by a Period “.” and then the Property or Method. You will need to reference documentation<br />
from the developer of the ActiveX Control to determine which properties are setting (Set) or retrieving (Get), and<br />
the functioning of the Methods available. For example, with the Microsoft scroll bar control, we access<br />
Properties using the following code:<br />
MFSC1.Min = 0 ’ Set the min value of the scroll bar to 0<br />
MFSC1.Max = 100 ’ Set the max value of the scroll bar to 100<br />
$LocTag = MFSC1.Value ’ Get the current location of the scroll bar, pass to <strong>IWS</strong> tag<br />
<strong>IWS</strong> tools such as Position and Command can be used with ActiveX controls. To enable these tools, insert the<br />
ActiveX control on the Screen and then make sure the ActiveX control is selected (highlighted). Then, select the<br />
Position or Command tool. For example, with the Position tool, you can control the visibility of the ActiveX<br />
Control, or change its location on the screen.<br />
Notes:<br />
• All ActiveX Controls must have a unique name<br />
• When referencing an ActiveX object name that has been inserted on a screen, note that<br />
the reference is case-sensitive from VBScript.<br />
• Only ActiveX Properties and Methods can be accessed via VBScript. Event handling must<br />
be set-up by configuring the object (i.e. right click on the object)<br />
• ActiveX Controls can only be accessed by VBScript interfaces associated with the Screen<br />
which contains the ActiveX Control (i.e. Screen Script, Command Dynamic, ActiveX Event<br />
Handler)<br />
InduSoft Web Studio 25–53
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
IntelliSense<br />
IntelliSense<br />
The VBScript Editor provides a useful tool called IntelliSense, a feature first popularized in Microsoft Visual<br />
Studio. Intellisense can be thought of providing “auto-completion” based on the language elements, variables<br />
and class members, as well as a convenient listing of available functions. As the developer<br />
IntelliSense the dialog box can display the following:<br />
• VBScript Functions<br />
• ActiveX Controls, Properties and Methods (the ActiveX Control must be inserted on the Screen where<br />
the Screen Script, Command Dynamic or ActiveX Event is used)<br />
• <strong>IWS</strong> tags and tag fields.<br />
• <strong>IWS</strong> built-in functions<br />
As the programmer begins to type and characters are recognized, IntelliSense may turn on. If not, the<br />
programmer can activate IntelliSense by pressing the Ctrl key plus the Spacebar (“Ctrl” + “ “). By typing a “$” at<br />
the beginning of a line, this allows access to <strong>IWS</strong> tags and built-in functions to be referenced.<br />
When IntelliSense is activate, a pop-up box will appear. The contents of the pop-up box depend on what the<br />
programmer has already typed. Sample IntelliSense pop-up dialogs are shown below:<br />
IntelliSense Dialog for<br />
VBScript Functions<br />
IntelliSense Dialog for<br />
<strong>IWS</strong> Functions<br />
IntelliSense Dialog for<br />
<strong>IWS</strong> Tag Fields<br />
IntelliSense uses different Icons to indicate the type of item that is being referenced. Some Icons are used to<br />
indicate different items, so it is important to notice what object is being referenced (i.e. is it an <strong>IWS</strong> tag, ActiveX<br />
Control, VBScript function, etc.)<br />
IntelliSense<br />
Icon<br />
Use<br />
<strong>IWS</strong> Boolean Tag<br />
<strong>IWS</strong> Integer Tag<br />
<strong>IWS</strong> Real Tag<br />
<strong>IWS</strong> String Tag<br />
<strong>IWS</strong> Class Tag<br />
VBScript Function, built-in <strong>IWS</strong> function, or ActiveX Control Method<br />
ActiveX Control Property, VBScript Constants<br />
For many of the functions (both VBScript functions and <strong>IWS</strong> built-in functions), IntelliSense provide a Parameter<br />
Quick Info pop-up dialog. This pop-up dialog may appear once the VBScript or <strong>IWS</strong> function is entered. An<br />
example is:<br />
25–54 InduSoft Web Studio
IntelliSense<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Notes:<br />
• Use the Ctrl key plus Spacebar key (“Ctrl” + “ ”) to activate IntelliSense. Doing this on a<br />
blank line will show all available VBScript functions and any ActiveX controls available.<br />
• Use the Ctrl key plus Spacebar key (“Ctrl” + “ ”) to auto-complete any VBScript function,<br />
<strong>IWS</strong> tag, <strong>IWS</strong> tag field, <strong>IWS</strong> Class or Class Member, <strong>IWS</strong> built-in function, or ActiveX<br />
Control name, Property or Method once enough of the characters have been entered so<br />
that the reference is no longer ambiguous.<br />
• Typing a “$” at the beginning of a line will invoke IntelliSense, referencing existing <strong>IWS</strong><br />
tags and built-in functions<br />
• Typing the name of an <strong>IWS</strong> tag, followed by the minus key “-“ plus a greater than arrow<br />
key “>” will open the list of available fields for the <strong>IWS</strong> tag<br />
InduSoft Web Studio 25–55
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
VBScript with Web Thin Clients<br />
VBScript with Web Thin Clients<br />
In a Web Thin Client environment, the browser serves as the host for both HTML web pages published by the<br />
<strong>IWS</strong> Server, as well as the host for VBScript code segments that are associated with a particular Screen or<br />
object on the Screen. Generally, Microsoft Internet Explorer serves as the browser in a Web Thin Client<br />
environment. A InduSoft ActiveX Control (ISSymbol) is used to coordinate communications between the <strong>IWS</strong><br />
Server and a Web Thin Client.<br />
In a Windows XP/2000/NT-based Web Thin Client environment, Microsoft Internet Explorer (e.g. Version 6 or<br />
later) supports VBScripts and ActiveX by default. In a Windows CE-based Web Thin Client environment,<br />
Microsoft Internet Explorer (typically provided with PocketPC products) supports both VBScript and ActiveX, but<br />
VBScript support must be enabled in the Windows CE image (part of the Platform Build process, typically done<br />
by the hardware supplier). Windows CE systems with Microsoft Pocket Explorer (different that Microsoft Internet<br />
Explorer) will not work with VBScript as Pocket Explorer does not support VBScript due to memory limitations.<br />
Also remember that any ActiveX controls used on a Windows CE Web Thin Client must be developed to<br />
support Windows CE.<br />
VBScript Interface<br />
Global Procedures<br />
Graphics Module<br />
Screen Scripts<br />
Command Dynamic<br />
ActiveX Event Handler<br />
Background Task<br />
Startup<br />
Background Task<br />
Scripts<br />
Functioning related to a Web Thin Client<br />
VBScript Global Procedures are accessible to VBScript code segments that<br />
execute on a Web Thin Client<br />
Operates on <strong>IWS</strong> Server PC only. Procedures and Variables not accessible to a<br />
Web Thin Client.<br />
This VBScript interface (for a Web Page) executes independently from the<br />
VBScript Interface for a Screen running on the <strong>IWS</strong> Server.<br />
• The Graphics_OnStart() subroutine starts when the Web Thin Client Station<br />
is successfully logged in and ISSymbol is hosted on the Web Browser<br />
• The Graphics_WhileRunning() subroutine executes on the Web Thin Client<br />
while the Web Thin Client remains logged in and the ISSymbol Control<br />
remain hosted on the Web Browser<br />
• The Graphics_OnEnd() subroutine is executed once the Web Thin Client logs<br />
off or the ISSymbol Control is no longer hosted by the Web Browser<br />
This VBScript interface (for a Web Page) executes independently from the<br />
VBScript Interface for a Screen running on the <strong>IWS</strong> Server.<br />
This VBScript interface (for a Web Page) executes independently from the<br />
VBScript Interface for a Screen running on the <strong>IWS</strong> Server.<br />
Operates on <strong>IWS</strong> Server PC only. Procedures and Variables not accessible to a<br />
Web Thin Client.<br />
Operates on <strong>IWS</strong> Server PC only. Procedures and Variables not accessible to a<br />
Web Thin Client.<br />
Notes:<br />
• Under Windows XP/2000/NT, to check or modify Internet Explorer’s settings for support of<br />
VBScript and ActiveX Controls, open Internet Explorer, then click on Tools Internet Options<br />
Security Custom Level.<br />
• All VBScript interfaces unique to the Web Thin Client continue to have access to <strong>IWS</strong> tags and<br />
<strong>IWS</strong> built-in functions.<br />
• When using a Windows CE device for the Web Thin Client, be sure ActiveX support and<br />
VBScript support is enabled. This is a function of the Windows CE OS image built using<br />
Microsoft Platform Builder.<br />
• When using a Windows CE device for the Web Thin Client, verify that MsgBox and InputBox<br />
functions are enabled in the Windows CE OS image if you intent to use them.<br />
25–56 InduSoft Web Studio
Exercise: Using VBScript with Screens<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Using VBScript with Screens<br />
In this exercise, we will create 4 Objects; 3 button objects and a Text I/O object. The buttons will increment,<br />
decrement and display the value of Tag v1.<br />
Open the Main.scr Screen<br />
Using the Button tool from the Static Object toolbar, add 3 Button Objects.<br />
Add the Command Dynamic to each Button Object.<br />
Set the following properties to the buttons:<br />
Button1:<br />
Caption<br />
Increment v1<br />
Command Dynamic $v1 = $v1 + 1 (Click on Config…, choose VBScript and put in the On Down<br />
tab)<br />
Button2:<br />
Caption<br />
Command Dynamic<br />
tab)<br />
Button3:<br />
Caption<br />
Command Dynamic<br />
Add a Text Object, caption is v1 = ######<br />
Decrement v1<br />
$v1 = $v1 - 1 (Click on Config…, choose VBScript and put in the On Down<br />
Display v1<br />
Msgbox “v1 = “ & $v1 (Click on Config…, choose VBScript and put in the On<br />
Down tab)<br />
Add the Text I/O Dynamic Property to the Text Object. Put v1 in the Tag Expression field.<br />
Save and Close the Screen<br />
InduSoft Web Studio 25–57
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Using VBScript & Script Worksheets<br />
Exercise: Using VBScript & Script Worksheets<br />
This Exercise demonstrates a VBScript alternative to a previous Exercise where we used the WS Scripting<br />
Language to create a Field Process Simulator.<br />
Use the following procedure to configure a Script worksheet:<br />
In the Workspace, select the Tasks tab and then right-click on the Script folder.<br />
When the pop-up menu displays, select the Insert option:<br />
Opening a Math Worksheet<br />
A blank Script worksheet displays:<br />
Blank Script Worksheet<br />
The header portion of the worksheet contains the following fields:<br />
Description field: Provides space for an optional description of the worksheet.<br />
Execution field:<br />
Controls the script execution. You can type a full expression here, a simple condition, a<br />
tag name, or a value. Whatever it is, the script will execute while it is TRUE.<br />
The body section consists of a plain text field into which you can type VBScript.<br />
In the Description field, type Field Process Simulator.<br />
In the Execution field, type 1. This enables continuous execution of this Math worksheet; the value 1 is the<br />
TRUE condition.<br />
25–58 InduSoft Web Studio
Exercise: Using VBScript & Script Worksheets<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Next, to generate simulated process data that can be used by the various screens, we must set the following<br />
variables:<br />
• Valve status (according to the command given)<br />
• Temperature, pressure, and level for three tanks<br />
• Simulated valve status (just transfer the value from the command tags to the status tags).<br />
• Simulated temperature and pressure properties for each tank (configure these properties using sine<br />
and cosine trigonometric functions)<br />
• Simulated level properties for each tank (remember that both the Fill and Empty valves allow for the<br />
same flow).<br />
Given this information, complete the body of the Script worksheet as follows:<br />
Completed Script Worksheet<br />
Notes:<br />
• In the preceding Worksheet, the Script is executed continuously. In a real world application, we strongly<br />
recommend that the execution of each Script worksheet be carefully controlled to improve system<br />
performance.<br />
• The Execution Field in the Header can usually be set to any non-zero value to execute the script.<br />
Depending on the BooleanTrueAboveZero setting (set in the Application File), this value must either<br />
be >0 or non-zero.<br />
• BE SURE TO ONLY USE EITHER THE MATH WORKSHEET OR THE SCRIPT WORKSHEET, NOT<br />
BOTH<br />
InduSoft Web Studio 25–59
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Using VBScript & Script Worksheets<br />
Right click on the Startup Script Folder in the Tasks tab of the Workspace to open the Startup Script<br />
Worksheet<br />
Enter the following VBScript code.<br />
25–60 InduSoft Web Studio
Exercise: Using VBScript<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Using VBScript<br />
In this Exercise, we will create some examples using VBScript.<br />
Open the Scripts.scr Screen<br />
In a blank area of the Screen, click the right mouse button. Choose the Screen Script option.<br />
Enter the VBScript as shown below:<br />
Save and Close the Scripts Screen Script (v7 should be declared as an integer Tag).<br />
Open the Scripts Screen<br />
Add a Text Object with the caption v7 = #########################<br />
Add a Text I/O property and type v7 in the Tag/Expression field.<br />
InduSoft Web Studio 25–61
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Using VBScript<br />
Add two button objects to the Screen. One will have the caption Divide by 2 and the other will have the<br />
caption Multiply by 2.<br />
Add the Command Dynamic to each button object. Select Type as VBScript<br />
Add the VBScript to each Command Dynamic as shown:<br />
Close the Object Properties dialog box<br />
Save and Close the Screen<br />
Notes:<br />
• For Background Tasks, the <strong>IWS</strong> Scripting Language uses Math Worksheets while VBScript uses<br />
Script Worksheets<br />
• The Script Worksheets include a Startup Script, which can be used to run VBScript code one time<br />
at startup.<br />
25–62 InduSoft Web Studio
Exercise: Using VBScript<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Notes<br />
InduSoft Web Studio 25–63
Chapter 26.<br />
Databases<br />
Databases store information in one or more tables that can be accessed, updated and queried by an application<br />
program, whether the database is in the same PC or a remote PC from the application program. There are<br />
different data models for databases, and the choice of database depends upon several factors including:<br />
- amount of data to be stored<br />
- the type and number of consumers of the database information<br />
- security<br />
- reliability<br />
- type of operations to be performed on the database<br />
A database can be defined as a structured collection of records or data stored in a computer so that the<br />
records or data can be retrieved in response to queries executed on the database by a program. The records<br />
retrieved in response to the query become information that can be used for decision making. There are a<br />
number of database models that are used today, although<br />
ISAM File Database<br />
ISAM (Indexed Sequential Access Method) databases are very simple file-based databases. ISAM files have<br />
fixed length records, indexes and file system locks (to control access to the database). To read a ISAM file, you<br />
open a file that has the table you are interested in, and read through the file sequentially starting with the first<br />
record and ending with the last record. The index points to the current record in the file (table). An example of<br />
an ISAM file might be a file of comma separated values (CSV), where each record in the file consists of a fixed<br />
number of fields.<br />
Index {BOF} = 1 <br />
Index {EOF} = 9 <br />
Record 1<br />
Record 2<br />
Record 3<br />
Record 4<br />
Record 5<br />
Record 6<br />
Record 7<br />
Record 8<br />
Record 9<br />
Record 1 = 00123, Joe, Sanborn, 382-184-2934, Manufacturing<br />
Record 2 = 01469, Kathy, Smith, 256-398-9387, Sales<br />
Record 3 = 03953, Kim, Jones, 287-934-9132, Admin<br />
Etc.<br />
While ISAM file databases are simple and relatively inexpensive, they have many drawbacks and are only used<br />
for very simple applications. Mission critical applications (i.e. high reliability/uptime) generally use Client-Server<br />
Relational Database architecture such a Microsoft SQL Server.<br />
InduSoft Web Studio 26–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Using VBScript<br />
Flat Database<br />
The flat database is another simple data model where all required information is generally contained in one<br />
table. This type of database may contain additional tables that are usually unrelated to each other. The<br />
difference between the flat database and an ISAM file database is that the flat database can access data items<br />
in rows and columns, versus the ISAM file which sequentially accesses records.<br />
A flat database consists of a two-dimensional array of data elements. The columns represent values that are of<br />
the same data type, each column being a different type of information from another column. The rows are single<br />
entries that have columns related to one another. For example, a list of employees might be organized as<br />
follows:<br />
EmployeeID First Last SSNum Department<br />
00123 Joe Sanborn 382-184-2934 Manufacturing<br />
01469 Kathy Smith 256-398-9387 Sales<br />
03950 Kim Jones 287-934-9132 Admin<br />
The flat database model forms the basis for spreadsheets such as Microsoft Excel. Note that Excel, a<br />
spreadsheet application, includes limited database functions that can operate over a span of rows and columns.<br />
These functions include Average, Count, Max, Min, Sum, Product and Get.<br />
Although these database functions operate from within Excel and no external query can be made using these<br />
built-in functions, the Microsoft JET database engine supports Excel and will access Excel records to support<br />
SQL data access and queries. Using a flat database such as Excel with <strong>IWS</strong> allows simple storage, retrieval<br />
and updating of a simple table of information contained in 2-dimensional format (rows and columns).<br />
While this database model is simple, it is inefficient in memory utilization. As the number of entries in the<br />
database grows, the database size can quickly grown to a point where the file size and memory requirements<br />
become troublesome, not to mention the adverse impact on the time for data retrieval and queries. By<br />
comparison, a relational database stores data in multiple tables that have some logical connection to each<br />
other. The relational database model is much more efficient in terms of storage, retrieval and queries for larger<br />
amounts of storage.<br />
26–2 InduSoft Web Studio
Exercise: Using VBScript<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Relational Database<br />
Relational databases became popular in the 1980’s. They were first defined by Dr. E.F. Codd of IBM<br />
in the late 1960s in an attempt to improve on the efficiency of the existing flat database model. Codd<br />
introduced 12 principles that defined a relational database. However, virtually no product that is<br />
marketed as a relational database follows all of his principles so the term “relational database” is<br />
somewhat generically used. Virtually all relational databases use SQL as the query language.<br />
Examples of relational databases include Microsoft Access, Microsoft SQL Server, Oracle, MySQL,<br />
and Sybase.<br />
A relational database allows for the definition of data structures, storage and retrieval operations and<br />
integrity constraints. Data is stored in a collection of tables that are organized in rows (records) and<br />
columns (fields). Each row in the table contains the same fields.<br />
Each row in any given field (column) is of the same data type. The common data types supported by<br />
databases include text, number (integer), and data or datetime. Each database typically supports a<br />
variety of data types.<br />
The six key properties of tables in a relational database are as follows:<br />
• Entries in any given column are single valued<br />
• Column values are of the same data type<br />
• Each row is unique<br />
• Each column has a unique name<br />
• The sequence of the columns is insignificant<br />
• The sequence of the rows is insignificant<br />
Each table can have one or more “keys” which are columns in the table that contains a unique value<br />
for each row. These keys match values in columns of other tables, providing access to data that is<br />
contained in the selected row. Keys make the relational database work, and provide a controlled level<br />
of data redundancy. Each table has one “primary” key that appears again as the link (foreign key) in<br />
another table. Tables are linked together logically by a combination of the table names, the primary<br />
key value and the column name. The primary key can be an autonumber field.<br />
When columns in two different tables take values from the same set, a join operation can be<br />
performed to select related records in the two tables by matching values in those columns. Often, but<br />
not always, the columns will have the same name in both tables. For example, an "orders" table might<br />
contain customer-ID and product-code pairs, and a "products" table might contain product-code and<br />
price pairs so to calculate a given customer's bill you would sum the prices of all products ordered by<br />
that customer by joining on the product-code fields of the two tables. This can be extended to joining<br />
multiple tables on multiple fields. Because these relationships are only specified at retrieval time,<br />
relational databases are classed as dynamic database management system.<br />
InduSoft Web Studio 26–3
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Using VBScript<br />
Central to relational databases are the concept of the “Normal Form”. This refers to the organization<br />
of data in the relational database. Normalization is the design process method to structure a relational<br />
database to be compliant with the Normal Form. Normalizing a database design leads to optimal<br />
database and application performance.<br />
Signs of a normalized database<br />
A greater number of narrow tables with fewer columns<br />
Fast sorting<br />
Few indexes per table<br />
Few null values, increasing data compactness<br />
Signs of a non-normalized database<br />
A few tables that are wide (more columns)<br />
Slower sortation speeds<br />
Several indexes per table<br />
Use of null values<br />
There are several levels of normalization, although most database designers stop at the 3 rd level<br />
since it is usually quite efficient.<br />
1 st Normal Form (1NF)<br />
Reduce tables to the 1NF by:<br />
• Eliminating duplicate columns from the same table. (i.e. every column must be single-valued)<br />
• Create separate tables for each group of related data and identify each row with a unique column<br />
or set of columns (the primary key).<br />
2 nd Normal Form (2NF)<br />
Reduce the 1NF tables to 2NF by:<br />
• Meeting all the requirements of the first normal form.<br />
• Remove subsets of data that apply to multiple rows of a table and place them in separate tables.<br />
• Create relationships between these new tables and their predecessors through the use of foreign<br />
keys.<br />
3 rd Normal Form (3NF)<br />
Reduce the 2NF tables to 3NF by:<br />
• Meeting all the requirements of the second normal form.<br />
• Remove columns that are not dependant upon the primary key<br />
A table that is in the 3 rd normal form is also in the 1 st and 2 nd normal form.<br />
26–4 InduSoft Web Studio
Exercise: Using VBScript<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Example of Normalizing a Database<br />
Non-normalized database<br />
The data is organized with each record containing a particular Company/Division combination. Note that<br />
repeating groups of part and supplier related information occurs.<br />
Suppliers and Parts By Company Division<br />
Company<br />
Allied Clock<br />
and Watch<br />
Allied Clock<br />
and Watch<br />
Global Robot<br />
Global Robot<br />
Company<br />
Founder<br />
Horace<br />
Washington<br />
Horace<br />
Washington<br />
Company<br />
Logo<br />
Sundial<br />
Sundial<br />
Nils Neumann Gearbox<br />
Nils Neumann Gearbox<br />
Division Part Type Supplier<br />
Clocks<br />
Watches<br />
Industrial<br />
Robots<br />
Domestic<br />
Robots<br />
Spring<br />
Pendulum<br />
Spring<br />
Toothed Wheel<br />
Quartz Crystal<br />
Tuning Fork<br />
Battery<br />
Flywheel<br />
Axle<br />
Axle<br />
Mechanical Arm<br />
Artificial Brain<br />
Artificial Brain<br />
Metal Housing<br />
Backplate<br />
Tensile Globodynamics<br />
Tensile Globodynamics<br />
Pieza de Acero<br />
Pieza de Acero<br />
Microflux<br />
Microflux<br />
Dakota Electrics<br />
Wheels 4 Less<br />
Wheels 4 Less<br />
TransEuropa<br />
TransEuropa<br />
Prometheus Labs<br />
Frankenstein Labs<br />
Pieza de Acero<br />
Pieza de Acero<br />
Supplier<br />
Country<br />
USA<br />
USA<br />
Mexico<br />
Mexico<br />
Belgium<br />
Belgium<br />
USA<br />
USA<br />
USA<br />
Italy<br />
Italy<br />
Luxembourg<br />
Germany<br />
Mexico<br />
Mexico<br />
Supplier<br />
Continent<br />
N. Amer.<br />
N. Amer.<br />
N. Amer.<br />
N. Amer.<br />
Europe<br />
Europe<br />
N. Amer.<br />
N. Amer.<br />
N. Amer.<br />
Europe<br />
Europe<br />
Europe<br />
Europe<br />
N. Amer.<br />
N. Amer.<br />
InduSoft Web Studio 26–5
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Using VBScript<br />
1NF database<br />
The 1 st Normalized Form eliminates the repeating groups. Now, each group will appear as its own record.<br />
Suppliers and Parts By Company Division<br />
Company<br />
Company<br />
Founder<br />
Company<br />
Logo<br />
Division Part Type Supplier<br />
Supplier<br />
Country<br />
Supplier<br />
Continent<br />
Allied Clock and<br />
Watch<br />
Horace<br />
Washington<br />
Sundial Clocks Spring<br />
Tensile<br />
Globodynamics<br />
USA<br />
N. Amer.<br />
Allied Clock and<br />
Watch<br />
Allied Clock and<br />
Watch<br />
Allied Clock and<br />
Watch<br />
Horace<br />
Washington<br />
Horace<br />
Washington<br />
Horace<br />
Washington<br />
Sundial Clocks Pendulum<br />
Tensile<br />
Globodynamics<br />
USA<br />
N. Amer.<br />
Sundial Clocks Spring Pieza de Acero Mexico N. Amer.<br />
Sundial<br />
Clocks<br />
Toothed<br />
Wheel<br />
Pieza de Acero Mexico N. Amer.<br />
Allied Clock and<br />
Watch<br />
Horace<br />
Washington<br />
Sundial<br />
Watches<br />
Quartz<br />
Crystal<br />
Microflux Belgium Europe<br />
Allied Clock and<br />
Watch<br />
Allied Clock and<br />
Watch<br />
Horace<br />
Washington<br />
Horace<br />
Washington<br />
Global Robot Nils Neumann Gearbox<br />
Global Robot Nils Neumann Gearbox<br />
Global Robot Nils Neumann Gearbox<br />
Global Robot Nils Neumann Gearbox<br />
Global Robot Nils Neumann Gearbox<br />
Global Robot Nils Neumann Gearbox<br />
Global Robot Nils Neumann Gearbox<br />
Global Robot Nils Neumann Gearbox<br />
Sundial Watches Tuning Fork Microflux Belgium Europe<br />
Sundial Watches Battery Dakota Electrics USA N. Amer.<br />
Industrial<br />
Robots<br />
Industrial<br />
Robots<br />
Industrial<br />
Robots<br />
Industrial<br />
Robots<br />
Domestic<br />
Robots<br />
Domestic<br />
Robots<br />
Domestic<br />
Robots<br />
Domestic<br />
Robots<br />
Flywheel Wheels 4 Less USA N. Amer.<br />
Axle Wheels 4 Less USA N. Amer.<br />
Axle TransEuropa Italy Europe<br />
Mechanical<br />
Arm<br />
TransEuropa Italy Europe<br />
Artificial Brain Prometheus Labs Luxembourg Europe<br />
Artificial Brain Frankenstein Labs Germany Europe<br />
Metal<br />
Housing<br />
Pieza de Acero Mexico N. Amer.<br />
Backplate Pieza de Acero Mexico N. Amer.<br />
26–6 InduSoft Web Studio
Exercise: Using VBScript<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
2NF database<br />
The 2 nd Normalized Form eliminates the repeating Company Founder and Company Logo details (and Supplier<br />
Countries and Continents for a given Supplier) by splitting this information into separate tables.<br />
Suppliers and Parts By Company Division<br />
Company Division Part Type Supplier<br />
Allied Clock and Watch Clocks Spring Tensile Globodynamics<br />
Allied Clock and Watch Clocks Pendulum Tensile Globodynamics<br />
Allied Clock and Watch Clocks Spring Pieza de Acero<br />
Allied Clock and Watch Clocks Toothed Wheel Pieza de Acero<br />
Allied Clock and Watch Watches Quartz Crystal Microflux<br />
Allied Clock and Watch Watches Tuning Fork Microflux<br />
Allied Clock and Watch Watches Battery Dakota Electrics<br />
Global Robot Industrial Robots Flywheel Wheels 4 Less<br />
Global Robot Industrial Robots Axle Wheels 4 Less<br />
Global Robot Industrial Robots Axle TransEuropa<br />
Global Robot Industrial Robots Mechanical Arm TransEuropa<br />
Global Robot Domestic Robots Artificial Brain Prometheus Labs<br />
Global Robot Domestic Robots Artificial Brain Frankenstein Labs<br />
Global Robot Domestic Robots Metal Housing Pieza de Acero<br />
Global Robot Domestic Robots Backplate Pieza de Acero<br />
Companies<br />
Company Company Founder Company Logo<br />
Allied Clock and Watch Horace Washington Sundial<br />
Global Robot Nils Neumann Gearbox<br />
Suppliers<br />
Supplier<br />
Supplier Country<br />
Tensile Globodynamics USA N. Amer.<br />
Pieza de Acero Mexico N. Amer.<br />
Microflux Belgium Europe<br />
Dakota Electrics USA N. Amer.<br />
Wheels 4 Less USA N. Amer.<br />
TransEuropa Italy Europe<br />
Prometheus Labs Luxembourg Europe<br />
Frankenstein Labs Germany Europe<br />
Supplier<br />
Continent<br />
InduSoft Web Studio 26–7
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Using VBScript<br />
3NF database<br />
The 3 rd Normalized Form eliminates the repeating Supplier Continent for a given Supplier Country by creating a<br />
separate table relating the Supplier Country to Supplier Continent.<br />
Suppliers and Parts By Company Division<br />
Company Division Part Type Supplier<br />
Allied Clock and Watch Clocks Spring Tensile Globodynamics<br />
Allied Clock and Watch Clocks Pendulum Tensile Globodynamics<br />
Allied Clock and Watch Clocks Spring Pieza de Acero<br />
Allied Clock and Watch Clocks<br />
Toothed Wheel Pieza de Acero<br />
Allied Clock and Watch Watches Quartz Crystal Microflux<br />
Allied Clock and Watch Watches Tuning Fork Microflux<br />
Allied Clock and Watch Watches Battery Dakota Electrics<br />
Global Robot Industrial Robots Flywheel Wheels 4 Less<br />
Global Robot Industrial Robots Axle Wheels 4 Less<br />
Global Robot Industrial Robots Axle TransEuropa<br />
Global Robot<br />
Industrial Robots Mechanical Arm TransEuropa<br />
Global Robot Domestic Robots Artificial Brain Prometheus Labs<br />
Global Robot Domestic Robots Artificial Brain Frankenstein Labs<br />
Global Robot Domestic Robots Metal Housing Pieza de Acero<br />
Global Robot Domestic Robots Backplate Pieza de Acero<br />
Companies<br />
Company Company Founder Company Logo<br />
Allied Clock and Watch Horace Washington Sundial<br />
Global Robot Nils Neumann Gearbox<br />
Countries<br />
Country Continent<br />
USA N. Amer.<br />
Mexico N. Amer.<br />
Belgium Europe<br />
Italy Europe<br />
Luxembourg Europe<br />
Suppliers<br />
Countries Supplier Supplier Country<br />
Tensile Globodynamics USA<br />
Pieza de Acero Mexico<br />
Microflux<br />
Belgium<br />
Dakota Electrics USA<br />
Wheels 4 Less USA<br />
TransEuropa Italy<br />
Prometheus Labs Luxembourg<br />
Frankenstein Labs Germany<br />
Source: Wikipedia<br />
26–8 InduSoft Web Studio
Exercise: Using VBScript<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
The 5 Rules of Data Normalization<br />
InduSoft Web Studio 26–9
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Using VBScript<br />
Estimating the size of a database (SQL Server 2000)<br />
http://msdn2.microsoft.com/en-us/library/aa933054(SQL.80).aspx<br />
Types of Relational Databases<br />
The flat database<br />
26–10 InduSoft Web Studio
Exercise: Using VBScript<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
InduSoft Web Studio 26–11
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Using VBScript<br />
26–12 InduSoft Web Studio
Exercise: Using VBScript<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Source: www.marcrettig.com<br />
InduSoft Web Studio 26–13
Chapter 27.<br />
Configuring the Database<br />
The following information pertains to the initial configuration of various databases for use with <strong>IWS</strong>. However,<br />
the user should consult the respective database documentation for updated information<br />
Microsoft Excel<br />
The following information can be used to configure Microsoft Excel to support an <strong>IWS</strong> application:<br />
Configuring Excel for use with <strong>IWS</strong> built-in Alarm, Event, Trend, and Grid Objects<br />
For use with the <strong>IWS</strong> Alarm, Event, Trend and Grid Objects, you must have a pre-existing Excel file (*.xls).<br />
Excel (the application) need not be present on the same PC as the <strong>IWS</strong> runtime. The Alarm, Event and<br />
Trend Objects should be configured to automatically create their own Table (i.e. Worksheet) using the<br />
default table name (e.g. Trend001 for the first Trend Worksheet).<br />
The Grid Object can be used to display an existing Excel Table (Worksheet), so in this case the Excel<br />
Worksheet must be defined and populated with some data. The Grid Object can be used to change or add<br />
to this data. When specifying an Excel Worksheet, be sure to enclose the Worksheet name in square<br />
brackets and put a $ character following the Excel Worksheet name. Also be sure to disable the Primary<br />
Key when using Excel, Excel does not support Primary Keys (E.g. when configuring the default database, in<br />
the Default Database Configuration dialog box, click on the Advanced button and check the Disable<br />
Primary Keys checkbox.<br />
As an alternative to the above, in a script worksheet you can either:<br />
1) Use a file command (<strong>IWS</strong> built-in file function or VBScript FileSystemObject) to copy and rename an<br />
existing (blank) Excel file for use with the <strong>IWS</strong> application.<br />
2) Use Microsoft Office <strong>Automation</strong> to create an Excel file, define the Worksheets and populate the<br />
Worksheet with any necessary data. Note that this option required Microsoft Excel (the application)<br />
to be present on the same PC as the <strong>IWS</strong> application.<br />
3) Using VBScript, use ADOX with the Microsoft Jet 4.0 ADO OLE-DB Provider to create a new<br />
instance of an Excel file, create one or more Tables (Worksheets) and define the Column data type.<br />
Example of how to specify an Excel Worksheet<br />
InduSoft Web Studio 27–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Configuring Excel for use with VBScript<br />
Depending on how VBScript is going to use an Excel Worksheet, the Excel file or Worksheet does not need<br />
to pre-exist prior to running the VBScript application. To read existing data for an <strong>IWS</strong> application<br />
configuration, obviously an Excel Worksheet needs to pre-exist. But if an Excel Worksheet is to be used to<br />
store data from an <strong>IWS</strong> VBScript application, there are a few options:<br />
1) Use Excel (the application) to create an empty Excel file with the Worksheets you need. Copy this<br />
file into your <strong>IWS</strong> application folder.<br />
2) Use a file command (<strong>IWS</strong> built-in file function or VBScript FileSystemObject) to copy and rename an<br />
existing blank Excel file for use with the <strong>IWS</strong> application.<br />
3) From VBScript, use ADOX with the Microsoft Jet 4.0 ADO OLE-DB Provider to create a new instance<br />
of an Excel file, create one or more Tables (Worksheets) and define the Column data type.<br />
4) If you have an existing blank Excel file on your <strong>IWS</strong> runtime PC (e.g. in your application folder), you<br />
can use the SQL statement Create Table to create a table (Worksheet) and columns. E.g.<br />
Dim oConn, strConn, myFile<br />
Set oConn = CreateObject("ADODB.Connection")<br />
myFile = $GetAppPath() & "test.xls"<br />
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & myfile &_<br />
";Extended Properties=""Excel 8.0;HDR=Yes"""<br />
mySQL = "Create Table MyTable " &_<br />
"(LastName varchar, FirstName varchar, Address varchar, Age Int)"<br />
With oConn<br />
.Open strConn<br />
.execute mySQL<br />
End With<br />
oConn.close<br />
Set oConn=Nothing<br />
Note:<br />
• The SQL Query is dependant on your ADO.NET Provider.<br />
• Microsoft Excel may not be the best choice for real-time data storage. It only allows for single access<br />
and if there are frequent reads & writes, the Database may need compaction.<br />
• When accessing an Excel file, in the SQL command you refer to a specific worksheet by the following<br />
syntax: [worksheetname$]<br />
• When accessing an Excel spreadsheet with no Headers, be sure to do the following<br />
- Make sure the Connection string has HDR=No in the Extended Properties field.<br />
- In your SQL command (and Recordset Object), your refer to each column as “Fx”, where x is the<br />
column number (e.g. “F1” for the first column, “F2” for the second, etc.)<br />
More information on using Jet SQL can be found at<br />
http://msdn2.microsoft.com/en-us/library/aa140011(office.10).aspx<br />
27–2 InduSoft Web Studio
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Microsoft Access<br />
The following information can be used to configure Microsoft Access to support an <strong>IWS</strong> application:<br />
Configuring Access for use with <strong>IWS</strong> built-in Alarm, Event, Trend, and Grid Objects<br />
For use with the <strong>IWS</strong> Alarm, Event, Trend and Grid Objects, you must have a pre-existing Access Database<br />
(*.mdb file). Access (the application) need not be present on the same PC as the <strong>IWS</strong> runtime. The Alarm,<br />
Event and Trend Objects should be configured to automatically create their own Table using the default<br />
table name (e.g. Trend001 for the first Trend Worksheet).<br />
The Grid Object can be used to display an existing Access Table, so in this case the Access table must be<br />
defined and populated with some data. The Table Name can be obtained from the Database or specified<br />
manually using the Table name. The Grid Object can be used to change or add to this data. Unlike<br />
Microsoft Excel, Access support Primary Keys – so Primary Keys should be enabled.<br />
As an alternative to the above, in a startup script you can either:<br />
1) Use a file command (<strong>IWS</strong> built-in file function or VBScript FileSystemObject) to copy and rename an<br />
existing Access Database for use with the <strong>IWS</strong> application.<br />
2) Use Microsoft Office <strong>Automation</strong> to create an Access Database, define the Database and populate<br />
the Worksheet with any necessary data. Note that this option required Microsoft Access (the<br />
application) to be present on the same PC as the <strong>IWS</strong> application.<br />
3) Using VBScript, use ADOX with the Microsoft Jet 4.0 ADO OLE-DB Provider to create a new<br />
instance of an Access Database, create one or more Tables and define the Column data type.<br />
Example of how to specify an Access Table<br />
InduSoft Web Studio 27–3
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Configuring Access for use with VBScript<br />
Depending on how VBScript is going to use an Access Table, the Access Table (*.mdb file) does not need<br />
to pre-exist prior to running the VBScript application. To read existing data for an <strong>IWS</strong> application<br />
configuration, obviously an Access Database and Table needs to pre-exist. But if an Access Database is to<br />
be used to store data from an <strong>IWS</strong> VBScript application, there are a few options:<br />
1) Use Access (the application) to create an empty Access Database with the Table(s) you need. Copy<br />
this file into your <strong>IWS</strong> application folder.<br />
2) Use a file command (<strong>IWS</strong> built-in file function or VBScript FileSystemObject) to copy and rename an<br />
existing blank Access database (*.mdb file) for use with the <strong>IWS</strong> application.<br />
3) From VBScript, use ADOX with the Microsoft Jet 4.0 ADO OLE-DB Provider to create a new instance<br />
of an Access Database, create one or more Tables and define the Column data type.<br />
4) If you have an existing blank Access file on your <strong>IWS</strong> runtime PC (e.g. in your application folder), you<br />
can use the SQL statement Create Table to create a table and columns. E.g.<br />
VBScript creating an Access Database with no Primary Key<br />
Dim strConn, myPath, oDB, Catalog<br />
Set Catalog = CreateObject("ADOX.Catalog")<br />
Set oDB = CreateObject("ADODB.Connection")<br />
myPath =$GetAppPath() & "test1.mdb"<br />
strConn="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & myPath & ";"<br />
Catalog.Create strConn<br />
'Create new database<br />
Set Catalog = Nothing<br />
With oDB<br />
'Connect to database and insert a new table<br />
.Open strConn<br />
.Execute "CREATE TABLE myTable “ &_<br />
“([Name] text(50) WITH Compression, " &_<br />
"[Address] text(150) WITH Compression, " & _<br />
"[City] text(50) WITH Compression, " & _<br />
"[State] text(2) WITH Compression, " & _<br />
"[Zip] text(6) WITH Compression, " & _<br />
"[Account] decimal(6))"<br />
End With<br />
Set oDB = Nothing<br />
VBScript creating an Access Database with a Primary Key<br />
Dim strConn, myPath, oDB, Catalog<br />
Set Catalog = CreateObject("ADOX.Catalog")<br />
Set oDB = CreateObject("ADODB.Connection")<br />
myPath =$GetAppPath() & "test1.mdb"<br />
strConn="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & myPath & ";"<br />
Catalog.Create strConn<br />
'Create new database<br />
Set Catalog = Nothing<br />
With oDB<br />
'Connect to database and insert a new table<br />
.Open strConn<br />
.Execute "CREATE TABLE myTable " &_<br />
"([employeeName] char(15) Not Null, " &_<br />
"[street] char(15), " &_<br />
"[city] char(10), " &_<br />
"primary key (employeeName));"<br />
End With<br />
27–4 InduSoft Web Studio
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Note:<br />
• The SQL Query is dependant on your ADO.NET Provider.<br />
• Microsoft Access may not be the best choice for real-time data storage. While it allows for multiple<br />
user access, if there are frequent reads & writes the Database may need periodic compaction.<br />
• When accessing an Access database, in the SQL command you refer to a specific Table by its name<br />
More information on Microsoft Jet SQL can be found at<br />
http://msdn2.microsoft.com/en-us/library/bb245488.aspx<br />
http://msdn2.microsoft.com/en-us/library/aa140011(office.10).aspx<br />
InduSoft Web Studio 27–5
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Microsoft SQL Server 2005<br />
SQL Server 2005 Types<br />
Microsoft offers several versions of SQL Server 2005. These versions include:<br />
- Enterprise Edition (for high-end Enterprises)<br />
- Standard Edition (for Small to Medium-size organizations)<br />
- Workgroup Edition (for Small organizations )<br />
- Express Edition (upgraded version of MSDE, for local database use)<br />
- Compact Edition (for light-weight mobile, embedded or desktop platform applications)<br />
The Enterprise Edition and Standard Edition support advanced features such as Database Mirroring and<br />
Failover Clustering. The Workgroup, Standard and Enterprise Editions include Business Intelligence (BI)<br />
Tools, as well as multiple CPUs with no limit on the Database size.<br />
Limitations of Express Edition and Compact Edition are:<br />
Feature Express Edition Compact Edition<br />
# of CPUs 1 1<br />
RAM<br />
1 GB max<br />
Database Size 4 GB max 4 GB max<br />
T-SQL Support Yes Subset<br />
Platforms XP, 2000, Server 2003, Vista XP, 2000, Server 2003, Vista, CE<br />
.NET Framework 2.0 2.0<br />
Install Size Disk 197MB 1.8 MB<br />
Install Size RAM<br />
1.7 MB<br />
Cost $0 $0<br />
Downloading SQL Server 2005 Express Edition or Compact Edition<br />
This section covers the installation and use of Microsoft SQL Server 2005 Express Edition or Compact<br />
Edition. These versions of Microsoft SQL Server 2005 are robust and reliable for use with many industrial<br />
applications and are available at no cost from Microsoft.<br />
The SQL Server 2005 Express Edition can be downloaded from Microsoft’s web site at:<br />
http://msdn.microsoft.com/vstudio/express/sql/download/<br />
The SQL Server 2005 Compact Edition can be downloaded from Microsoft’s web site at:<br />
http://www.microsoft.com/sql/editions/compact/downloads.mspx<br />
Be sure to download SQL Server 2005 Management Studio Express which can be used for Database<br />
configuration. SQL Server 2005 Management Studio can be used with both SQL Server 2005 Express<br />
Edition and SQL Server 2005 Compact Edition.<br />
http://msdn.microsoft.com/vstudio/express/sql/download/<br />
27–6 InduSoft Web Studio
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
MySQL 5.0<br />
The MySQL 5.0 database has become popular since it is open source software and is available at no cost<br />
under a GNU General Public License (GPL). It is widely used in Web-based applications and several industrial<br />
applications. From the MySQL web site (www.mysql.org), you can download the MySQL Database Server, an<br />
ODBC Driver and a MySQL Database Management tool. Presently, the MySQL website does not include an<br />
ADO.NET Provider for MySQL. 3 rd Party MySQL ADO.NET (OLE-DB) Providers are available from companies<br />
such as Cherry Hill Software (www.cherryhillsoftware.com), or you can use MyOLEDB (and ADO.NET OLE-DB<br />
Provider for MySQL **not officially supported by MySQL) found at http://sourceforge.net/projects/myoledb/.<br />
Downloading MySQL 5.0<br />
The MySQL 5.0 database can be downloaded from<br />
http://dev.mysql.com/downloads/mysql/5.0.html#win32<br />
The MySQL ODBC 3.51 driver (Connector) can be downloaded from<br />
http://dev.mysql.com/downloads/connector/odbc/3.51.html<br />
The MySQL Administrator (GUI Tool) can be downloaded from<br />
http://dev.mysql.com/downloads/gui-tools/5.0.html<br />
The MyOLEDB ADO.NET OLE-DB Provider v3.9.6 can be downloaded from<br />
http://sourceforge.net/project/showfiles.phpgroup_id=148466<br />
InduSoft Web Studio 27–7
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Oracle<br />
The current version of Oracle is 10g Release 2, designed for Grid Computing. Previous versions wer<br />
8i and 9i. Oracle 11g is announced but not yet available.<br />
Oracle 10g Release 2 Types<br />
Oracle offers several versions of Oracle 10g. These versions include:<br />
- Enterprise Edition (large enterprises)<br />
- Standard Edition (medium sized business environments)<br />
- Standard Edition One (small to medium enterprise environments)<br />
- Express Edition (entry-level, small footprint database)<br />
The Express Edition is free to develop, deploy and distribute. Stores up to 4GB of user data, 1GB of RAM and<br />
supports 1 CPU.<br />
The Oracle Database 10g Release 2 Express Edition for Windows is located at:<br />
http://www.oracle.com/technology/software/products/database/xe/htdocs/102xewinsoft.html<br />
Download the Oracle Database 10g for Express Edition (Universal or Wester European Edition)<br />
OracleXE.exe or OracleXEUniv.exe<br />
Download the Oracle Database 10g Express Client<br />
OracleXEClient.exe<br />
http://www.oracle.com/technology/products/database/application_express/html/3.0.1_and_xe.html<br />
27–8 InduSoft Web Studio
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
PostgreSQL<br />
PostgreSQL is another open-source database program. The main website is found at<br />
www.postgresql.org. This software is released under a BSD-style license compared to a GNU license<br />
commonly used for other open-sourced databases. The SQL language for PostgreSQL is called<br />
PL/pgSQL and closely resembles Oracle’s PL/SQL.<br />
Notes about PostgreSQL<br />
• There is a FAQ listed at http://www.postgresql.org/docs/faqs.FAQ_windows.html<br />
• Encoding Set to UTF-8 (UniCode). Works correctly for 8.2<br />
• PostgreSQL uses double quotes around strings<br />
• Online documentation is at http://www.postgresql.org/docs/8.2/interactive/index.html<br />
Download the PostgreSQL 8.2.4.1 Database Program:<br />
Go to http://www.postgresql.org/download/<br />
Go to http://www.postgresql.org/ftp/binary/v8.2.4/win32/ ,<br />
download the file postgresql-8.2.4-1.zip. Extract and install it.<br />
Must edit the pg_hba.conf file in the data directory to allow other host addresses other than local host to access<br />
the database. Then, need to restart PostgreSQL<br />
OLE-DB Provider<br />
http://pgfoundry.org/projects/oledb//<br />
click on PgOleDb v1.0.0.20<br />
Follow the installation directions (install into C:/Windows and run REGSVR32).<br />
Also see http://www.mono-project.com/PostgreSQL<br />
When setting up the default database<br />
Data Source Database Server Name, or IP Address of your PC (or 127.0.0.1)<br />
Location<br />
Name of your database<br />
User Name<br />
The User Name you established when installing PostgreSQL<br />
Password<br />
The Password you established when installing PostgreSQL<br />
InduSoft Web Studio 27–9
Chapter 28.<br />
SQL – The Language of Databases<br />
Structured Query Language (SQL) is a standard computer language used to access and manipulate relational<br />
databases such as Microsoft Access, Microsoft SQL Server, Oracle, MySQL, etc. SQL is a declarative language<br />
(i.e. sequence of commands for the computer to perform), whereas languages such as C or Basic are<br />
imperative languages (i.e. a set of statements that change a program state).<br />
Although SQL is an ANSI standard language (ANSI SQL-92, SQL:1999, SQL:2003, SQL:2006) and a set of<br />
ISO standards, database manufacturers often provide proprietary extensions to the SQL language that are<br />
incompatible among different databases. So it is best to check the database documentation to determine the<br />
SQL commands that are supported. However, all databases support standard SQL keywords that allow:<br />
- running queries on the database, retrieving a set of records (a recordset) from the database<br />
- inserting new records into the database<br />
- deleting records from the database<br />
- updating records in the database<br />
The SQL Language is broken into three (3) groups of statements, each performing different types of functions.<br />
These are:<br />
1. SQL Schema Statements<br />
This category of statements form the Data Definition Language (DDL) part of SQL. The DDL is used<br />
to manage the Data Objects that contain the data. Schema means a plan or model to the database.<br />
Example DDL statements include:<br />
Category Statements Function<br />
Schema CREATE TABLE Creates a table<br />
Schema DROP TABLE Deletes a table<br />
Schema ALTER TABLE Alter (change) a Table<br />
Schema CREATE INDEX Creates an Index (search key)<br />
Schema DROP INDEX Deletes an Index (search key)<br />
In an <strong>IWS</strong> application using the Alarm, Event, or Trend Objects, the built-in ADO.NET will use DDL<br />
statements to create the Tables required to store data, although an existing database must be created<br />
separately.<br />
2. SQL Data Statements<br />
This category of statements form the Data Manipulation Language (DML) part of SQL. The DML is<br />
used to manage data within the database. For example, DML is used to extract, add, modify and delete<br />
information contained in the relational database tables. DML statements have no effect on the structure<br />
of the database. Example DML statements include:<br />
Category Statements Function<br />
Data SELECT Extracts date from a database table<br />
Data INSERT Inserts date into a database table<br />
Data DELETE Deletes data from a database table<br />
Data UPDATE Updates data in a database table<br />
In an <strong>IWS</strong> application using the Alarm, Event, or Trend Objects, the built-in ADO.NET will use DML<br />
statements to retrieve, add and/or remove data from Tables.<br />
3. SQL Transaction Statements<br />
The Transaction statements are generally used to perform actions on the database. These statements<br />
are often dependent on the database.<br />
Category Statements Function<br />
Transaction COMMIT Makes data modifications part of the database<br />
InduSoft Web Studio 28–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
SQL Nomenclature<br />
SQL Nomenclature<br />
• The semicolon can be used to separate multiple SQL statements in databases that allow more than one<br />
SQL statement in a call to the database server. Some databases force you to put a semicolon at the<br />
end of a statement. This is not required for Microsoft Access or Microsoft SQL Server.<br />
• The asterisk is used to select all<br />
• Single quotes are used for text values, i.e. strings (most databases will support double quotes as well).<br />
• Numeric values should not be enclosed in quotes<br />
• Comments can be added to a SQL statement by using a double-dash (--), curly brackets (braces) or C-<br />
style /* comment */ (supports multi-line comments).<br />
SQL Coding Conventions<br />
As with any programming language, following standard coding conventions makes the code more readable to<br />
other users, as well as to you. With SQL, there are a few simple coding conventions:<br />
• Use uppercase for all SQL Keywords<br />
• If you must break a line of SQL code, do so at a major section of the SQL statement<br />
Example: Well-formatted SQL Code<br />
CREATE TABLE tblCustomers<br />
(CustomerID INTEGER NOT NULL,<br />
[Last Name] TEXT(50) NOT NULL,<br />
[First Name] TEXT(50) NOT NULL,<br />
Phone TEXT(10),<br />
Email TEXT(50))<br />
Example: Poorly formatted SQL Code<br />
CREATE TABLE tblCustomers (CustomerID INTEGER NOT NULL, [Last Name] TEXT(50)<br />
NOT NULL, [First Name] TEXT(50) NOT NULL, Phone TEXT(10), Email TEXT(50))<br />
28–2 InduSoft Web Studio
SQL Language Derivatives<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
SQL Language Derivatives<br />
• Microsoft JET SQL<br />
The Microsoft JET Database Engine supports several Microsoft products including Access and Excel.<br />
The JET (Joint Engine Technology) 4.0 Engine supports Microsoft Access 2000, 2002 and 2003, as<br />
well as Excel and Delimited Text files.<br />
• Microsoft Transact-SQL<br />
• MySQL<br />
• Oracle PL/SQL<br />
• Postgres PL.pgSQL<br />
Notes:<br />
• When used with <strong>IWS</strong>, SQL Statements are typically enclosed in quotation marks “ and used with the<br />
Connection Object, Command Object or Recordset Object.<br />
InduSoft Web Studio 28–3
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
SQL Operators<br />
SQL Operators<br />
The ANI SQL-92 standard supports a number of basic operators. In addition, many relational databases support<br />
additional operators that are extensions to the ANSI-92 standard.<br />
Arithmetic Operators<br />
Arithmetic operators perform mathematical operations on two expressions of any of the data types of the<br />
numeric data type category. The plus (+) and minus (-) can also be used to perform arithmetic operations on<br />
datetime and smalldatetime values.<br />
Operator Function Description<br />
+ Add Adds two numbers<br />
- Subtract Subtract one number from the other<br />
* Multiply Multiply two numbers together<br />
/ Divide Divide one number by the other<br />
% Modulo Returns the integer remainder of a division. For example, 12 % 5 = 2 because<br />
the remainder of 12 divided by 5 is 2.<br />
Assignment Operator<br />
The assignment operator is used to set a SQL variable (with a proceeding @) to a value returned by an<br />
expression. It can also be used to establish the relationship between a column heading and the expression<br />
defining the values for the column.<br />
Operator Function Description<br />
= Assignment Can be used to assign a value (or result of an expression) to a variable, can<br />
also establish a relationship between a column heading and the expression<br />
defining the values for the column.<br />
28–4 InduSoft Web Studio
SQL Operators<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Bitwise Operators<br />
Bitwise operators perform bit manipulations between two expressions of any of the data types of the integer<br />
data type category.<br />
Operator Function Description<br />
& Bitwise AND Bitwise AND (two operands).<br />
| Bitwise OR Bitwise OR (two operands).<br />
^<br />
Bitwise Exclusive<br />
OR<br />
Bitwise exclusive OR (two operands).<br />
The operands for bitwise operators can be any of the data types of the integer or binary string data type<br />
categories (except for the image data type), with the exception that both operands cannot be any of the data<br />
types of the binary string data type category. The table shows the supported operand data types.<br />
Left operand<br />
binary<br />
bit<br />
int<br />
smallint<br />
tinyint<br />
varbinary<br />
Right operand<br />
int, smallint, or tinyint<br />
int, smallint, tinyint, or bit<br />
int, smallint, tinyint, binary, or varbinary<br />
int, smallint, tinyint, binary, or varbinary<br />
int, smallint, tinyint, binary, or varbinary<br />
int, smallint, or tinyint<br />
Comparison Operators<br />
Comparison operators test whether or not two expressions are the same. Comparison operators can be used<br />
on all expressions except expressions of the text, ntext, or image data types.<br />
Operator<br />
Description<br />
= Equal to<br />
> Greater than<br />
< Less than<br />
>= Greater than or equal to<br />
Not greater than (not SQL-92 standard)<br />
The result of a comparison operator has the Boolean data type, which has three values: TRUE, FALSE, and<br />
UNKNOWN. Expressions that return a Boolean data type are known as Boolean expressions.<br />
Unlike other SQL Server data types, a Boolean data type cannot be specified as the data type of a table column<br />
or variable, and cannot be returned in a result set.<br />
InduSoft Web Studio 28–5
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
SQL Operators<br />
Null Handling<br />
It should be noted that ANSI SQL-92 says that NULLS are unknown values. When SET ANSI_NULLS is ON<br />
(default setting), any comparison to a NULL is to fail (i.e. return False). E.g.<br />
NULL = NULL returns False<br />
NULL NULL returns False<br />
When SET ANSI_NULLS is O<strong>FF</strong>, the same rules apply, except that the statement:<br />
NULL = NULL returns True<br />
Use SQL statements such as<br />
Where ColumnName IS NULL<br />
But avoid using SQL statements such as<br />
Where ColumnName = Null<br />
Boolean Expressions<br />
Expressions with Boolean data types are used in the WHERE clause to filter the rows that qualify for the search<br />
conditions and in control-of-flow language statements such as IF and WHILE.<br />
28–6 InduSoft Web Studio
SQL Operators<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Logical Operators<br />
Logical operators test for the truth of some condition. Logical operators, like comparison operators, return a<br />
Boolean data type with a value of TRUE or FALSE.<br />
Operator<br />
ALL<br />
AND<br />
ANY<br />
Description<br />
TRUE if all of a set of comparisons are TRUE.<br />
TRUE if both Boolean expressions are TRUE.<br />
TRUE if any one of a set of comparisons are TRUE.<br />
BETWEEN TRUE if the operand is within a range.<br />
EXISTS<br />
IN<br />
LIKE<br />
NOT<br />
OR<br />
SOME<br />
TRUE if a subquery contains any rows.<br />
TRUE if the operand is equal to one of a list of expressions.<br />
TRUE if the operand matches a pattern.<br />
Reverses the value of any other Boolean operator.<br />
TRUE if either Boolean expression is TRUE.<br />
TRUE if some of a set of comparisons are TRUE.<br />
Unary Operators<br />
Unary operators perform an operation on only one expression of any of the data types of the numeric data type<br />
category.<br />
Operator Function Description<br />
+ Positive Numeric value is positive.<br />
- Negative Numeric value is negative.<br />
~ Bitwise NOT Returns the ones complement of the number.<br />
The + (Positive) and - (Negative) operators can be used on any expression of any of the data types of the<br />
numeric data type category. The ~ (Bitwise NOT) operator can be used only on expressions of any of the data<br />
types of the integer data type category.<br />
String Concatenation Operator<br />
The string concatenation operator allows string concatenation with the addition sign (+), which is also known as<br />
the string concatenation operator. All other string manipulation is handled through string functions such as<br />
SUBSTRING.<br />
By default, an empty string is interpreted as an empty string in INSERT or assignment statements on data of<br />
the varchar data type. In concatenating data of the varchar, char, or text data types, the empty string is<br />
interpreted as an empty string. For example, 'abc' + '' + 'def' is stored as 'abcdef'. However, if the<br />
sp_dbcmptlevel compatibility level setting is 65, empty constants are treated as a single blank character and<br />
'abc' + '' + 'def' is stored as 'abc def'.<br />
When two character strings are concatenated, the collation of the result expression is set following the rules of<br />
collation precedence.<br />
InduSoft Web Studio 28–7
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
SQL Operators<br />
Operator Precedence<br />
When a complex expression has multiple operators, operator precedence determines the sequence in which<br />
the operations are performed. The order of execution can significantly affect the resulting value.<br />
Operators have these precedence levels. An operator on higher levels is evaluated before an operator on a<br />
lower level:<br />
• + (Positive), - (Negative), ~ (Bitwise NOT)<br />
• * (Multiply), / (Division), % (Modulo)<br />
• + (Add), (+ Concatenate), - (Subtract), & (Bitwise AND)<br />
• =, >, =, , !< (Comparison operators)<br />
• ^ (Bitwise Exclusive OR), | (Bitwise OR)<br />
• NOT<br />
• AND<br />
• ALL, ANY, BETWEEN, IN, LIKE, OR, SOME<br />
• = (Assignment)<br />
When two operators in an expression have the same operator precedence level, they are evaluated left to right<br />
based on their position in the expression<br />
28–8 InduSoft Web Studio
SQL Operators<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
SQL Functions<br />
An SQL function is a special type of command in the SQL language used to return a single value. There can be<br />
one or more input parameters, or there can be no input parameters that are required. These Functions are<br />
typically used with a DML Query Statement.<br />
Aggregate Functions<br />
Function<br />
AVG (column)<br />
COUNT(*)<br />
COUNT (column)<br />
COUNT (DISTINCT<br />
column)<br />
MIN(column n)<br />
MAX(column )<br />
SUM(column)<br />
Usage<br />
Computes the average value of a column by the column<br />
Counts all rows in the specified table or view<br />
Counts the rows defined by the column<br />
Counts the number of distinct values of the column<br />
Finds the minimum value in a column from the column<br />
Finds the maximum value in a column from the column<br />
Computes the sum of column values from the column<br />
Notes:<br />
• The Functions AVG & SUM are not supported by all databases, but are supported by Microsoft Access,<br />
Microsoft SQL Server, Oracle, MySQL and PostgreSQL<br />
Scalar Functions<br />
Function<br />
UCASE(c)<br />
LCASE(c)<br />
MID(c,start[,end])<br />
LEN(c)<br />
INSTR(c,char)<br />
LEFT(c,number_of_char)<br />
RIGHT(c,number_of_char)<br />
ROUND(c,decimals)<br />
MOD(x,y)<br />
NOW()<br />
FORMAT(c,format)<br />
DATEDI<strong>FF</strong>(d,date1,date2)<br />
Usage<br />
Converts a field to upper case<br />
Converts a field to lower case<br />
Extract characters from a text field<br />
Returns the length of a text field<br />
Returns the numeric position of a named character within a text<br />
field<br />
Return the left part of a text field requested<br />
Return the right part of a text field requested<br />
Rounds a numeric field to the number of decimals specified<br />
Returns the remainder of a division operation<br />
Returns the current system date<br />
Changes the way a field is displayed<br />
Used to perform date calculations<br />
InduSoft Web Studio 28–9
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
SQL Operators<br />
DatePart() Function<br />
The following syntax is used for the DatePart()<br />
SELECT DATEPART(Part, dateVariable)<br />
E.g. SELECT DATEPART(month, ‘2007-08-05’)<br />
{returns August}<br />
Part Description Abbreviation(s)<br />
Year returns a 4 digit year yy,yyyy<br />
Quarter returns a value 1-4 representing the year's quarter qq,q<br />
Month returns the numeric equivalent month (1-12) mm,m<br />
Dayofyear returns the day of the year (1-365) dy,y<br />
Day returns the day of the month (1-31) dd,d<br />
Week returns the number of the week (1-53) wk,ww<br />
Weekday returns the number of the day of the week (1-7) dw<br />
Hour returns the number of hours for a given time hh<br />
Minute returns the number of minutes from a given time mi,n<br />
Second returns the number of seconds in a given time ss,s<br />
Millisecond returns the number of milliseconds in a given time ms<br />
28–10 InduSoft Web Studio
SQL Operators<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
System Values<br />
Function<br />
CURRENT_DATE<br />
CURRENT_TIME<br />
Usage<br />
Identifies the current date<br />
Identifies the current time<br />
CURRENT_TIMESTAMP Identifies the current date and time<br />
CURRENT_USER<br />
SESSION_USER<br />
SYSTEM_USER<br />
Identifies the active database user as identified by the Database<br />
Server<br />
Identifies the currently active Authorization ID, if it differs from the user<br />
Identifies the currently active user within the host operating system<br />
Notes:<br />
• Every SQL database has its own version of date functions.<br />
Common (but non-ANSI-92 Standard) Functions<br />
Function<br />
ABS(x)<br />
SIGN(x)<br />
MOD(x,y)<br />
FLOOR(x)<br />
CEILING(x) or CEIL(x)<br />
POWER(x,y)<br />
ROUND(x,d)<br />
SQRT(x)<br />
Usage<br />
Returns the absolute value of x<br />
Returns the sign of input x as -1, 0, or 1 (negative, zero, or positive<br />
respectively)<br />
Modulo - returns the integer remainder of x divided by y (same as x%y)<br />
Returns the largest integer value that is less than or equal to x<br />
Returns the smallest integer value that is greater than or equal to x<br />
Returns the value of x raised to the power of y<br />
Returns the value of x rounded to the number of decimal places specified<br />
by the value d<br />
Returns the square-root value of x<br />
InduSoft Web Studio 28–11
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
SQL DataTypes<br />
SQL DataTypes<br />
SQL recognizes different types of data that generally fall into one of three groupings; numeric, character strings<br />
and other. The specific data types depends on the database used. For example, Microsoft SQL Server 2005<br />
uses the following data types:<br />
Numeric<br />
Category Data Type Description<br />
Integer BIGINT Integer (whole number) data from -2^63 (-9,223,372,036,854,775,808)<br />
through 2^63-1 (9,223,372,036,854,775,807).<br />
Integer INT Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1<br />
(2,147,483,647).<br />
Integer SMALLINT Integer data from -2^15 (-32,768) through 2^15 - 1 (32,767).<br />
Integer TINYINT Integer data from 0 through 255.<br />
Real FLOAT Floating precision number data with the following valid values: -1.79E + 308<br />
through -2.23E - 308, 0 and 2.23E + 308 through 1.79E + 308.<br />
Real REAL Floating precision number data with the following valid values: -3.40E + 38<br />
through -1.18E - 38, 0 and 1.18E - 38 through 3.40E + 38.<br />
decimal<br />
and<br />
numeric<br />
DECIMAL Fixed precision and scale numeric data from -10^38 +1 through 10^38 –1<br />
decimal<br />
and<br />
numeric<br />
NUMERIC<br />
Functionally equivalent to decimal.<br />
bit BIT Integer data with either a 1 or 0 value.<br />
Binary<br />
Strings<br />
Binary<br />
Strings<br />
BINARY<br />
VARBINARY<br />
Fixed-length binary data with a maximum length of 8,000 bytes.<br />
Variable-length binary data with a maximum length of 8,000 bytes.<br />
Image IMAGE Variable-length binary data with a maximum length of 2^31 - 1<br />
(2,147,483,647) bytes.<br />
money and<br />
smallmoney<br />
money and<br />
smallmoney<br />
MONEY<br />
SMALLMONEY<br />
Date & Time DATETIME<br />
Monetary data values from -2^63 (-922,337,203,685,477.5808) through<br />
2^63 - 1 (+922,337,203,685,477.5807), with accuracy to a ten-thousandth of<br />
a monetary unit.<br />
Monetary data values from -214,748.3648 through +214,748.3647, with<br />
accuracy to a ten-thousandth of a monetary unit.<br />
Date and time data from January 1, 1753, through December 31, 9999, with<br />
an accuracy of three-hundredths of a second, or 3.33 milliseconds.<br />
Date & Time SMALLDATETIME Date and time data from January 1, 1900, through June 6, 2079, with an<br />
accuracy of one minute.<br />
TimeStamp TIMESTAMP A database-wide unique number that gets updated every time a row gets<br />
updated.<br />
28–12 InduSoft Web Studio
SQL DataTypes<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Character Strings<br />
Category Data Type Description<br />
Characters CHAR Fixed-length non-Unicode character data with a maximum length of 8,000<br />
characters.<br />
Characters VARCHAR Variable-length non-Unicode data with a maximum of 8,000 characters.<br />
Characters TEXT Variable-length non-Unicode data with a maximum length of 2^31 - 1<br />
(2,147,483,647) characters.<br />
Unicode NCHAR Fixed-length Unicode data with a maximum length of 4,000 characters.<br />
Unicode<br />
NVARCHAR Variable-length Unicode data with a maximum length of 4,000 characters.<br />
sysname is a system-supplied user-defined data type that is functionally<br />
equivalent to nvarchar(128) and is used to reference database object names<br />
Unicode NTEXT Variable-length Unicode data with a maximum length of 2^30 - 1 (1,073,741,823)<br />
characters.<br />
Other<br />
Category Data Type<br />
Description<br />
Cursor CURSOR A reference to a cursor.<br />
Misc. SQL_VARIANT A data type that stores values of various SQL Server-supported data types,<br />
except text, ntext, timestamp, and sql_variant.<br />
Table TABLE A special data type used to store a result set for later processing .<br />
Unique<br />
Identifier<br />
UNIQUEIDENTIFIER A globally unique identifier (GUID).<br />
XML<br />
Notes:<br />
• The dataType of a field (column) is generally defined when the column is created in the table<br />
• When the table is created, you often have the choice of allowing or disallowing NULL values. A NULL<br />
value means that nothing exists in the table field.<br />
InduSoft Web Studio 28–13
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Constraints and Keys<br />
Constraints and Keys<br />
Databases usually support multiple Constraint types, generally used to ensure the database integrity by also<br />
used for Query optimization. Domain Constraints apply to one or more columns (e.g. ensuring the data entered<br />
into the column conforms to the specified data type and any rules), while Entity Constraints apply to individual<br />
rows.<br />
One type of Constraint that we will use is a Primary Key Constraint. A Primary Key is a unique identifier of a<br />
row, its value must be unique to each row and cannot contain a NULL value. Primary Keys are the most<br />
important of all Keys and all Constraints. A table can have only one Primary Key.<br />
Primary Keys can be created as part of the Column definition in the CREATE TABLE statement or in the<br />
ALTER TABLE statement. The use of integer values as a Primary Key is highly recommended, as is the use of<br />
a Primary Key in every Table – this is what makes a relational database work.<br />
A Foreign Key is used to ensure data integrity within a column, as well as create a relationship to another table.<br />
To use a Foreign key, you must define the table which the Foreign Key references, and the column in the<br />
referenced table.<br />
Examples of creating Keys are:<br />
Creating a Primary Key when creating a Table<br />
USE myDB<br />
CREATE TABLE EmployeeData<br />
(EmployeeID INT NOT NULL PRIMARY KEY,<br />
First VARCHAR(15),<br />
Last VARCHAR(20),<br />
Age int,<br />
City VARCHAR(20),<br />
State VARCHAR(20))<br />
Creating a Primary Key when the Table already exists<br />
USE myDB<br />
ALTER TABLE Customers<br />
ADD CONSTRAINT CustomerID<br />
PRIMARY KEY (CustomerID)<br />
Creating a Foreign Key when creating the Table<br />
USE myDB<br />
CREATE TABLE Orders<br />
(OrderID INT NOT NULL PRIMARY KEY,<br />
CustomerID int FOREIGN KEY REFERENCES Customers (CustomerID),<br />
OrderDate smallDateTime NOT NULL,<br />
Item VARCHAR(20) )<br />
Creating a Foreign Key when the Table already exists<br />
USE myDB<br />
ALTER TABLE Orders<br />
ADD CONSTRAINT CustomerID<br />
FOREIGN KEY (CustomerID) REFERENCES Customers (CustomerID)<br />
28–14 InduSoft Web Studio
DDL Schema Statements<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
DDL Schema Statements<br />
The DDL allows the user to define new tables, as well as columns and indexes to be used in the tables. Certain<br />
Database Engines support Database creation and deletion as well.<br />
CREATE DATABASE<br />
The CREATE DATABASE statement is used to create a new database in the Database Server. The syntax of<br />
this command is:<br />
CREATE DATABASE database_name<br />
DELETE DATABASE<br />
The DELETE DATABASE statement is used to delete an existing database in the Database Server. The syntax<br />
of this command is:<br />
DROP DATABASE database_name<br />
Notes:<br />
• Not all Database Servers support the CREATE DATABASE and DELETE DATABASE statements.<br />
Check with your database server documentation.<br />
• Once you use the CREATE DATABASE statement, you must also use the CREATE TABLE statement.<br />
InduSoft Web Studio 28–15
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
DDL Schema Statements<br />
CREATE TABLE Statement<br />
The CREATE TABLE statement is used to create a new table in the database. The basic form of the CREATE<br />
TABLE statement is<br />
CREATE TABLE tableName<br />
(columnName1 dataType [constraint],<br />
columnName2 dataType [constraint],<br />
columnName3 dataType [constraint],<br />
.......)<br />
[ ] = optional<br />
The datatype must correspond to the datatypes supported by the database you are using. Constraints are<br />
optional, and include:<br />
NULL<br />
Indicates the column value can be a null<br />
NOT NULL<br />
Indicates the column value cannot be a null<br />
PRIMARY KEY<br />
Unique identifier for each row. Must be a unique, non-Null value<br />
FOREIGN KEY<br />
Adds a foreign key constraint<br />
For example, suppose we wanted to create the table as shown below.<br />
Table: EmployeeInfo<br />
First Last ID Age City State<br />
John Smith 64230 45 Ann Arbor Michigan<br />
Suzanne Collins 62175 35 Dexter Michigan<br />
Randall Carson 60748 40 Ann Arbor Michigan<br />
Bill Gross 52786 55 Jackson Michigan<br />
Joanne Thomas 50768 48 Ann Arbor Michigan<br />
Maryanne Lewis 68200 24 Plymouth Michigan<br />
Walter Williams 65891 35 Ann Arbor Michigan<br />
Karl Walters 68985 30 Sylvania Ohio<br />
Erica Edwards 59732 48 Toledo Ohio<br />
Elroy Clinger 69394 26 Chelsea Michigan<br />
Ginger Rogers 69710 22 Ann Arbor Michigan<br />
The SQL code for creating this table is:<br />
CREATE TABLE EmployeeInfo<br />
(First VARCHAR(15),<br />
Last VARCHAR(20),<br />
ID NUMBER(5),<br />
Age NUMBER(3),<br />
City VARCHAR(20),<br />
State VARCHAR(20))<br />
•<br />
28–16 InduSoft Web Studio
DDL Schema Statements<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Other examples of the CREATE TABLE statement include:<br />
CREATE TABLE tblCustomers<br />
(CustomerID INTEGER,<br />
[Customer Name] TEXT(50),<br />
Phone TEXT(10),<br />
Email TEXT(50))<br />
CREATE TABLE tblCustomers<br />
(CustomerID INTEGER NOT NULL,<br />
[Customer Name] TEXT(50) NOT NULL,<br />
Phone TEXT(10),<br />
Email TEXT(50))<br />
CREATE TABLE weekly_payroll<br />
(employee_id VARCHAR(10) PRIMARY KEY,<br />
total_hours INT NULL,<br />
hourly_rate MONEY NOT NULL,);<br />
InduSoft Web Studio 28–17
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
DDL Schema Statements<br />
TRUNCATE TABLE Statement<br />
The TRUNCATE TABLE statement is used to get rid of all of the data in a table. However, this statement does<br />
not eliminate the table itself. The basic form of the TRUNCATE TABLE statement is:<br />
TRUNCATE TABLE tableName<br />
28–18 InduSoft Web Studio
DDL Schema Statements<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
DROP TABLE Statement<br />
The DROP TABLE statement is used to delete all rows in the database and the table definition from the<br />
database. The basic form of the DROP TABLE statement is<br />
DROP TABLE tableName<br />
An example of the DROP TABLE statement is:<br />
DROP TABLE EmployeeInfo<br />
This will delete all records in the EmployeeInfo table and delete the table itself.<br />
InduSoft Web Studio 28–19
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
DDL Schema Statements<br />
ALTER TABLE Statement<br />
The ALTER TABLE statement can be used to add and drop columns from a table, or to change the name or<br />
data type of a column.<br />
Adding a column<br />
ALTER TABLE tableName<br />
ADD columnName dataType<br />
For example:<br />
ALTER TABLE tblCustomers ADD CustomerCity VARCHAR(20)<br />
ALTER TABLE orders ADD order_date<br />
TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL<br />
Adding a unique column<br />
ALTER TABLE tableName<br />
ADD UNIQUE columnName dataType<br />
For example:<br />
ALTER TABLE tblCustomers ADD UNIQUE CustomerCity VARCHAR(20)<br />
Add a Constraint<br />
ALTER TABLE tableName<br />
ADD CONSTRAINT columnName DEFAULT defaultValue<br />
Dropping a column<br />
ALTER TABLE tableName<br />
DROP columnName<br />
For example:<br />
ALTER TABLE tblCustomers DROP CustomerCity<br />
Changing a column<br />
ALTER TABLE tableName CHANGE<br />
CHANGE columnName columnName1 dataType<br />
For example:<br />
ALTER TABLE tblCustomers CHANGE CustomerCity VARHAR(20)<br />
ALTER TABLE tblCustomers CHANGE CustomerCity City VARCHAR(20)<br />
NOT NULL AUTO_INCREMENT<br />
Notes:<br />
• Microsoft SQL Server supports the ALTER COLUMN clause instead of the CHANGE clause<br />
28–20 InduSoft Web Studio
DDL Schema Statements<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
CREATE INDEX<br />
An index can be used with an existing table to locate rows quickly and efficiently during queries. You can create<br />
an index on one or more columns in a table. Each index has its own name.<br />
There are two types of indexes; a Simple Index and a Unique Index. A simple index will allow duplicate index<br />
values, while a Unique Index will not.<br />
Unique Index<br />
CREATE UNIQUE INDEX indexName<br />
ON tableName (columnName)<br />
Simple Index<br />
CREATE INDEX indexName<br />
ON tableName (columnName)<br />
DROP INDEX<br />
The DROP INDEX statement is used to delete an existing Index in a table. The format of the DROP INDEX<br />
statement varies by the particular database used.<br />
DROP INDEX indexName ON tableName<br />
DROP INDEX tableName.indexName<br />
DROP INDEX indexName<br />
ALTER TABLE tableName DROP INDEX indexName<br />
For JET SQL (Access, Excel)<br />
For Microsoft SQL Server<br />
For Oracle<br />
For MySQL<br />
Notes:<br />
• Check your database documentation for the proper format of the DROP INDEX and CREATE INDEX<br />
statements.<br />
• The DROP INDEX statement may not apply to indexes created by defining a PRIMARY KEY<br />
InduSoft Web Studio 28–21
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
DML Query Statements<br />
DML Query Statements<br />
Queries are loosely defined as a set of SQL commands that perform a function against the database, generally<br />
returning a set of records (a Recordset) from the database or moving data to the database.<br />
To illustrate the operation of these queries, the following tables will be used<br />
Table: EmployeeInfo<br />
First Last ID Age City State<br />
John Smith 64230 45 Ann Arbor Michigan<br />
Suzanne Collins 62175 35 Dexter Michigan<br />
Randall Carson 60748 40 Ann Arbor Michigan<br />
Bill Gross 52786 55 Jackson Michigan<br />
Joanne Thomas 50768 48 Ann Arbor Michigan<br />
Maryanne Lewis 68200 24 Plymouth Michigan<br />
Walter Williams 65891 35 Ann Arbor Michigan<br />
Karl Walters 68985 30 Sylvania Ohio<br />
Erica Edwards 59732 48 Toledo Ohio<br />
Elroy Clinger 69394 26 Chelsea Michigan<br />
Ginger Rogers 69710 22 Ann Arbor Michigan<br />
Table: Orders<br />
CustomerID OrderDate Item Qty Price<br />
0981 25-Aug-2007 Mug 10 40.80<br />
1035 16-Mar-2007 Stein 5 120.80<br />
0976 15-Jul-2007 Bottle 18 36.00<br />
1985 08-Aug-2007 Jar 16 48.32<br />
0758 13-Jun-2007 Lid 45 4.50<br />
Table: Customers<br />
CustomerID First Last City State<br />
0758 Barry Piper Phoenix Arizona<br />
0981 Jim Weber Milwaukee Wisconsin<br />
0976 Janis Cunningham Eugene Oregon<br />
1985 Elroy Klinger Pittsburgh Pennsylvania<br />
0823 Claudio Sanchez Cleveland Ohio<br />
1035 Donald Graham Austin Texas<br />
0911 Roberto Mendoza Chicago Illinois<br />
1022 Julia Mitchell Fort Collins Colorado<br />
0998 George Walker Tampa Florida<br />
1164 Eddie Schultz Atlanta Georgia<br />
1511 Ginger Dalton Green Bay Wisconsin<br />
28–22 InduSoft Web Studio
DML Query Statements<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
SELECT Statement<br />
The SELECT statement is probably the most commonly used DML Query statement and is used to query the<br />
database and return one or more records into a result set, typically stored in a ADO Recordset when using <strong>IWS</strong>.<br />
There are several forms of the SELECT statement but the basic form of the SELECT statement is<br />
SELECT [ALL | DISTINCT] column1<br />
[, column2, ….]<br />
FROM table1 [, table2,…]<br />
[WHERE columnName OPERATOR value<br />
[AND|OR columnName Operator value]]<br />
[GROUP BY columnList]<br />
[HAVING conditions]<br />
[ORDER BY columnList [ASC | DESC]]<br />
[[LEFT | RIGHT | FULL] [OUTER | INNER] JOIN]<br />
[LIMIT value [O<strong>FF</strong>SET value]]<br />
[ ] = optional parameters or arguments<br />
The ALL and DISTINCT keywords are used to select all (ALL) records (the default) or only unique (DISTINCT)<br />
records from the specified table. Use of the DISTINCT keyword will cause all duplicate records to be ignore in<br />
the search result.<br />
This SELECT statement will return a set of records from the specified table that contains data from the columns<br />
specified. Instead of specifying a column name, you can use the asterick “*” character to select all columns.<br />
For example, the SELECT statement can be used as follows:<br />
SELECT First, Last<br />
FROM EmployeeInfo<br />
This will return the following set of records<br />
John<br />
Suzanne<br />
Randall<br />
Bill<br />
Joanne<br />
Maryanne<br />
Walter<br />
Karl<br />
Erica<br />
Elroy<br />
Ginger<br />
Smith<br />
Collins<br />
Carson<br />
Gross<br />
Thomas<br />
Lewis<br />
Williams<br />
Walters<br />
Edwards<br />
Clinger<br />
Rogers<br />
In addition, there are a number of optional clauses that can be used to narrow the returned recordset to only the<br />
records of interest. These clauses include:<br />
InduSoft Web Studio 28–23
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
DML Query Statements<br />
A. WHERE clause<br />
The WHERE clause specifies the data values or rows that will be returned based on the criteria<br />
specified following in the WHERE clause. The syntax of the SELECT statement when using the<br />
WHERE clause is:<br />
SELECT column1<br />
[, column2, ….]<br />
FROM tableName<br />
WHERE columnName OPERATOR value<br />
[AND|OR columnName Operator value]<br />
Conditional Operator selections in the WHERE clause are:<br />
= Equal<br />
> Greater than<br />
< Less than<br />
>= Greater than or equal<br />
=45<br />
This will return the following set of records<br />
John Smith 64230 45 Ann Arbor Michigan<br />
Bill Gross 52786 55 Jackson Michigan<br />
Joanne Thomas 50768 48 Ann Arbor Michigan<br />
Erica Edwards 59732 48 Toledo Ohio<br />
This example finds employees in a City older than 25 and sorts by the employee first name:<br />
SELECT *<br />
FROM EmployeeInfo<br />
WHERE City=”Ann Arbor” AND Age > 25<br />
ORDER BY First ASC<br />
28–24 InduSoft Web Studio
DML Query Statements<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
This will return the following set of records<br />
Joanne Thomas 50768 48 Ann Arbor Michigan<br />
John Smith 64230 45 Ann Arbor Michigan<br />
Randall Carson 60748 40 Ann Arbor Michigan<br />
Walter Williams 65891 35 Ann Arbor Michigan<br />
This example is a slight modification of the previous example, showing only the columns of interest:<br />
SELECT First, Last, City, State<br />
FROM EmployeeInfo<br />
WHERE (City=”Ann Arbor”) AND (Age > 25)<br />
ORDER BY First ASC<br />
This will return the following set of records<br />
Joanne Thomas Ann Arbor Michigan<br />
John Smith Ann Arbor Michigan<br />
Randall Carson Ann Arbor Michigan<br />
Walter Williams Ann Arbor Michigan<br />
Notes:<br />
• You can use parentheses around the conditional expressions to make them easier to read, but they are<br />
not required.<br />
This example returns a sorted list, first by state in ascending order, then by city in ascending order.<br />
SELECT *<br />
FROM EmployeeInfo<br />
ORDER BY State ASC, City ASC<br />
This will return the following set of records<br />
John Smith 64230 45 Ann Arbor Michigan<br />
Randall Carson 60748 40 Ann Arbor Michigan<br />
Joanne Thomas 50768 48 Ann Arbor Michigan<br />
Walter Williams 65891 35 Ann Arbor Michigan<br />
Ginger Rogers 69710 22 Ann Arbor Michigan<br />
Elroy Clinger 69394 26 Chelsea Michigan<br />
Suzanne Collins 62175 35 Dexter Michigan<br />
Bill Gross 52786 55 Jackson Michigan<br />
Maryanne Lewis 68200 24 Plymouth Michigan<br />
Karl Walters 68985 30 Sylvania Ohio<br />
Erica Edwards 59732 48 Toledo Ohio<br />
This example returns a set of records where the first name starts with a “J”<br />
SELECT First, Last<br />
FROM EmployeeInfo<br />
WHERE First LIKE =’J%’<br />
This will return the following set of records<br />
John<br />
Joanne<br />
Smith<br />
Thomas<br />
InduSoft Web Studio 28–25
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
DML Query Statements<br />
Notes:<br />
• Depending on your database server, various wildcard characters may be available for use with the LIKE<br />
clause:<br />
Wildcard Description<br />
_ (underscore) Matches any single character<br />
% Matches a string of one or more characters<br />
[ ] Matches any single character withing the specified range (e.g. [a-f] )<br />
[ ^ ] Matches any single character not in the specified range (e.g. [^a-f])<br />
28–26 InduSoft Web Studio
DML Query Statements<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
B. WHERE clause with BETWEEN conditional operator<br />
The WHERE clause can use the conditional operator BETWEEN or NOT BETWEEN to test if a column<br />
value is between a range of values. The syntax of the SELECT statement when using the WHERE<br />
clause with the BETWEEN conditional operator is:<br />
SELECT column1<br />
[, column2, ….]<br />
FROM tableName<br />
WHERE column3 BETWEEN value1 AND value2<br />
For example,<br />
SELECT First, Last, City, State<br />
FROM EmployeeInfo<br />
WHERE Age BETWEEN 30 AND 50<br />
ORDER BY State ASC, City ASC<br />
This will return the following set of records<br />
John Smith 64230 45 Ann Arbor Michigan<br />
Randall Carson 60748 40 Ann Arbor Michigan<br />
Joanne Thomas 50768 48 Ann Arbor Michigan<br />
Walter Williams 65891 35 Ann Arbor Michigan<br />
Suzanne Collins 62175 35 Dexter Michigan<br />
Bill Gross 52786 55 Jackson Michigan<br />
Karl Walters 68985 30 Sylvania Ohio<br />
Erica Edwards 59732 48 Toledo Ohio<br />
InduSoft Web Studio 28–27
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
DML Query Statements<br />
B. WHERE clause with IN<br />
The WHERE clause can use the conditional operator IN or NOT IN to test if a column value is in a<br />
membership. The syntax of the SELECT statement when using the WHERE clause with the IN<br />
conditional operator is:<br />
SELECT column1<br />
[, column2, ….]<br />
FROM tableName<br />
WHERE column3 IN (lisfOfValues)<br />
For example,<br />
SELECT *<br />
FROM EmployeeInfo<br />
WHERE City IN (‘Ann Arbor’, ‘Dexter’)<br />
This will return the following set of records<br />
John Smith 64230 45 Ann Arbor Michigan<br />
Suzanne Collins 62175 35 Dexter Michigan<br />
Randall Carson 60748 40 Ann Arbor Michigan<br />
Joanne Thomas 50768 48 Ann Arbor Michigan<br />
Walter Williams 65891 35 Ann Arbor Michigan<br />
Ginger Rogers 69710 22 Ann Arbor Michigan<br />
28–28 InduSoft Web Studio
DML Query Statements<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
C. AS clause<br />
The AS clause can be used as an alias for either a column or a table. The syntax for using the AS<br />
clause is:<br />
SELECT column {example using a column alias}<br />
AS columnAlias<br />
FROM tableName<br />
SELECT column<br />
FROM tableName<br />
AS tableAlias<br />
{example using a table alias}<br />
InduSoft Web Studio 28–29
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
DML Query Statements<br />
D. CASE clause<br />
The CASE clause is part of T-SQL and other database’s SQL language. The CASE clause can be used<br />
with the SELECT statement. The syntax of the SELECT statement when using the CASE clause is:<br />
SELECT column1, ….<br />
CASE expression<br />
WHEN value1 THEN result1<br />
WHEN value2 THEN result2<br />
ELSE elseResult<br />
END<br />
FROM tableName<br />
Alternatively, you can use the following syntax:<br />
SELECT column1, ….<br />
CASE<br />
WHEN booleanExpression1 THEN result1<br />
WHEN booleanExpression2 THEN result2<br />
ELSE elseResult<br />
END<br />
FROM tableName<br />
For example, suppose we want to determine the tax code to be used based on the state the employee<br />
lives in. E.g. if the employee lives in Michigan, their tax code is M-1099, while in Ohio is O-1099.<br />
The SQL code would be:<br />
SELECT *<br />
(CASE<br />
WHEN State = ‘Michigan’ THEN ‘M-1099’<br />
WHEN State = ‘Ohio’ THEN ‘O-1099’<br />
END) AS TaxCode<br />
FROM EmployeeInfo<br />
The result would be as shown below. Note that the output column is named TaxCode and is part of<br />
the resulting recordset, but is not part of the database table at this point.<br />
First Last ID Age City State TaxCode<br />
John Smith 64230 45 Ann Arbor Michigan M-1099<br />
Suzanne Collins 62175 35 Dexter Michigan M-1099<br />
Randall Carson 60748 40 Ann Arbor Michigan M-1099<br />
Bill Gross 52786 55 Jackson Michigan M-1099<br />
Joanne Thomas 50768 48 Ann Arbor Michigan M-1099<br />
Maryanne Lewis 68200 24 Plymouth Michigan M-1099<br />
Walter Williams 65891 35 Ann Arbor Michigan M-1099<br />
Karl Walters 68985 30 Sylvania Ohio O-1099<br />
Erica Edwards 59732 48 Toledo Ohio O-1099<br />
Elroy Clinger 69394 26 Chelsea Michigan M-1099<br />
Ginger Rogers 69710 22 Ann Arbor Michigan M-1099<br />
Alternatively, the SQL code could be written as follows::<br />
SELECT *<br />
TaxCode = CASE<br />
WHEN State = ‘Michigan’ THEN ‘M-1099’<br />
WHEN State = ‘Ohio’ THEN ‘O-1099’<br />
END<br />
FROM EmployeeInfo<br />
28–30 InduSoft Web Studio
DML Query Statements<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
E. GROUP BY clause<br />
The GROUP BY clause is used to gather all rows that contain data in the specified column(s) and will<br />
allow SQL aggregate functions to be performed on the specified columns. The syntax of the SELECT<br />
statement when using the GROUP BY clause is:<br />
SELECT column1, Function (column2), Function (column3)<br />
FROM tableName<br />
GROUP BY column1<br />
[HAVING Function (column2) condition value]<br />
[ORDER BY columnList [ASC | DESC]]<br />
The following example will determine the oldest employee in each city<br />
SELECT MAX(Age), City<br />
FROM employeeInfo<br />
GROUP BY City<br />
ORDER BY City<br />
The result is<br />
48 Ann Arbor<br />
26 Chelsea<br />
35 Dexter<br />
55 Jackson<br />
24 Plymouth<br />
30 Sylvania<br />
48 Toledo<br />
The following example will select by City the total number of employees per city and the maximum age<br />
SELECT City, COUNT(City), MAX(Age)<br />
FROM employeeinfo<br />
GROUP BY City<br />
ORDER BY City<br />
The result is<br />
Ann Arbor 5 48<br />
Chelsea 1 26<br />
Dexter 1 35<br />
Jackson 1 55<br />
Plymouth 1 24<br />
Sylvania 1 30<br />
Toledo 1 48<br />
The following example uses the optional HAVING Function clause<br />
SELECT City, COUNT(City), MAX(Age)<br />
FROM employeeinfo<br />
GROUP BY City<br />
HAVING MAX(Age) > 40<br />
ORDER BY City<br />
The result is<br />
Ann Arbor 5 48<br />
Jackson 1 55<br />
InduSoft Web Studio 28–31
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
DML Query Statements<br />
F. INTO clause<br />
The INTO clause is used to create backup copies of table. The syntax of the SELECT statement when<br />
using the INTO clause is:<br />
SELECT column1<br />
[, column2, ….]<br />
INTO newTableName<br />
FROM tableName<br />
Notes:<br />
• You can use the asterick character (*) as a wildcard to select all columns.<br />
28–32 InduSoft Web Studio
DML Query Statements<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
G. Using the SELECT statement with SQL Functions<br />
The SELECT statement can also be used with the SQL Aggregate Functions. Some examples are:<br />
SELECT AVG(Age)<br />
FROM EmployeeInfo<br />
{returns single value average age of employees from table}<br />
SELECT AVG(Age) {returns average age of employees who live in Ann Arbor}<br />
FROM EmployeeInfo<br />
WHERE City = ‘Ann Arbor’<br />
SELECT COUNT(*)<br />
FROM EmployeeInfo<br />
SELECT COUNT(City)<br />
FROM EmployeeInfo<br />
{returns number of employee records}<br />
{returns number of employee records that have a City value}<br />
SELECT DATE(CURRENT_TIMESTAMP) {returns the date}<br />
SELECT TIME(CURRENT_TIMESTAMP) {returns the time}<br />
SELECT DAYOFWEEK(CURRENT_TIMESTAMP) {returns a numeric value 1-7}<br />
SELECT DAYOFMONTH(CURRENT_TIMESTAMP) {returns a numeric value 1-31}<br />
SELECT DAYOFYEAR(CURRENT_TIMESTAMP) {returns a numeric value 1-365}<br />
SELECT MONTHNAME(CURRENT_TIMESTAMP) {returns month name Jan-Dec}<br />
SELECT DAYNAME(CURRENT_TIMESTAMP)<br />
{returns name of day Sunday-Saturday}<br />
SELECT DAYNAME(CURRENT_TIMESTAMP) {returns number of week 1-53}<br />
SELECT MONTHNAME(‘2007-08-05’)<br />
{returns August}<br />
InduSoft Web Studio 28–33
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
DML Query Statements<br />
H. JOIN Clause<br />
Table joins make relational databases work, linking together two or more tables in a SELECT statement to<br />
obtain a single query result set. In the SELECT statement, you must specify the tables to be used and the<br />
primary key to be used to link the tables together. The syntax of the JOIN clause is:<br />
SELECT column1 [, column2, ….]<br />
FROM table1<br />
INNER JOIN table2<br />
ON table1.keyField OPERATOR table2.keyField<br />
The syntax shown above is compliant with ANSI SQL-92. However, most databases support the alternative<br />
format:<br />
SELECT column1 [, column2, ….]<br />
FROM table1, table2, ….<br />
WHERE columnName OPERATOR value<br />
The benefits of database normalization were discussed in the Database chapter. These benefits include the<br />
reduction of repeating data. The linkage of the normalized tables in accomplished through the Join.<br />
Consider the headers in our sample tables Orders and Customers. The CustomerID primary key is what is<br />
used to link these tables together.<br />
Table: Orders<br />
CustomerID OrderDate Item Qty Price<br />
Table: Customers<br />
CustomerID First Last City State<br />
For example, if you wanted to obtain the records that indicate the customer’s name and what items they<br />
purchased, you could use the following SQL statement:<br />
SELECT Customers.First, Customers.Last, Orders.Item<br />
FROM Customers<br />
INNER JOIN Orders<br />
ON Customers.CustomerID = Orders.CustomerID<br />
The result will be:<br />
First Last Item<br />
Barry Piper Lid<br />
Jim Weber Mug<br />
Janis Cunningham Bottle<br />
Elroy Klinger Jar<br />
Donald Graham Stein<br />
This type of a join is called an “Inner Join” and is the most common type of a Join. The result of executing<br />
this code will be a set of records that show the customer first name, last name and the item(s) ordered by<br />
the customer.<br />
The alternative form of the Inner Join clause for this example is:<br />
SELECT Customers.First, Customers.Last, Orders.Item<br />
FROM Customers, Orders<br />
WHERE Customers.CustomerID = Orders.CustomerID<br />
28–34 InduSoft Web Studio
DML Query Statements<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
If you wanted to find out the names of the customers who ordered a particular product, for instance a Stein,<br />
you could accomplish this through the following SQL code:<br />
SELECT Customers.First, Customers.Last, Orders.Item<br />
FROM Customers, Orders<br />
WHERE Customers.CustomerID = Orders.CustomerID<br />
AND orders.item = ‘Stein’<br />
In addition to the INNER JOIN, the other types of Joins available are a LEFT JOIN and a RIGHT JOIN.<br />
The LEFT JOIN returns alls rows to the left of the conditional (i.e. the first table) even if there is no right<br />
column (i.e. the second table) to match. An example of a LEFT JOIN is:<br />
SELECT Customers.First, Customers.Last, Orders.Item<br />
FROM Customers<br />
LEFT JOIN Orders<br />
ON Customers.CustomerID = Orders.CustomerID<br />
The result is:<br />
First Last Item<br />
Barry Piper Lid<br />
Jim Weber Mug<br />
Janis Cunningham Bottle<br />
Elroy Klinger Jar<br />
Claudio Sanchez NULL<br />
Donald Graham Stein<br />
Roberto Mendoza NULL<br />
Julia Mitchell NULL<br />
George Walker NULL<br />
Eddie Schultz NULL<br />
Ginger Dalton NULL<br />
The RIGHTJOIN returns alls rows to the right of the conditional (i.e. the second table) even if there is no left<br />
column match (i.e. from the first table).<br />
SELECT Customers.First, Customers.Last, Orders.Item<br />
FROM Customers<br />
RIGHT JOIN Orders<br />
ON Customers.CustomerID = Orders.CustomerID<br />
The result is<br />
First Last Item<br />
Jim Weber Mug<br />
Donald Graham Stein<br />
Janis Cunningham Bottle<br />
Elroy Klinger Jar<br />
Barry Piper Lid<br />
Notes:<br />
• The column name should contain the table name followed by a period followed by the column name.<br />
While this syntax (of including the table name followed by a period) is not necessarily required, it is a<br />
good idea to use this syntax so that column names do not get confused.<br />
• Types of Joins are Inner Join, Outer Join, Left Join and Right Join<br />
• The Join Query does not alter either data table, it simply combines the data from each table into one<br />
result recordset that can be viewed or manipulated.<br />
InduSoft Web Studio 28–35
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
DML Query Statements<br />
I. Union Clause<br />
The UNION clause places to separate queries together to form one result recordset. The two tables must<br />
have columns (those with the same column name) that have the same data type. The form of the UNION<br />
clause is:<br />
SQL Statement 1<br />
UNION<br />
SQL Statement 2<br />
For example, suppose we have our table of Employees broken into two separate tables, one for each plant:<br />
Table: Plant1EmployeeInfo<br />
First Last ID Age City State<br />
John Smith 64230 45 Ann Arbor Michigan<br />
Suzanne Collins 62175 35 Dexter Michigan<br />
Randall Carson 60748 40 Ann Arbor Michigan<br />
Bill Gross 52786 55 Jackson Michigan<br />
Joanne Thomas 50768 48 Ann Arbor Michigan<br />
Table: Plant2EmployeeInfo<br />
First Last ID Age City State<br />
Maryanne Lewis 68200 24 Plymouth Michigan<br />
Walter Williams 65891 35 Ann Arbor Michigan<br />
Karl Walters 68985 30 Sylvania Ohio<br />
Erica Edwards 59732 48 Toledo Ohio<br />
Elroy Clinger 69394 26 Chelsea Michigan<br />
Ginger Rogers 69710 22 Ann Arbor Michigan<br />
By using the UNION clause, we can get a list employees from both plants returned in one result set<br />
(Recordset). With the UNION clause, these will automatically be distinct values.<br />
SELECT First, Last FROM Plant1EmployeeInfo<br />
UNION<br />
SELECT First, Last FROM Plant2EmployeeInfo<br />
The result set will be:<br />
John<br />
Suzanne<br />
Randall<br />
Bill<br />
Joanne<br />
Maryanne<br />
Walter<br />
Karl<br />
Erica<br />
Elroy<br />
Ginger<br />
Smith<br />
Collins<br />
Carson<br />
Gross<br />
Thomas<br />
Lewis<br />
Williams<br />
Walters<br />
Edwards<br />
Clinger<br />
Rogers<br />
You can also use the UNION ALL clause but by doing so, you will select all values, even if they are not<br />
distinct.<br />
28–36 InduSoft Web Studio
DML Query Statements<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
INSERT Statement<br />
The INSERT statement is used to insert (add) a row of data into the table. The basic form of the INSERT<br />
statement is<br />
INSERT INTO tableName<br />
(firstColumn, ….., lastColumn)<br />
VALUES (firstValue, ….., lastValue)<br />
For example, if we wanted to insert a new record into the<br />
INSERT INTO EmployeeInfo<br />
(First, Last, ID, Age, City, State)<br />
VALUES (‘Kim’, ‘Fitzgerald’, 69459, 35, ‘Ann Arbor’, ‘Michigan’)<br />
The result would be:<br />
John Smith 64230 45 Ann Arbor Michigan<br />
Suzanne Collins 62175 35 Dexter Michigan<br />
Randall Carson 60748 40 Ann Arbor Michigan<br />
Bill Gross 52786 55 Jackson Michigan<br />
Joanne Thomas 50768 48 Ann Arbor Michigan<br />
Maryanne Lewis 68200 24 Plymouth Michigan<br />
Walter Williams 65891 35 Ann Arbor Michigan<br />
Karl Walters 68985 30 Sylvania Ohio<br />
Erica Edwards 59732 48 Toledo Ohio<br />
Elroy Clinger 69394 26 Chelsea Michigan<br />
Ginger Rogers 69710 22 Ann Arbor Michigan<br />
Kim Fitzgerald 69459 35 Ann Arbor Michigan<br />
Notes:<br />
• All strings should be enclosed between single quotes: ‘string’<br />
InduSoft Web Studio 28–37
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
DML Query Statements<br />
UPDATE Statement<br />
The UPDATE statement is used to update (change) a record or set of records to match the specified criteria.<br />
The basic form of the UPDATE statement is<br />
UPDATE tableName<br />
SET columnName = newValue<br />
[,columnName2 = newValue2, …..]<br />
WHERE columnName OPERATOR value<br />
[and|or columnName Operator value]<br />
[ ] = optional<br />
For example, if we wanted to update a record in the EmployeeInfo table<br />
UPDATE EmployeeInfo<br />
SET Age = Age+1<br />
WHERE First=’John’ AND Last=’Smith’<br />
John Smith 64230 46 Ann Arbor Michigan<br />
Suzanne Collins 62175 35 Dexter Michigan<br />
Randall Carson 60748 40 Ann Arbor Michigan<br />
Bill Gross 52786 55 Jackson Michigan<br />
Joanne Thomas 50768 48 Ann Arbor Michigan<br />
Maryanne Lewis 68200 24 Plymouth Michigan<br />
Walter Williams 65891 35 Ann Arbor Michigan<br />
Karl Walters 68985 30 Sylvania Ohio<br />
Erica Edwards 59732 48 Toledo Ohio<br />
Elroy Clinger 69394 26 Chelsea Michigan<br />
Ginger Rogers 69710 22 Ann Arbor Michigan<br />
This example shows updating multiple columns in a record.<br />
UPDATE EmployeeInfo<br />
SET City=’Maumee’, State=’Ohio’<br />
WHERE First=’John’ AND Last=’Smith’<br />
John Smith 64230 45 Maumee Ohio<br />
Suzanne Collins 62175 35 Dexter Michigan<br />
Randall Carson 60748 40 Ann Arbor Michigan<br />
Bill Gross 52786 55 Jackson Michigan<br />
Joanne Thomas 50768 48 Ann Arbor Michigan<br />
Maryanne Lewis 68200 24 Plymouth Michigan<br />
Walter Williams 65891 35 Ann Arbor Michigan<br />
Karl Walters 68985 30 Sylvania Ohio<br />
Erica Edwards 59732 48 Toledo Ohio<br />
Elroy Clinger 69394 26 Chelsea Michigan<br />
Ginger Rogers 69710 22 Ann Arbor Michigan<br />
Notes:<br />
• To update a DateTime field, you can use the following syntax:<br />
Update tableName<br />
Set Date = ‘2007-08-02 12:30:00’<br />
Where Name=’Joe Frederick’<br />
28–38 InduSoft Web Studio
DML Query Statements<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
The CASE clause can also be used with the UPDATE statement. In a previous example using the SELECT<br />
statement with the CASE clause, we looked at the employee state and created a result column indicating the<br />
tax code form to be used. Note that this result field was in the returned recordset, it was not updated in the<br />
database.<br />
If we wanted to perform a similar operation but update the database with the result, we could create a column<br />
named TaxForm that would initially be set to NULL (i.e. no valid value assigned).<br />
First Last ID Age City State TaxForm<br />
John Smith 64230 45 Ann Arbor Michigan NULL<br />
Suzanne Collins 62175 35 Dexter Michigan NULL<br />
Randall Carson 60748 40 Ann Arbor Michigan NULL<br />
Bill Gross 52786 55 Jackson Michigan NULL<br />
Joanne Thomas 50768 48 Ann Arbor Michigan NULL<br />
Maryanne Lewis 68200 24 Plymouth Michigan NULL<br />
Walter Williams 65891 35 Ann Arbor Michigan NULL<br />
Karl Walters 68985 30 Sylvania Ohio NULL<br />
Erica Edwards 59732 48 Toledo Ohio NULL<br />
Elroy Clinger 69394 26 Chelsea Michigan NULL<br />
Ginger Rogers 69710 22 Ann Arbor Michigan NULL<br />
Then, we would execute the following SQL code:<br />
UPDATE EmployeeInfo<br />
SET TaxForm =<br />
Case<br />
WHEN State = ‘Michigan’ THEN ‘M-1099’<br />
WHEN State = ‘Ohio’ THEN ‘O-1099’<br />
END<br />
The result would be that the database would be updated to the following values in the EmployeeInfo table:<br />
First Last ID Age City State TaxForm<br />
John Smith 64230 45 Ann Arbor Michigan M-1099<br />
Suzanne Collins 62175 35 Dexter Michigan M-1099<br />
Randall Carson 60748 40 Ann Arbor Michigan M-1099<br />
Bill Gross 52786 55 Jackson Michigan M-1099<br />
Joanne Thomas 50768 48 Ann Arbor Michigan M-1099<br />
Maryanne Lewis 68200 24 Plymouth Michigan M-1099<br />
Walter Williams 65891 35 Ann Arbor Michigan M-1099<br />
Karl Walters 68985 30 Sylvania Ohio O-1099<br />
Erica Edwards 59732 48 Toledo Ohio O-1099<br />
Elroy Clinger 69394 26 Chelsea Michigan M-1099<br />
Ginger Rogers 69710 22 Ann Arbor Michigan M-1099<br />
Here is another example of the Update Statement:<br />
UPDATE EmployeeInfo SET Age = 55, date = "2007-08-02 16:21:00" WHERE First = ‘Joan’ AND<br />
Last=’Smith’<br />
InduSoft Web Studio 28–39
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
DML Query Statements<br />
DELETE Statement<br />
The DELETE statement is used to delete a record or set of records from the table where certain criteria are<br />
met. The basic form of the DELETE statement is<br />
DELETE FROM tableName<br />
[WHERE columnName OPERATOR value<br />
[and|or columnName Operator value]]<br />
[ ] = optional<br />
Note that the DELETE FROM tableName form of this statement without any criteria will delete the entire table.<br />
For example, if we wanted to delete an employee from the EmployeeInfo table<br />
DELETE FROM EmployeeInfo<br />
WHERE First=’John’ AND Last=’Smith’<br />
Suzanne Collins 62175 35 Dexter Michigan<br />
Randall Carson 60748 40 Ann Arbor Michigan<br />
Bill Gross 52786 55 Jackson Michigan<br />
Joanne Thomas 50768 48 Ann Arbor Michigan<br />
Maryanne Lewis 68200 24 Plymouth Michigan<br />
Walter Williams 65891 35 Ann Arbor Michigan<br />
Karl Walters 68985 30 Sylvania Ohio<br />
Erica Edwards 59732 48 Toledo Ohio<br />
Elroy Clinger 69394 26 Chelsea Michigan<br />
Ginger Rogers 69710 22 Ann Arbor Michigan<br />
Notes:<br />
• When the DELETE FROM statement is used without any criteria, it will delete the entire table<br />
E.g. DELETE FROM tableName<br />
28–40 InduSoft Web Studio
JET SQL<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
JET SQL<br />
Microsoft created a version of SQL designed to support Microsoft Access and Excel. It is implemented as part<br />
of an OLE-DB Provider. JET is different that other versions of SQL. It cannot create a database and it cannot<br />
manage database security. When using JET SQL with ADO, you can use ADOX (ADO Extensions) to create an<br />
Excel file (and spreadsheet), or an Access database.<br />
Use with Microsoft Excel<br />
When using JET SQL with an Excel spreadsheet, you need be sure to enclose the Worksheet name in square<br />
brackets, followed by a $. Some examples are:<br />
SELECT * FROM [Sheet1$]<br />
SELECT * FROM [MyNamedRange]<br />
SELECT * FROM [Sheet1$A1:B10]<br />
INSERT INTO [Sheet1$] (F1, F2) VALUES (‘111’, ‘ABC’)<br />
CREATE TABLE Sheet1 (F1 char(255), F2 char(255))<br />
Creating a Primary Key<br />
Excel does not support a Primary Key. To create a Primary Key in Access, you can use the following example:<br />
CREATE TABLE Orders<br />
(OrderID INTEGER CONSTRAINT PK_OrderID PRIMARY KEY,<br />
CustomerID INTEGER NOT NULL CONSTRAINT FK_CustomerID<br />
REFERENCES Customers (CustomerID),<br />
Item VarChar(20),<br />
OrderDate DATETIME,<br />
Amount CURRENCY)<br />
More on Microsoft Jet<br />
http://en.wikipedia.org/wiki/Microsoft_Jet (see section on locking)<br />
http://support.microsoft.com/default.aspx/kb/275561/en<br />
http://support.microsoft.com/default.aspx/kb/288631 Compaction<br />
InduSoft Web Studio 28–41
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Transact-SQL<br />
Transact-SQL<br />
Microsoft provides a proprietary extension to the SQL language called Transact-SQL, abbreviated as T-SQL. T-<br />
SQL is implemented in Microsoft’s SQL Server. A complete overview of T-SQL is beyond the scope of these<br />
materials. Additional information on T-SQL can be found on the Microsoft MSDN website.<br />
T-SQL Functions (subset)<br />
Function<br />
Create Database<br />
Create Table<br />
Create User<br />
Create Index<br />
Drop Database<br />
Drop Table<br />
If <br />
Then <br />
If <br />
Then <br />
Else
Examples using a SQL Query with <strong>IWS</strong> Tags<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Examples using a SQL Query with <strong>IWS</strong> Tags<br />
Command Object with Execute using <strong>IWS</strong> Tags & VBScript variables with SQL<br />
Dim oConn, oCmd, strSql<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
Set oCmd = CreateObject(“ADODB.Command”)<br />
oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & $GetAppPath()& "myDB.mdb"<br />
StrSql = $ID_Insert & ", '" & $Name_Insert & "', '"& $Address_Insert & "'"<br />
cmd.CommandText = "INSERT into Table1 (ID, Name, Address) values (‘"&StrSql&"’)"<br />
Set oRs=cmd.Execute<br />
The VBScript variable needs to be enclosed in the following order:<br />
- a single quote<br />
- a double quote<br />
- an ampersand<br />
- the VBScript variable<br />
- an ampersand<br />
- a double quotation<br />
- a single quotation<br />
In addition, parentheses or additional double quotes may be required, depending on how the SQL string is built.<br />
The following is another sample application:<br />
‘ The following just instantiates the objects and opens them<br />
Set con = CreateObject("ADODB.Connection")<br />
Set cmd = CreateObject("ADODB.Command")<br />
strPathToMDB = "C:\Demo.MDB"<br />
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & strPathToMDB & ";"<br />
con.Open strConn<br />
cmd.ActiveConnection = con<br />
‘ The following code inserts a new record into the table with data from the variable MyStr<br />
MyStr = “Hello”<br />
strSQL = "Insert Into Table(Column) Values('"&MyStr&"')"<br />
cmd.CommandText = strSQL<br />
cmd.execute<br />
Note:<br />
• The SQL Query syntax is dependant on your database server.<br />
• When accessing an Excel file, in the SQL command you refer to a specific worksheet by the following<br />
syntax: [worksheetname$]<br />
• When accessing an Excel spreadsheet with no Headers, be sure to do the following<br />
- Make sure the Connection string has HDR=No in the Extended Properties field.<br />
- In your SQL command (and Recordset Object), your refer to each column as “Fx”, where x is the<br />
column number (e.g. “F1” for the first column, “F2” for the second, etc.)<br />
InduSoft Web Studio 28–43
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Examples using a SQL Query with <strong>IWS</strong> Tags<br />
Review Questions<br />
1. What does SQL stand for<br />
2. Which relational database support SQL<br />
3. Which SQL statement is used to extract from a database<br />
a. EXTRACT<br />
b. SELECT<br />
c. OPEN<br />
d. GET<br />
4. Which SQL statement is used to save changes to the database<br />
a. UPDATE<br />
b. SAVE AS<br />
c. SAVE<br />
d. MODIFY<br />
5. Which SQL statement is used to delete data from a database<br />
a. DELETE<br />
b. REMOVE<br />
c. COLLAPSE<br />
6. Which SQL statement inserts data into a database<br />
a. ADD NEW<br />
b. ADD RECORD<br />
c. INSERT INTO<br />
d. INSERT NEW<br />
7. How do you select the column “FirstName” from a table named “Employees”<br />
a. SELECT FirstName FROM Employees<br />
b. SELECT Employees.FirstName<br />
c. EXTRACT FirstName FROM Employees<br />
8. How do you select all columns from a table named “Employees”<br />
a. SELECT *.Employees<br />
b. SELECT Employees<br />
c. SELECT [all] FROM Employees<br />
d. SELECT * FROM Employees<br />
9. How do you select all records from a table “Employees” where the First name is “George” and the City is<br />
“Ann Arbor”<br />
a. SELECT FirstName=’George’, City=’Ann Abor’ From Employees<br />
b. SELECT * FROM Employees WHERE FirstName LIKE ‘George’ AND City LIKE ‘Ann Arbor’<br />
c. SELECT * FROM Employees WHERE FirstName=’George’ AND City=’Ann Arbor’<br />
28–44 InduSoft Web Studio
Examples using a SQL Query with <strong>IWS</strong> Tags<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
10. How do you sort the returned records from the “Employees” Table sorted by the last name in ascending<br />
order<br />
a. SELECT * FROM Employees SORT LastName ASC<br />
b. SELECT * FROM Employees ORDER LastName ASC<br />
c. SELECT * FROM Employees SORT BY LastName ASC<br />
d. SELECT * FROM Employees ORDER BY LastName ASC<br />
11. How do you change an employee’s last name from “Smith” to “Jones” where the first name is “Kim” and<br />
EmployeeID = 987 in the Table Employees<br />
a. UPDATE EMPLOYEES SET LastName=’Jones’ WHERE LastName=’Smith’<br />
b. UPDATE EMPLOYEES SET LastName=’Smith’ INTO LastName=’Jones’<br />
c. MODIFY EMPLOYEES SET LastName=’Jones’ WHERE LastName=’Smith’<br />
d. MODIFY EMPLOYEES SET LastName=’Jones’ INTO LastName=’Jones’<br />
12. How do you return the total number of records in the “Employees” table<br />
a. SELECT COLUMNS() FROM Employees<br />
b. SELECT COUNT (*) FROM Employees<br />
c. SELECT COUNT() FROM Employees<br />
d. SELECT COLUMNS(*) FROM Employees<br />
InduSoft Web Studio 28–45
Chapter 29.<br />
Accessing Databases with VBScript<br />
InduSoft Web Studio (<strong>IWS</strong>) supports ADO.NET (ActiveX for Data Objects for the .NET Framework) used for<br />
accessing data sources such as relational databases. ADO.NET allows for the access of data in a consistent,<br />
uniform manner regardless of the source of the data. This means that you can develop an application that can<br />
easily migrate from one database to another, or be developed prior to the selection of the database. The only<br />
database specific requirement is the definition of a connection string, identical to the connection string that is<br />
built by the <strong>IWS</strong> Database configuration wizard.<br />
To implement ADO.NET, one or more ADO.NET Managed Providers are required. These Providers are either<br />
included as part of the operating system installation (Microsoft includes several ADO.NET Providers), included<br />
with the Database, or come from a 3 rd party vendor.<br />
The ADO.NET Managed Data Provider provides the interface between the database engine and an <strong>IWS</strong><br />
application. The <strong>IWS</strong> Application issues ADO.NET commands or SQL queries, and the Provider responds to<br />
those commands or SQL queries. Results of a SQL query are generally returned in Recordsets, which are a<br />
collection of records (i.e. rows of data that meet the SQL query criteria). Recordsets are disjoint data; i.e. the<br />
Recordset is resident in local memory where the <strong>IWS</strong> application is run. When an <strong>IWS</strong> application manipulates<br />
a Recordset, it is manipulating the records contained in local memory, not in the Database. To return Records<br />
back to the Database, a SQL Update command must be issued to store the Records (i.e. the Recordset) back<br />
into the Table in the Database.<br />
.NET Data Provider<br />
Connection<br />
DataAdapter<br />
Transaction<br />
SelectCommand<br />
DataSet<br />
DataTableCollection<br />
DataTable<br />
Command<br />
Parameters<br />
DataReader<br />
InsertCommand<br />
UpdateCommand<br />
DeleteCommand<br />
DataRowCollection<br />
DataColumnCollection<br />
ConstraintCollection<br />
DataRelationCollection<br />
Database<br />
Data Provider Functions<br />
• Connects to Database<br />
• Executes commands on database<br />
• Retrieves/updates results<br />
<strong>IWS</strong> Application<br />
Data Provider Functions<br />
• Client-side memory resident<br />
representation of database result set<br />
• Consistent interface model<br />
Most ADO.NET providers support ADO, a subset of ADO.NET that uses Microsoft COM technology. VBScript<br />
supports ADO, but since VBScript is not a .NET language, VBScript cannot support ADO.NET.<br />
Notes:<br />
• Applications using ADO require an ADO or ADO.NET Provider. Microsoft includes several with the<br />
.NET framework. Other 3 rd party ADO Providers are available.<br />
• ADO.NET is automatically installed with IIS (e.g. with Windows XP Pro)<br />
• Recordsets are disjoint data. The Recordset is usually the result of a SQL query, and is stored in local<br />
memory. You need to issue a SQL Update Command to write the Recordset to the Database Table.<br />
InduSoft Web Studio 29–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
ADO Overview<br />
ADO Overview<br />
ADO (ActiveX for Data Objects) is a Microsoft technology based on COM (Component Object Model) objects<br />
that is used as an API (Applications Programming Interface) between an application (e.g. <strong>IWS</strong> running<br />
VBScript) and the database. ADO connects to an ADO ODBC or ADO OLE-DB Provider to access data from<br />
the database, and because ADO has a common API, it removes the dependencies on the particular database<br />
used. This makes it much easier for the developer to support multiple databases as well as switch between<br />
databases. ADO is a successor technology to DAO (Data Access Objects).<br />
The ADO model includes a number of high-level objects, and are described below. Although ADO defines an<br />
object hierarchy, most ADO Objects (except for Error, Field and Property) can be created (instantiated) on their<br />
own. This gives you flexibility when defining the programmable objects, and allows you to accomplish the same<br />
task through different means. For example, a SQL Execute Method can be used with either the Connection or<br />
Command objects.<br />
A chart explaining the function of each of these Objects is below. The high-level steps involved in reading from,<br />
querying and writing to a database are:<br />
1. Create a Connection to the data source (database)<br />
2. Open the database connection<br />
3. Create an ADO Recordset<br />
4. Extract data from the database using an SQL string, placing the matching records into a Recordset<br />
5. Manipulate the Recordset<br />
6. Update the database (if required)<br />
7. Close the Recordset Object<br />
8. Close the Connection Object<br />
These steps are general in nature, and additional steps may be added or removed, based on your specific<br />
database access requirements.<br />
29–2 InduSoft Web Studio
ADO Overview<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
ADO Object ProgID Description<br />
Connection ADODB.Connection Used to establish connections between <strong>IWS</strong> and the database server<br />
Command ADODB.Command Used to execute commands (e.g. SQL) on the database.<br />
Recordset ADODB.Recordset Used to store, view and manipulate results of a query. Also used to<br />
store and manipulate created records.<br />
Record ADODB.Record A Record is the equivalent of a row of data<br />
Stream ADODB.Stream Manipulates a stream of binary or text data. E.g. text files<br />
Errors<br />
A collection of Error Objects<br />
Error ADOB.Error An Error Object containing the details of a Data Provider error<br />
Parameters<br />
A collection of Parameter Objects<br />
Parameter<br />
A Parameter Object for the specified Object (e.g. a SQL Command,<br />
Connection String)<br />
Properties<br />
A collection of Property Objects<br />
Property<br />
A Data Provider-specific configuration value or returned value<br />
Fields<br />
A collection of Field Objects<br />
Field<br />
Allows you to access each Field (column) in a Recordset Object<br />
ADO can be used with ODBC (using a DSN, or Data Source Name) with the Microsoft ADO.NET Provider for<br />
ODBC Drivers, or with a DSN-less connection using the ADO.NET Provider for OLE-DB. ADO (ADODB) is<br />
supported on Windows 2000/XP/Server 2003 platforms while a slightly less powerful versions called ADOCE is<br />
used for Windows CE platforms.<br />
Microsoft also developed ADOX (or ADO Extensions for Database Definition Language (Schema) and<br />
Security). ADOXCE is ADOX for Windows CE-based platforms. ADOX is primarily used to create new tables in<br />
a database.<br />
Notes:<br />
• Not all ADO.NET Providers support ADO. You may need to use ADO OLE-DB or ADO ODBC<br />
Providers.<br />
• The ADODB Class Library is used for Windows XP/2000/Server 2003-based systems<br />
• The ADOCE Class Library is used for Windows CE-based systems<br />
• ADO simplifies the interface to databases<br />
InduSoft Web Studio 29–3
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Relational Databases supported by ADO<br />
Relational Databases supported by ADO<br />
With ADO, you can access virtually any relational database using the Microsoft ADO ODBC Provider (using a<br />
DSN) and most databases using the Microsoft ADO OLE-DB Provider or a vendor supplied ADO OLE-DB<br />
Provider (or ADO.NET provider). Supported databases include:<br />
• Microsoft SQL Server 2005 (Enterprise Edition, Standard Edition, Workgroup Edition, Express Edition,<br />
Compact Edition)<br />
• Microsoft SQL 2000<br />
• MSDE<br />
• Oracle 8i/9i/10g<br />
• MySQL 5<br />
• Sybase<br />
• DB2<br />
• PostgreSQL<br />
• SQL Lite<br />
• Microsoft Access<br />
• Microsoft Excel*<br />
• Delimited Text Files*<br />
* Technically not a relational database, but with the ADO OLE-DB Provider you can access data from these<br />
data sources using the ADO interface.<br />
Notes:<br />
• Microsoft provides ADO.NET Providers for all Microsoft databases including SQL Server, Access,<br />
Excel and Text Files<br />
• Microsoft provides an ADO.NET ODBC Provider that can be used to connect (via ODBC) to most<br />
databases using an ODBC Driver supplied by the database supplier<br />
• When possible, use an ADO OLE-DB Provider instead of an ADO ODBC Provider. It will give better<br />
performance.<br />
29–4 InduSoft Web Studio
Database Terminology<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Database Terminology<br />
The general terminology for databases is as follows:<br />
Database<br />
Server<br />
Catalog<br />
Catalog<br />
Groups<br />
Users<br />
Tables<br />
Colums<br />
Keys<br />
Records<br />
• Database Server<br />
The Database Server handles all queries to the database. There is commonly a Database Management<br />
tool that lets you create or delete Catalogs, Tables within a Catalog and define structure of the Table.<br />
Microsoft SQL Server is an example of a Database Server.<br />
• Catalog<br />
The Catalog is a database that contains one or more Tables. The Database Management tool can create a<br />
new Catalog.<br />
• Groups<br />
A logical organization of users that have access to the Database<br />
• Users<br />
The person who has permission to access the database<br />
• Table<br />
A table is a named data object consisting of a defined set of columns that can be used to store data in a<br />
structured manner, or to contain a key used to index rows in the Table, and some number of unordered<br />
rows (records).<br />
• Column<br />
A vertical component of a Table that contains a common set of information. Each columns can consist of<br />
different data type.<br />
• Key(s)<br />
A column or set of columns used to index information in the table.<br />
• Records<br />
A horizontal component of a Table that consists of a sequence of values, one for each column in the Table.<br />
InduSoft Web Studio 29–5
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Data Type Mapping<br />
Data Type Mapping<br />
While we just got done saying that ADO provides a common interface to databases, you must still consider that<br />
each database supports its own set of data types. The following Data Type Map represents a the data types<br />
supported by SQL Server, Oracle and Access. Consult your database documentation for more details of the<br />
data types supported.<br />
ADO Data Type<br />
Enum<br />
ADO Data Type<br />
Enum Value<br />
adBigInt 20 bigint 9 8<br />
adBinary 128<br />
SQL<br />
Server Size Access Oracle<br />
binary<br />
timestamp<br />
50<br />
8<br />
Raw 7<br />
adBoolean 11 bit 1<br />
2 YesNo<br />
adBSTR 8<br />
adChapter 136<br />
adChar 129 char X Char<br />
adCurrency 6<br />
adDate 7<br />
adDBDate 133<br />
adDBFileTime 137<br />
adDBTime 134<br />
adDBTimeStamp 135<br />
money<br />
smallmoney<br />
datetime<br />
smalldatetime<br />
8<br />
4<br />
0 Currency<br />
0 DateTime 2<br />
8<br />
4<br />
Date<br />
0 DateTime 1<br />
adDecimal 14 Decimal 7<br />
adDouble 5 float 8<br />
0 Double<br />
Float<br />
adEmpty 0<br />
adError 10<br />
adFileTime 64<br />
adGUID 72 uniqueidentifier 5 16<br />
adIDispatch 9<br />
ReplicationID 2,3<br />
adInteger 3<br />
identity 4<br />
int<br />
4<br />
4 AutoNumber<br />
Long Integer<br />
Int 7<br />
adIUnknown 13<br />
29–6 InduSoft Web Studio
Data Type Mapping<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
ADO Data Type<br />
Enum<br />
ADO Data Type<br />
Enum Value<br />
adBigInt 20 bigint 9 8<br />
adBinary 128<br />
SQL<br />
Server Size Access Oracle<br />
binary<br />
timestamp<br />
50<br />
8<br />
Raw 7<br />
adBoolean 11 bit 1<br />
2 YesNo<br />
adBSTR 8<br />
adChapter 136<br />
adChar 129 char X Char<br />
adCurrency 6<br />
money<br />
smallmoney<br />
8<br />
4<br />
0 Currency<br />
adLongVarBinary 205 image 2147483647<br />
OLEObject<br />
Long Raw 7<br />
Blob 8<br />
adLongVarChar 201 text 2147483647 Memo 1, 2 Long 7<br />
Hyperlink 1, 2 Clob 8<br />
adLongVarWChar 203 ntext 5 1073741823 Memo 3<br />
Hyperlink 3 NClob 8<br />
adNumeric 131<br />
adPropVariant 138<br />
decimal<br />
numeric<br />
9<br />
Decimal 3<br />
Decimal<br />
Integer<br />
Number<br />
SmallInt<br />
adSingle 4 real 4<br />
Single<br />
adSmallInt 2 smallInt 2<br />
adTinyInt 16<br />
adUnsignedBigInt 21<br />
adUnsignedInt 19<br />
adUnsignedSmallIn<br />
t<br />
18<br />
Integer<br />
adUnsignedTinyInt 17 tinyInt 1<br />
adUserDefined 132<br />
adVarBinary 204 varbinary 50<br />
Byte<br />
InduSoft Web Studio 29–7
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Data Type Mapping<br />
ADO Data Type<br />
Enum<br />
ADO Data Type<br />
Enum Value<br />
adBigInt 20 bigint 9 8<br />
adBinary 128<br />
SQL<br />
Server Size Access Oracle<br />
binary<br />
timestamp<br />
50<br />
8<br />
Raw 7<br />
adBoolean 11 bit 1<br />
2 YesNo<br />
adBSTR 8<br />
adChapter 136<br />
adChar 129 char X Char<br />
adCurrency 6<br />
money<br />
smallmoney<br />
8<br />
4<br />
0 Currency<br />
ReplicationID 1<br />
adVarChar 200 varchar X<br />
Text 1, 2<br />
VarChar<br />
adVariant 12 sql_variant 9 8016 VarChar2<br />
adVarNumeric 139<br />
adVarWChar 202 nvarchar 5 X<br />
adWChar 130 nchar 5 X<br />
Text 3<br />
1 - ODBC Driver (3.51.171300): Microsoft Access Driver (*.mdb), Access 97 (3.5 format)<br />
2 - OLE DB Provider: Microsoft.Jet.OLEDB.3.51, Access 97 (3.5 format)<br />
3 - OLE DB Provider: Microsoft.Jet.OLEDB.4.0 , Access 2000 (4.0 format)<br />
4 - OLE DB Provider: SQLOLEDB, SQL Server 6.5<br />
5 - OLE DB Provider: SQLOLEDB, SQL Server 7.0 +<br />
6 - The VB Decimal data type can only be used within a Variant, that is, you cannot declare<br />
a VB variable to be of type Decimal.<br />
7 - Oracle 8.0.x Note: DECIMAL and INT are synonyms for NUMBER and NUMBER(10) respectively.<br />
8 - Oracle 8.1.x<br />
9 - OLE DB Provider: SQLOLEDB, SQL Server 2000 +<br />
10 - SQL Server .NET Data Provider (via System.Data.SqlTypes)<br />
NVarChar2<br />
Source: www.carlprothman.net<br />
29–8 InduSoft Web Studio
The ADO Connection Object<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
The ADO Connection Object<br />
The Connection Object is used to establish a virtual connection between an <strong>IWS</strong> application and a specific<br />
Database. The Database can use a DSN (Data Source Name) connection type, typically used to connect to a<br />
database using ODBC, or use a DSN-less database connection.<br />
Notes:<br />
• A DSN, or Data Source Name, is a data structure used to define a connection to a specific database.<br />
The DSN defines the Database name, directory, database driver, User ID, password and other<br />
information.<br />
• DSN’s are defined in Windows XP by going to the Start Control Panel Administrative Tools<br />
Data Sources. You will generally use a System DSN.<br />
The Connection Object has a number of Properties, Methods, Events and returned Object Collections<br />
associated with it. There are more items than can be realistically covered in these materials, however we will<br />
cover the key items in each group. For further information, consult Microsoft’s MSDN website.<br />
Connection Object Properties<br />
Property<br />
Provider<br />
Connection<br />
Cursor Location<br />
Mode<br />
State<br />
Connection Object Methods<br />
Method<br />
Open<br />
Close<br />
Execute<br />
Cancel<br />
OpenSchema<br />
Connection Object Events<br />
Event<br />
Disconnect<br />
ExecuteComplete<br />
Connection Complete<br />
Description<br />
The Name of the Data Provider used for the connection.<br />
A string containing the information for the current connection. This<br />
string can contain the definition of the Data Provider, Data Source,<br />
User ID, Password, File Name, Remote Provider and Remote Server.<br />
Indicates where the cursor for the current connection should be<br />
created, on the Client (adUseClient), or on the Server<br />
(adUseServer). Default is the Server.<br />
Defines the levels of permission for the connection allowed by the<br />
Provider. Mode may be able to instruct the Provider to not allow any<br />
additional connections until your connection is closed.<br />
An integer value indicating whether the Connection Object is opened<br />
(adStateOpen) or closed (adStateClosed)<br />
Description<br />
Explicitly opens a connection to a Data Provider<br />
Close the current Connection<br />
Executes a SQL query (the SQL is sent as a parameter)<br />
Cancels execution of a pending (asynchronous) Execute or Open<br />
method call.<br />
Obtains information on the database structure from the Data Provider.<br />
Description<br />
This event is fired when the Connection Object is set to Nothing and<br />
the Connection is disconnected.<br />
This event is fired after a call to the Execute Method of a Connection<br />
Object<br />
This event is fired when a Connection Object is successfully<br />
instantiated.<br />
InduSoft Web Studio 29–9
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
The ADO Connection Object<br />
Connection Object Collections<br />
Collection<br />
Errors<br />
Properties<br />
Description<br />
A collection of current Error Objects generated by the last execution<br />
performed by the Data Provider. The collection is empty if there are no<br />
errors.<br />
A collection of Data Provider-specific Properties for the Connection<br />
Object. If the Data Provider does not support any custom Properties,<br />
the collection is empty.<br />
There are 3 steps to using a Connection Object. These are:<br />
• Instantiantiating the Connection Object (i.e. create an instance of) through use of the VBScript<br />
CreateObject statement.<br />
• Define the Connection String or set the Connection Object parameters<br />
• Execute one or more Connection Object commands<br />
The Connection Object can use any valid VBScript name, although by convention you may want to use a small<br />
o as a prefix (to indicate an Object), or name the Connection Object as con or something of the sort.<br />
29–10 InduSoft Web Studio
The ADO Connection Object<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Example ADO Connection Strings and use of the Connection Object<br />
A. Text Files<br />
Example: Jet OLE-DB Provider connecting to a CSV File with Header<br />
Dim oConn, connStr<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=” & $GetAppPath() & _<br />
"Extended Properties=""text; HDR=Yes;FMT=CSVDelimited"""<br />
oConn.Open connStr<br />
Example: Jet OLE-DB Provider connecting to a TAB Delimited File with No Header<br />
Dim oConn, connStr<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=” & $GetAppPath() & _<br />
"Extended Properties=""text; HDR=No;FMT=TABDelimited"""<br />
oConn.Open connStr<br />
Notes:<br />
• Text files are, of course, not a relational database. However, with the Microsoft Jet 4.0 Provider,<br />
you can read text files into an ADO recordset object<br />
• Delimiter options are:<br />
CSVDelimited Comma separated variables<br />
TabDelimited Tab separated variables<br />
Delimited(x) x = delimited character<br />
FixedLength Fixed length fields<br />
The choice of delimiters depends on the Provider (Jet or ODBC)<br />
• If the text file does not contain a header row, then use the field number in parenthesis following<br />
the recordset object, e.g. oRS (0)<br />
• Notice the file name is not in the connection string, only the folder. The file name will be used in<br />
the Recordset Open Method to open the file of interest.<br />
B. Microsoft Excel Worksheets<br />
Example: Connecting to Microsoft Excel via ODBC (System DSN is myXL)<br />
Dim oConn<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
oConn.Open “myXL”<br />
Example: Connecting to Microsoft Excel via ODBC (System DSN is myXL)<br />
Dim oConn<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
oConn.Open (“DSN=myXL;”)<br />
Notes:<br />
• The previous two examples use the Microsoft OLE-DB Provider for ODBC Drivers<br />
• ADO will assume the first row in the Excel file will contain the column headings<br />
• Excel does not support multi-user concurrent access.<br />
InduSoft Web Studio 29–11
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
The ADO Connection Object<br />
Example: Connecting to Microsoft Excel (DSN-less) using the JET 4.0 OLEDB Provider with Headers<br />
Dim oConn, connStr<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=” & $GetAppPath() & “myFile.xls;” & _<br />
"Extended Properties=""Excel 8.0; HDR=Yes"""<br />
oConn.Open connStr<br />
Example: Connecting to Microsoft Excel (DSN-less) using the JET 4.0 OLEDB Provider with no Headers<br />
Dim oConn, connStr<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=” & $GetAppPath() & “myFile.xls;” & _<br />
"Extended Properties=""Excel 8.0; HDR=No"""<br />
oConn.Open connStr<br />
Notes:<br />
• The Microsoft OLE-DB Jet 4.0 Provider is used to connect to Microsoft Access, Excel and Text<br />
files. It is used to interact with files created using Microsoft Office 2000, 2002, XP, 2003 and later<br />
products.<br />
• The Microsoft OLE-DB Jet 3.51 Provider is used for Microsoft Office 97 products<br />
• More Microsoft OLE-DB Jet Properties are defined at<br />
http://msdn2.microsoft.com/en-us/library/aa140022(office.10).aspx, and<br />
http://msdn2.microsoft.com/en-us/library/aa139977(office.10).aspx<br />
C. Microsoft Access Database<br />
Example: Connecting to MS Access Database via ODBC (System DSN is myDB)<br />
Dim oConn<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
oConn.Open (“DSN=myDB;”)<br />
Example: Connecting to Microsoft Access Database via ODBC with User Name & Password<br />
Dim oConn<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
oConn.Open (“DSN=myDB; "username","password"”)<br />
Example: Connecting to Microsoft Access (DSN-less) using Connection Object Properties<br />
Dim oConn<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
oConn.Provider = “Microsoft.Jet.OLEDB.4.0”<br />
oConn.Properties (“Data Source”).value= $GetAppPath() & “myDB.mdb”<br />
oConn.Open<br />
Example: Connecting to Microsoft Access (DSN-less) using a Connection String Property<br />
Dim oConn, connStr<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
connStr ="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & $GetAppPath()& "myDB.mdb"<br />
oConn.ConnectionString = connStr<br />
oConn.Open<br />
29–12 InduSoft Web Studio
The ADO Connection Object<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Example: Connecting to Microsoft Access Exclusively<br />
Dim oConn, connStr<br />
Const adModeShareExclusive = &HC<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
connStr ="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & $GetAppPath() & "myDB.mdb"<br />
oConn.Mode = adModeShareExclusive<br />
oConn.Open connStr<br />
Example: Connecting to Microsoft Access that has a Database Password<br />
Dim oConn<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
oConn.Provider = “Microsoft.Jet.OLEDB.4.0”<br />
oConn.ConnectionString = “Data Source=" & $GetAppPath() & "myDB.mdb"<br />
oConn.Properties(“Jet OLEDB:Database Password”)=MyDBPassword<br />
oConn.Open<br />
Example: Connecting to Microsoft Access using a User ID & Password<br />
Dim oConn<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
oConn.Provider = “Microsoft.Jet.OLEDB.4.0”<br />
oConn.ConnectionString = “Data Source=" & $GetAppPath() & "myDB.mdb"<br />
oConn.Open ,,userID, Password<br />
Example: Connecting to Microsoft Access using a User ID & Password<br />
Dim oConn<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
oConn.Provider = “Microsoft.Jet.OLEDB.4.0”<br />
oConn.ConnectionString = “Data Source=" & $GetAppPath() & "myDB.mdb;" &_<br />
“User ID=” & userID & “;Password=” & password<br />
oConn.Open<br />
Example: Connecting to Microsoft Access (DSN-less) using Connection Object Parameters<br />
Dim oConn<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & $GetAppPath() & "myDB.mdb"<br />
Example: Connecting to Microsoft Access (DSN-less) on a Remote Machine<br />
Dim oConn, connStr<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
connStr ="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=\\myServer\myShare\myPath\myDB.mdb"<br />
oConn.ConnectionString = connStr<br />
oConn.Open<br />
Example: Connecting to Microsoft Access (DSN-less) on a Remote Machine<br />
Dim oConn, connStr<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
connStr ="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=\\152.10.101.24\myShare\myPath\myDB.mdb"<br />
oConn.ConnectionString = connStr<br />
oConn.Open<br />
InduSoft Web Studio 29–13
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
The ADO Connection Object<br />
D. Microsoft SQL Server Database<br />
Example: Connecting to Microsoft SQL Server Express (on local PC) with a trusted connection<br />
Dim oConn, connStr<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
connStr = "Provider=SQLOLEDB.1;" & "Data Source=user\sqlexpress;" &_<br />
“Initial Catalog=MyDB;” & “Integrated Security=SSPI”<br />
oConn.Open connStr<br />
Example: Connecting to Microsoft SQL Server (on local PC) with standard security<br />
Dim oConn, connStr<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
connStr = "Provider=SQLOLEDB.1;" & "Data Source=myServer;" &_<br />
“Initial Catalog=MyDB;” & “User ID=UserID;” & “Password=myPassword;”<br />
oConn.Open connStr<br />
Example: Connecting to Microsoft SQL Server (on local PC) with standard security<br />
Dim oConn, connStr<br />
connStr = "Provider=SQLOLEDB.1;" & "Data Source=(local);" & “Initial Catalog=MyDatabaseName;” &_<br />
"User Id=myUsername;" & "Password=myPassword"<br />
oConn.Open connStr<br />
Example: Connecting to an Microsoft SQL Server Database prompting for UserName & Password<br />
Dim oConn<br />
Const adPromptAlways=1<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
oConn.Provider = “sqloledb”<br />
oConn.Properties (“Prompt”)= adPromptAlways<br />
oConn.Open "Data Source=myServerName;" & “Initial Catalog=MyDatabaseName”<br />
Example: Connecting to Microsoft SQL Server on a Remote PC<br />
Dim oConn, connStr<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
connStr = "Provider=SQLOLEDB.1; Data Source=192.168.23.200;Initial Catalog=MyDB;” &_<br />
“Integrated Security=SSPI”<br />
oConn.Open connStr<br />
Example: Connecting to an Microsoft SQL Server Database on a Remote PC (using an IP address)<br />
Dim oConn, connStr<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
connStr = "Provider=sqloledb;" & “Network Library=DBMSSOCN;” &_<br />
"Data Source=xxx.xxx.xxx.xxx, 1433;” & “Initial Catalog=MyDatabaseName;” &_<br />
"User Id=myUsername;" & "Password=myPassword"<br />
oConn.Open connStr<br />
where:<br />
xxx.xxx.xxx.xxx is the IP address where SQL Server is found<br />
1444 is the default port number for SQL Server<br />
You can also add “Encrypt=yes” to enable encryption<br />
29–14 InduSoft Web Studio
The ADO Connection Object<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
E. Microsoft SQL Server 2000 CE Database<br />
Dim oConn, strConn, dbName<br />
Set oConn = CreateObject("ADOCE.Connection.3.1")<br />
dbName = $GetAppPath() & "myDB1.SDF"<br />
strConn = "Provider=Microsoft.SQLServer.OLEDB.CE.2.0;Data Source=" & dbName<br />
oConn.Open strConn<br />
Note:<br />
• SQL Server 2000 CE does not support remote database, only local databases<br />
F. Microsoft SQL Server 2005 Compact Edition for Windows CE<br />
Dim oConn<br />
Set conn = CreateObject("ADOCE.connection.3.1")<br />
oConn.Open "Provider=Microsoft.SQLSERVER.MOBILE.OLEDB.3.0; Data Source = \HardDisk\MyDB.sdf"<br />
G. Oracle Database (9i/10g)<br />
Example: Connecting to an Oracle Database using an OLEDB Provider (from Microsoft)<br />
Dim oConn, connStr<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
connStr = "Provider=msdaora;" & "Data Source=myOracleDB;" & "User Id=myUsername;" & _<br />
"Password=myPassword"<br />
oConn.Open connStr<br />
Example: Connecting to an Oracle Database using an OLEDB Provider (from Oracle)<br />
Dim oConn, connStr<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
connStr = "Provider=OraOLEDB.Oracle.1; Data Source=myDB;User Id=MyID;” &_<br />
“Password=myPassword"<br />
oConn.Open connStr<br />
H. MySQL 5.0 Database<br />
Example: Connecting to a MySQL Database using an OLEDB Provider<br />
Dim oConn, connStr<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
connStr = "Provider=MySQLProv; Data Source=myDB;" & "User Id=myUsername;" & _<br />
"Password=myPassword"<br />
oConn.Open connStr<br />
Example: Connecting to a Remote MySQL Database using an OLEDB Provider<br />
Dim oConn, connStr<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
connStr = "Provider=MySQLProv; Data Source=myDB; Location=192.168.23.200"<br />
oConn.Open connStr<br />
Note:<br />
• In addition to VBScript variables, <strong>IWS</strong> tags can be used in the connection string. E.g. provide the file<br />
name.<br />
• Additional connection strings can be found at:<br />
www.connectionstrings.com<br />
www.carlprothman.net<br />
www.sqlstrings.com<br />
InduSoft Web Studio 29–15
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
The ADO Command Object<br />
The ADO Command Object<br />
The Command Object is used to execute a single query against a database. Queries can create, add, retrieve,<br />
delete or update records in the database. If the query returns any data, the data will return records in a<br />
Recordset Object<br />
The Command Object has a number of Properties, Methods, Events and returned Object Collections<br />
associated with it. There are more items than can be realistically covered in these materials, however we will<br />
cover the key items in each group. For further information, consult Microsoft’s MSDN website.<br />
Command Object Properties<br />
Property<br />
CommandText<br />
CommandTimeout<br />
CommandType<br />
State<br />
Command Object Methods<br />
Method<br />
Cancel<br />
Execute<br />
CreateParameter<br />
Command Object Collections<br />
Collection<br />
Parameters<br />
Properties<br />
Description<br />
A string containing the text of a command you wish to execute against<br />
the database<br />
An integer value representing the number of seconds ADO should wait<br />
for the results of the Command Object’s execution before raising an<br />
error. The default value is 30 seconds.<br />
The type of command that is executed using the Command Object<br />
An integer value indicating whether the Connection Object is opened<br />
(adStateOpen) or closed (adStateClosed)<br />
Description<br />
Cancel the execution of a Method<br />
Executes the Query, SQL Statement or Procedure in the Command<br />
Text Property<br />
Creates a new Parameter Object for the Command Object’s<br />
Parameters Collection<br />
Description<br />
Contains all of the instantiated Parameter Objects that contain<br />
parameters for the current Command Object<br />
Data Provider-specific properties for the Command Object. If the Data<br />
Provider does not support any custom Properties, the Collection is<br />
empty.<br />
29–16 InduSoft Web Studio
The ADO Command Object<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Example using Command Object with Execute and Parameters<br />
Dim oConn, oCmd, oRS<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
Set oCmd = CreateObject(“ADODB.Command”)<br />
Set oRS = CreateObject(“ADODB.Recordset”)<br />
oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & $GetAppPath()& "myDB.mdb"<br />
Set oRs = oCmd.Execute (Select * From Table1”)<br />
Example using Command Object with Execute and Properties<br />
Dim oConn, oCmd, oRS<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
Set oCmd = CreateObject(“ADODB.Command”)<br />
Set oRS = CreateObject(“ADODB.Recordset”)<br />
oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & $GetAppPath()& "myDB.mdb"<br />
oCmd.CommandText = “Select * From Table1"<br />
Set oRs = oCmd.Execute<br />
Example using Command Object with Execute using <strong>IWS</strong> Tags & VBScript variables in SQL<br />
Dim oConn, oCmd, strSql<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
Set oCmd = CreateObject(“ADODB.Command”)<br />
oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & $GetAppPath()& "myDB.mdb"<br />
StrSql = $ID_Insert & ", ' " & $Name_Insert & " ', ' "& $Address_Insert & " ' "<br />
cmd.CommandText = "INSERT into Table1 (ID, Name, Address) values (" & StrSql & ")"<br />
Set oRs=cmd.Execute<br />
Notes:<br />
• One of the primary purposes of the Command Object is to execute SQL commands using the<br />
Execute Method.<br />
• The Execute Method is also available with the Connection Object and the Recordset Object, although<br />
the Command Object is more flexible since it can define, add and remove query parameters.<br />
InduSoft Web Studio 29–17
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
The ADO RecordSet Object<br />
The ADO RecordSet Object<br />
The Recordset Object is the most important Object in ADO. It is used to store records returned from a query (or<br />
Table) and contains a cursor into those records. A Recordset Object consists of Records (rows) and Fields<br />
(columns). An open Connection Object can support multiple Recordsets. Recordsets can also be created<br />
without a Connection Object.<br />
Recordset Object Properties<br />
Property<br />
Description<br />
AbsolutePosition The ordinal number of the current Record in the Recordset<br />
ActiveConnection Indicates to which Connection Object the Recordset object belongs to<br />
BOF<br />
Indicates whether the current Record pointer is pointing to the beginning of the<br />
Recordset. Boolean read-only value.<br />
CursorType Specifies the type of cursor ADO will use for the underlying Data Provider. Default is<br />
adOpenForwardOnly.<br />
DataSource Can be used to specify an Object containing data that will be represented as a<br />
Recordset Object.<br />
EOF<br />
Indicates whether the current Record pointer is pointing to the end of the Recordset.<br />
Boolean read-only value.<br />
Locktype Reflects the current locking scheme placed in the Records during editing (Read-<br />
Only, Pessimistic, Optimistic, or BatchOptimistic)<br />
MaxRecords Sets or retrieves the maximum number of Records returned in a Recordset by a<br />
specific query. If a value of 0, there is no maximum. Can only read when the<br />
Recordset is open<br />
RecordCount Returns the number of records in a Recordset. Can only be used with adOpenStatic<br />
or adOpenKeyset type cursors. Cannot be used (will return -1) with adOpenDynamic<br />
or adOpenForwardOnly.<br />
Sort<br />
Specifies the name of one or more Fields in the Records in the Recordset Object<br />
that will be used to sort the data.<br />
Source<br />
Sets or returns the source for the Recordset<br />
State<br />
An integer value indicating whether the Recordset Object is opened (adStateOpen)<br />
or closed (adStateClosed)<br />
29–18 InduSoft Web Studio
The ADO RecordSet Object<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Recordset Object Methods<br />
Method<br />
AddNew<br />
Cancel<br />
CancelUpdate<br />
Clone<br />
Close<br />
Delete<br />
Find<br />
GetRows<br />
GetString<br />
Move<br />
MoveFirst<br />
MoveLast<br />
MoveNext<br />
MovePrevious<br />
Open<br />
Requery<br />
Save<br />
Seek<br />
Update<br />
Description<br />
Recordset Object Collections<br />
Collection<br />
Fields<br />
Errors<br />
Properties<br />
Adds a new record to the recordset and to the underlying data if the recordset is<br />
updateable<br />
Cancels the execution of a pending (asynchronous) Recordset Open operation<br />
Cancels the update to the current record<br />
Creates a duplicate of the current Recordset<br />
Closes the current Recordset<br />
Deletes the current Record or group of Records from the Recordset and the<br />
underlying data (if the cursor type of the recordset supports updating)<br />
Searches for Records in the Current Recordset Object that match the search criteria<br />
Retrieves multiple records from a Recordset into an Array<br />
Retrieves a Recordset as a string<br />
Moves the current record pointer to a certain number of positions forward or<br />
backward from the current Record. The Recordset must support the forward and<br />
backward movement.<br />
Moves the Record pointer to the first Record in the Recordset<br />
Moves the Record pointer to the last Record in the Recordset<br />
Moves the Record pointer to the next Record in the Recordset<br />
Moves the Record pointer to the previous Record in the Recordset<br />
Opens a Recordset<br />
Repopulates the current Recordset by rerunning the Query<br />
Saves the current Recordset to a file<br />
Searches the current Index in a Recordset to locate a specific value<br />
Saves changes the current record into the Database<br />
Description<br />
Contains each Field Object, corresponding to each column of data in the Recordset<br />
Contains all the Error Objects created in response to a Provider error<br />
Contains Data Provider-specific Properties for the Recordset Object. If the Data<br />
Provider does not support any custom Properties, the Collection is empty.<br />
InduSoft Web Studio 29–19
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
The ADO RecordSet Object<br />
Fields Collection Object<br />
A Recordset object has a Fields Collection Object made up of Field objects. Each Field object corresponds to a<br />
column (Field) in the Recordset. You can populate the Fields collection before opening the Recordset by calling<br />
the Refresh method on the collection.<br />
Fields Collection Properties<br />
Property<br />
Count<br />
Item<br />
Fields Collection Methods<br />
Method<br />
Append<br />
Delete<br />
Refresh<br />
Update<br />
Description<br />
Indicates the number of Objects in the Collection<br />
Indicates a specific member of a Collection, by Name or ordinal number<br />
Description<br />
Appends a Field Object to a Fields Collection. Can create a new Field Object before<br />
it is appended to the Collection.<br />
Deletes a Field Object from the Fields Collection<br />
Updates the Field Objects in the Fields Collection<br />
Saves any changes you make to the Fields Collection of a Recordset Object (since<br />
calling AddNew or changing a field value).<br />
Field Object<br />
The Field Object represents a column of Data in the Recordset.<br />
Fields Collection Properties<br />
Property Description<br />
Name<br />
Sets or Returns a string value that indicates the Name of the Object<br />
Value<br />
Indicates the value assigned to the Field.<br />
DefinedSize Sets and Returns a Long value that is the maximum length in characters of the data<br />
value(s). Default is 0 (no limit)<br />
NumericScale Used when the Type Property is set to adNumeric or adDecimal. Defines the scale<br />
of data values. Byte value. Default is 0.<br />
Type<br />
Indicates the operational data type of the Field. E.g. adNumeric, adSingle<br />
29–20 InduSoft Web Studio
The ADO RecordSet Object<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Recordset Cursor Types<br />
There are four different cursor types defined in ADO:<br />
• Dynamic cursor (adOpenDynamic)<br />
Allows you to view additions, changes, and deletions by other users; allows all types of movement<br />
through the Recordset that doesn't rely on bookmarks; and allows bookmarks if the provider supports<br />
them.<br />
• Keyset cursor (adOpenKeyset)<br />
Behaves like a dynamic cursor, except that it prevents you from seeing records that other users add,<br />
and prevents access to records that other users delete. Data changes by other users will still be visible.<br />
It always supports bookmarks and therefore allows all types of movement through the Recordset.<br />
• Static cursor (adOpenStatic)<br />
Provides a static copy of a set of records for you to use to find data or generate reports; always allows<br />
bookmarks and therefore allows all types of movement through the Recordset. Additions, changes, or<br />
deletions by other users will not be visible. This is the only type of cursor allowed when you open a<br />
client-side Recordset object.<br />
• Forward-only cursor (adForwardOnly)<br />
Allows you to only scroll forward through the Recordset. Additions, changes, or deletions by other<br />
users will not be visible. This improves performance in situations where you need to make only a single<br />
pass through a Recordset.<br />
The CursorType Property can be set prior to opening the Recordset to choose the cursor type, or pass a<br />
CursorType argument with using the Open method. Some providers don't support all cursor types. Check the<br />
documentation for the provider. If you don't specify a cursor type, ADO opens a forward-only cursor by default.<br />
Recordset Cursor Location<br />
The CursorLocation property defines where the recordset is created when it's opened — on the client or the<br />
server. In and <strong>IWS</strong> application, leave this parameter set to Server.<br />
LockType<br />
The LockType property tells the Provider what type of locks should be placed on records during editing. Locking<br />
can prevent one user from reading data that is being changed by another user, and it can prevent a user from<br />
changing data that is about to be changed by another user.<br />
Modifying a record in an Access database locks some neighboring records. This is because Access uses, so<br />
called, page locking strategy. This means that if a user is editing a record, some other user won't be allowed to<br />
modify that record, or even to modify the next few records after or before it.<br />
• LockReadOnly (adLockReadOnly)<br />
Read only locking simply does not allow data editing. This lock is useful in conditions where your<br />
application must temporarily prevent data changes, but still can allow unrestricted reading. Read only<br />
locking with CursorType set to ctForwardOnly is ideal for reporting purposes.<br />
• LockOptimistic (adLockOptimistic)<br />
Optimistic locking locks the record only when it's physically updated. This type of locking is useful in<br />
conditions where there is only a small chance that a second user may update a row in the interval<br />
between when a cursor is opened and the row is finally updated. The current values in the row are<br />
compared with the values retrieved when the row was last fetched.<br />
• LockPessimistic (adLockPessimistic)<br />
Pessimistic locking locks each record while it's being edited. This option tells ADO to get an exclusive<br />
lock on the row when the user makes any change to any column in the record. The ADOExpress<br />
InduSoft Web Studio 29–21
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
The ADO RecordSet Object<br />
components don't directly support pessimistic record locking because ADO itself does not have any<br />
way to arbitrarily lock a given record and still support navigating to other records.<br />
• LockBatchOptimistic (adLockBatchOptimistic)<br />
BatchOptimistic locking is used with disconnected recordsets. These recordsets are updated locally and<br />
all modifications are sent back to the database in a batch.<br />
29–22 InduSoft Web Studio
The ADO RecordSet Object<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Using the Recordset Object<br />
The following are examples using the Recordset Object:<br />
A. Using the Recordset Object with Text Files<br />
Example : Reading data from a text file (CSV delimited) with Headers<br />
Dim oConn, connStr, oRS, strSQL, msg<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
Set oRS = CreateObject(“ADODB.Recordset”)<br />
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=” & $GetAppPath() & _<br />
"Extended Properties=""text; HDR=Yes;FMT=CSVDelimited"""<br />
oConn.Open connStr<br />
strSQL = "Select * FROM myFile.csv"<br />
Set oRS = oConn.Execute(strSQL)<br />
msg = “”<br />
Do Until oRS.EOF<br />
msg = msg & “V1= “& oRS.Fields.Item(“V1”) & “ V2= “& oRS.Fields.Item(“V2”) & VbCrLf<br />
oRS.MoveNext<br />
Loop<br />
Msgbox msg<br />
oRS.close<br />
oConn.close<br />
Set oRS = Nothing<br />
Set oConn = Nothing<br />
Example : Reading data from a text file (CSV delimited) with Headers<br />
Dim oConn, oDB, oRS, strConn, strSQL, strRec, Path<br />
Const adOpenStatic = 3<br />
Const adLockOptimistic = 3<br />
Const adCmdText = &H0001<br />
Set oConn = CreateObject("ADODB.Connection")<br />
Set oRS = CreateObject("ADODB.Recordset")<br />
Path = "C:\myData\"<br />
strConn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Path &_<br />
";Extended Properties='text;HDR=No;FMT=CSVDelimited'"<br />
oConn.Open strConn<br />
strSql = "Select * FROM test.txt"<br />
'strSql = "Select * FROM MovimentoOperativos.txt"<br />
oRS.open strSql, oConn, adOpenStatic, adLockOptimistic, adCmdText<br />
recStr = ""<br />
Do Until oRS.EOF<br />
recStr = recStr & " Col1= " & oRS (0)<br />
recStr = recStr & " Col2= " & oRS (1) & vbCrLf<br />
oRS.Movenext<br />
Loop<br />
MsgBox recStr<br />
oRS.close<br />
oConn.close<br />
Set oRS = Nothing<br />
Set oConn = Nothing<br />
Note:<br />
• If the Text file contains no header row, use oRS(n) to access the an item from the record (n=item # in<br />
the record, starting with 0).<br />
InduSoft Web Studio 29–23
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
The ADO RecordSet Object<br />
B. Using the Recordset Object with Microsoft Excel Worksheets<br />
Example : Reading data from an Excel file with a header row<br />
Dim oConn, strConn, oRS, myFile, msg<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
Set oRS = CreateObject(“ADODB.Recordset”)<br />
myFile = “C:\test\myDB.xls”<br />
strConn = “Provider=Microsoft.Jet.OLEDB.4.0;” & “Data Source=“ & myfile & “;” &_<br />
“Extended Properties = “”Excel 8.0; HDR=Yes”””<br />
oConn.open = strConn<br />
Set oRS = oConn.Execute (“SELECT * FROM [Alarm$]”)<br />
msg = “”<br />
While Not rs.EOF<br />
msg = msg & “Alarm =” & oRS(“time”) & “ reason= “ & oRS(“reason”) & VbCrLf<br />
oRS.MoveNext<br />
Wend<br />
Msgbox msg<br />
oRS.close<br />
oConn.close<br />
Set oRS = Nothing<br />
Set oConn = Nothing<br />
Example : Reading data from an Excel file with no header row<br />
Dim oConn, strConn, oRS, myFile, strSQL, msg, temp, loopCtr<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
Set oRS = CreateObject(“ADODB.Recordset”)<br />
myFile = “C:\test\myDB.xls”<br />
strConn = “Provider=Microsoft.Jet.OLEDB.4.0;” & “Data Source=“ & myfile & “;” &_<br />
“Extended Properties = “”Excel 8.0; HDR=No”””<br />
oConn.open = strConn<br />
temp = $myVal<br />
strSQL = “SELECT * FROM [Alarm$] WHERE (F6=’Hi Alarm’) AND (F7 IS NULL) AND (F8=’”&temp”’)”<br />
Set oRS = oConn.Execute (strSQL)<br />
Msg = “”<br />
loopCtr = 0<br />
While Not rs.EOF<br />
msg= msg & “Alarm =” & oRS(“F4”) & “ reason= “ & oRS(“F5”) & VbCrLf<br />
loopCtr = loopCtr + 1<br />
oRS.MoveNext<br />
Wend<br />
Msgbox “Total of “ & loopCtr & “ records” & VbCrLf & msg<br />
oRS.close<br />
oConn.close<br />
Set oRS = Nothing<br />
Set oConn = Nothing<br />
29–24 InduSoft Web Studio
The ADO RecordSet Object<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Example : Writing data to a cell in an Excel file with no header row<br />
Dim oConn, connStr, oRS, myFile, strSQL, msg, temp, loopCtr, temp, newVal<br />
Set oConn = CreateObject(“ADODB.Connection”)<br />
Set oRS = CreateObject(“ADODB.Recordset”)<br />
myFile = “C:\test\myDB.xls”<br />
connStr = “Provider=Microsoft.Jet.OLEDB.4.0;” & “Data Source=“ & myfile & “;” &_<br />
“Extended Properties = Excel 8.0; HDR=No”<br />
oConn.open = strConn<br />
temp = $mySearchData<br />
newVal = $myNewVal<br />
strSQL = "Select * From [Alarm$] Where F5='"&temp&"' "<br />
oRS.Open strSQL, oDB, adOpenKeySet, adLockOptimistic<br />
oConn.BeginTrans<br />
oRS.update "F8", newVal<br />
oConn.CommitTrans<br />
oRS.close<br />
oConn.close<br />
Set oRS = Nothing<br />
Set oConn = Nothing<br />
Notes:<br />
• The Excel Worksheet name syntax in the SQL statement opening the recordset must be as follows:<br />
[Worksheet$]<br />
• If the Excel file contains no header row, use Fx as the column designator (e.g. F1, F5, etc.)<br />
• If looking for an cell that is empty in a SQL Query, use the SQL command IS NULL<br />
• If using a VBScript variable an an SQL argument, it must be enclosed in a single quote ‘, followed by<br />
a double quote “, then an & symbol, the VBScript variable, a double quote, then a single quote.<br />
InduSoft Web Studio 29–25
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
The ADO RecordSet Object<br />
C. Using the Recordset Object with Microsoft Access<br />
Example Program to print Fields of a MS Access Table using the Field Object and Field Collection<br />
Dim con, fld, flds, rs<br />
Dim strConn<br />
Dim i, totCount, myStr<br />
Set con = CreateObject("ADODB.Connection")<br />
Set rs = CreateObject("ADODB.Recordset")<br />
con.Provider = "Microsoft.Jet.OLEDB.4.0"<br />
con.Properties("Data Source").value = $GetAppPath()& "MachineInfo.mdb"<br />
con.Open<br />
Set rs = con.Execute ("Select * From Table1")<br />
Set flds = rs.Fields<br />
totCount = flds.Count<br />
MsgBox "Count = " & totcount<br />
myStr = ""<br />
For Each fld In Flds<br />
myStr = myStr & "Name = " & fld.Name & " Type = " & fld.Type & " Value = " & fld.Value & vbCrLf<br />
Next<br />
MsgBox "total fields = " & totCount & vbCrLf & myStr<br />
rs.close<br />
con.close<br />
Set rs = Nothing<br />
Set con = Nothing<br />
Example – Reading data from an ADO DB and saving into an <strong>IWS</strong> Class Array<br />
Dim oConn, oDB, oRS, strSQL, DBRowCount<br />
Set odb = CreateObject ("ADODB.Connection")<br />
Set oRS= CreateObject (“ADODB.Recordset”)<br />
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & $GetAppPath() & “MyDB.mdb"<br />
oDB.open strConn<br />
strSQL = "Select * From Table1"<br />
Set oRS = oDB.Execute (strSQL)<br />
DbRowCount = -1<br />
While Not oRS.EOF<br />
DbRowCount = DbRowCount + 1<br />
$ProdStat[DbRowCount].Time= CStr(oRS("Time"))<br />
$ProdStat[DbRowCount].Total = CInt(oRS ("Total"))<br />
$ProdStat[DbRowCount].Good = CInt(oRS ("Good"))<br />
$ProdStat[DbRowCount].Marginal = CInt(oRS ("Marginal"))<br />
$ProdStat[DbRowCount].Bad = CInt(oRS ("Bad"))<br />
oRS.MoveNext<br />
Wend<br />
oDB.close<br />
Set oDB = Nothing<br />
29–26 InduSoft Web Studio
The ADO RecordSet Object<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
D. Using the Recordset Object with Oracle<br />
Example Program to write data into an Oracle Database<br />
Dim strConn, strSQL, oDB, oRS<br />
Dim msg, m, LoopCounter, myTemp<br />
Const adOpenKeySet=1<br />
Const adLockOptimistic=3<br />
strConn=”Provider=OraOLEDB.Oracle.1;Data Source=MyDB; User ID=MyID;Password=MyPW;”<br />
Set oDB=CreateObject(“ADODB.Connection”)<br />
Set oRS=CreateObject(“ADODB.Recordset”)<br />
oDB.open strConn<br />
strSQL = “Select * FROM myTable”<br />
oRS.open strSQL, oDB, adOpenKeySet, adLockOptimistic<br />
‘Append data at end of file<br />
While Not oRS.eof<br />
oRS.movenext<br />
Wend<br />
oRS.addnew<br />
myTemp=Date & “ “ & Time<br />
oRS(“read_date”)=Cstr(myTemp)<br />
oRS(“quantity”) = $myQuantity<br />
oRS(“tank_number”)= Cstr($tankLabel)<br />
oDB.BeginTrans<br />
oRS.update<br />
oDB.CommitTrans<br />
oRS.close<br />
oDB.close<br />
Set oRS=Nothing<br />
Set oDB=Nothing<br />
E. Examples using Recordset Object Methods<br />
Move Previous<br />
If Not oRS =True Then<br />
oRS.moveprevious ‘Record cursor type must support this<br />
End If<br />
Move Next<br />
If Not oRS =True Then<br />
oRS.movenext<br />
End If<br />
‘Works even with forward only cursor types<br />
Add a new Record<br />
With oRS<br />
.addnew<br />
.Fields(“Field1”) = myVal1<br />
.Fields(“Field2”) = myVal2<br />
.Fields(“Field3”) = myText3<br />
.Update<br />
‘Updates database<br />
End With<br />
InduSoft Web Studio 29–27
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
The ADO RecordSet Object<br />
Deleting a Record<br />
If Not (oRS.BOF=True) Or (oRS.EOF=True) Then<br />
oRS.Delete<br />
End If<br />
29–28 InduSoft Web Studio
The Stream Object<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
The Stream Object<br />
The Stream object provides the means to read, write, and manage a stream of bytes. This byte stream may be<br />
text or binary and is limited in size only by system resources. Typically, ADO Stream objects are used to contain<br />
the data of a Recordset saved in XML format<br />
This Example saves a Recordset to a file and then to a Stream. It then opens the persisted stream into<br />
another Recordset.<br />
Dim con, rs1, rs2, stm, StrRst<br />
Const adPersistXML =1<br />
Set con = CreateObject("ADODB.Connection")<br />
Set rs1 = CreateObject("ADODB.Recordset")<br />
Set rs2 = CreateObject("ADODB.Recordset")<br />
Set stm = CreateObject("ADODB.Stream")<br />
con.Provider = "Microsoft.Jet.OLEDB.4.0"<br />
con.Properties("Data Source").value = $GetAppPath()& "MachineInfo.mdb"<br />
con.Open<br />
Set rs1 = con.Execute ("Select * From Table1")<br />
rs1.Save $GetAppPath()& "MachineInfo.xml", adPersistXML<br />
rs1.Save stm, adPersistXML<br />
rs2.Open stm<br />
This Example persists a Recordset into a Stream in XML format. It then reads the Stream into a string that you<br />
can examine, manipulate, or display.<br />
Dim con, rs, stm, StrRst<br />
Const adReadAll = -1<br />
Const adPersistXML =1<br />
Set con = CreateObject("ADODB.Connection")<br />
Set rs = CreateObject("ADODB.Recordset")<br />
Set stm = CreateObject("ADODB.Stream")<br />
con.Provider = "Microsoft.Jet.OLEDB.4.0"<br />
con.Properties("Data Source").value = $GetAppPath()& "MachineInfo.mdb"<br />
con.Open<br />
Set rs = con.Execute ("Select * From Table1")<br />
rs.Save stm, adPersistXML<br />
strRst = stm.ReadText (adReadAll)<br />
'Display thee XML data.<br />
MsgBox strRst<br />
InduSoft Web Studio 29–29
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Using the ADOX Object Model<br />
Using the ADOX Object Model<br />
ADOX (ADO Extensions) is a set of Extension Objects to the ADO Programming Model, created by Microsoft<br />
following the release of ADO 2.1. These Objects are primarily used for Schema (Data) Definition and Security.<br />
The entire ADOX Model is beyond the scope of these materials, although there are some useful features which<br />
will be covered here.<br />
Microsoft designed ADOX to work with the Microsoft Jet OLE-DB Provider. This means that a runtime system<br />
with <strong>IWS</strong> and the Jet OLE-DB Provider can create blank Excel spreadsheets or Access Database without either<br />
the Excel or Access program being installed on the runtime system. ADOX can be used to create additional<br />
tables (Access) or Worksheets (Excel), and define the fields (columns). However, the use of ADOX with other<br />
databases is problematic. For example, ADOX will not work with Oracle since Oracle is case-sensitive, while Jet<br />
is not.<br />
The ADOX object model starts with the Catalog object, the top-level object providing schema information about<br />
a Data Store. The Catalog object contains a number of objects as Properties, each of which are collections.<br />
(For example, the Tables property of the Catalog object is a collection of Table objects.) These Catalog Object<br />
Properties include:<br />
• Tables<br />
• Groups<br />
• Users<br />
• Procedures<br />
• Views<br />
ADOX CatalogObject Properties<br />
Property<br />
ActiveConnection<br />
ADOX Catalog Object Methods<br />
Method<br />
Create<br />
ADOX Catalog Collections<br />
Collection<br />
Tables<br />
Users<br />
Description<br />
Sets a Connection Object of a string containing the definition for a<br />
connection. Returns the active Connection Object.<br />
Description<br />
Creates a new Catalog. Uses a connection string parameter to<br />
connect to the Data Source<br />
Description<br />
A collection containing all the Tables in the Catalog<br />
A collection containing all the Catalog’s users<br />
29–30 InduSoft Web Studio
Using the ADOX Object Model<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
In addition to the Catalog Object, ADOX has two other Objects that are useful to manipulate Data Sources.<br />
These are the Table Object and Column Object. The Table Object can be used to create a new Table<br />
consisting of columns, indexes and keys.<br />
ADOX Table Object Properties<br />
Property<br />
Name<br />
Type<br />
Parent Catalog<br />
Description<br />
Sets or Returns the name of the Table<br />
Returns the Type of Table (e.g. Table, System Table, or Global<br />
Temporary.<br />
Sets and Returns the Parent Catalog of the Table Object.<br />
ADOX Table Collections<br />
Collection<br />
Columns<br />
Keys<br />
Description<br />
Contains all Column Objects of a Table<br />
Contains all Keys of a Table<br />
The Columns Collection for the Table Object represents al of the Column Objects in the Table. This Collection<br />
is useful for adding and removing Columns in the Table.<br />
ADOX Column Collection Methods<br />
Method<br />
Description<br />
Append<br />
Adds a new Column Object to the Columns Collection<br />
Delete<br />
Deletes a Column from the Table Object<br />
Example Usage of the ADOX Column Collection Object<br />
oTable.Columns.Append Column [,optType] [,optDefinedSize]<br />
where:<br />
Column= a Name to create and append, or Column Object to append to the Table<br />
optType= a long value that spefices the data type of the Column<br />
optDefiendSize= a long value that specifies the size of the Column<br />
The Column Object is used to represent a column (Fields) for a Table.<br />
ADOX Column Object Properties<br />
Property<br />
Name<br />
Type<br />
Parent Catalog<br />
Sort Order<br />
Defined Size<br />
Numeric Scale<br />
Description<br />
Sets or Returns the name of the Column<br />
Sets or Returns a Long value that can be one of the DataTypeEnum<br />
constants. Default is adVarWChar.<br />
Sets and Returns the Parent Catalog of the Column Object.<br />
Indicates the Sort sequence for the column (Index columns only).<br />
Default is adSortAscending.<br />
Sets and Returns a Long value that is the maximum length in<br />
characters of the data value(s). Default is 0 (no limit)<br />
Used when the Type Property is set to adNumeric or adDecimal.<br />
Defines the scale of data values. Byte value. Default is 0.<br />
InduSoft Web Studio 29–31
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Using the ADOX Object Model<br />
Example using the Catalog Object to Create a new Microsoft Access Database<br />
The Catalog Object first needs to be instantiated just like other Objects in VBScript. This is done by the<br />
following method:<br />
Dim oADOXDB<br />
Set oADOXDB = CreateObject (“ADOX.Catalog”)<br />
Now that we have created a Catalog Object, we can use the Catalog Object to create a new Data Source using<br />
the Data Provider. For instance, we could create a new Microsoft Access Database.<br />
Dim oADOXDB<br />
Set oADOXDB = CreateObject (“ADOX.Catalog”)<br />
oADOXDB.Create "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & $GetAppPath()& "newDB.mdb"<br />
The location and name of the new Access Database can be changed by specifying a different name in the Data<br />
Provider string. Note that this is similar to a connection string.<br />
Note:<br />
• The name of the Data Source must be unique (i.e. does not already exist). If it does, you will receive<br />
the following error message: “Viewer: Runtime Error => screenX.scr : Screen Script : Line X :<br />
Database already exists. (-2147217897)” in the Output Window. The Sceen Name and Line Number<br />
will depend on your application (or the Script may be located in a Math Worksheet).<br />
Now that the Access database file has been created, we can create a Table in the database, and add Fields<br />
(columns) and a Primary Key constraint.<br />
Dim oADOXDB, oTable<br />
Const adInteger = 3<br />
Const adVarWChar = 202<br />
Set oADOXDB = CreateObject (“ADOX.Catalog”)<br />
Set oTable = CreateObject(“ADOX.Table”)<br />
oADOXDB.Create "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & $GetAppPath()& "newDB.mdb"<br />
oTable.Name = “Table1”<br />
oTable.Columns.Append “ID”, adInteger<br />
‘integer column<br />
oTable.Columns.Append “Machine Name”, adVarWChar, 30 ‘variable width character column, max=30<br />
oTable.Columns.Append “Hourly Production”. adInteger ‘integer column<br />
oTable.Keys.Append “PK_ID”, 1, “ID”<br />
‘primary key column, 1=primary key<br />
oADOXDB.Tables.Append oTable<br />
In the example above, Table1 is the new table name, Machine Name is a column that is 30 characters wide,<br />
with variable width characters and Hourly Production is a column containing integers.<br />
The ID column will be used as the Primary Key field. The Keys.Append command puts a Primary Key constraint<br />
on this field. PK_ID is the name of the Primary Key, the 2 nd argument is the type of key (1=primary key), and<br />
the 3 rd argument in the Keys.Append command specifies the column which will be the Primary key. Remember<br />
that each primary key needs to be a unique number or name. As an alternative, we could have chosen to put a<br />
primary key constraint on the Machine Name column.<br />
29–32 InduSoft Web Studio
Using the ADOX Object Model<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Example using the Catalog Object to Create a new Microsoft Excel File<br />
Following the above example (creating a new Microsoft Access Database), we can create a new Microsoft<br />
Excel file using the following code:<br />
Dim oADOXDB, oTable, oColumn, i<br />
Const adDouble = 5<br />
Set oADOXDB = CreateObject("ADOX.Catalog")<br />
Set oTable = CreateObject("ADOX.Table")<br />
oADOXDB.ActiveConnection = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & $GetAppPath()& _<br />
"newXL.xls;" & "Extended Properties = ""Excel 8.0; HDR=Yes"""<br />
oTable.Name = "ProdData"<br />
For i = 1 To 4<br />
Set oColumn = CreateObject("ADOX.Column")<br />
With oColumn<br />
.Name ="Col" & i<br />
.Type = adDouble<br />
End With<br />
oTable.Columns.Append oColumn<br />
Set oColumn = Nothing<br />
Next<br />
oADOXDB.Tables.Append oTable<br />
Notes:<br />
• ADOX is primary used to support Microsoft Access and Excel. It has limited support for Microsoft<br />
SQL Server.<br />
• For other databases, use the Database Manager tool to create a new catalog.<br />
• You can use SQL the Create Table command and possibly the Create Database command to<br />
create a new Catalog (if the Database Server supports this command).<br />
• You can use T-SQL for Microsoft SQL Server to create a new Catalog.<br />
• ADOX is powerful in that you can create Microsoft Access databases and Excel worksheets on a<br />
runtime system (from the <strong>IWS</strong> application) without Microsoft Access or Microsoft Excel being<br />
installed on the system. The file (.mdb for Access, .xls for Excel) can be later copied or moved to a<br />
remote platform.<br />
• A Windows CE version of ADOX is available – ADOXCE.<br />
InduSoft Web Studio 29–33
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
ADOCE and ADOXCE<br />
ADOCE and ADOXCE<br />
Microsoft provides a version of ADO for Windows CE applications. The ADOCE version 3.1 control is shipped<br />
with Microsoft Embedded Tools 3.0 and can be downloaded from Microsoft’s website. ADOCE version 3.1<br />
replaces ADOCE control 2.0 and 3.0. You must use the version number in the programmatic identifier, or<br />
ProgID. If you do not, you may get a “Create Object Error” when executing your application.<br />
The ADOCE version 3.1 control is designed to work with data sources that use an OLE-DB provider. ADOCE<br />
provides a subset of ADO’s (ADODB) functionality. Most of ADOCE’s syntax is the same as ADO, and many of<br />
the error values and error strings are the same.<br />
ADOXCE is Microsoft’s ActiveX Data Objects Extensions for Data Definition Language (DDL) and Security for<br />
the Windows CE operating system (ADOXCE), an extension (companion library) to the ADOCE objects and<br />
programming model. ADOXCE provides objects for schema creation and modification (creating, modifying and<br />
deleting schema objects such as databases and tables). Unlike ADOX, ADOXCE does not include any security<br />
objects (e.g. users or groups).<br />
The ADOCE Object Model is shown below. Note that unlike the ADO Object Model, the following Objects are<br />
not available in ADOCE: Command Object, Record Object, Stream Object, Errors Object<br />
ADOCE Object ProgID Description<br />
Connection ADOCE.Connection.3.1 Used to establish connections between VBScript and the<br />
database server<br />
Recordset ADOCE.Recordset.3.1 Used to store, view and manipulate results of a query. Also<br />
used to store and manipulate created records.<br />
Fields<br />
A collection of Field Objects<br />
Field<br />
Allows you to access each Field (column) in a Recordset<br />
Object<br />
Errors<br />
A collection of Error Objects<br />
Error ADOB.Error An Error Object containing the details of a Data Provider error<br />
OpenSchema<br />
29–34 InduSoft Web Studio
ADOCE and ADOXCE<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
The RecordSet Object<br />
Recordset Object Properties<br />
Property<br />
Description<br />
AbsolutePage Specifies which page to move for a new current record<br />
AbsolutePosition Specifies the ordinal number (position) of the current Record in the Recordset<br />
ActiveConnection Sets the current database connection. Default is a zero-length string “”<br />
BOF<br />
Indicates whether the current Record pointer is pointing to the beginning of the<br />
Recordset. Boolean read-only value.<br />
Bookmark Specifies a bookmark that uniquely identifies a record in a Recordset Object<br />
CacheSize Specifies the number of records from a Recordset Object that are cached locally in<br />
memory.<br />
CursorType Specifies the type of cursor ADO will use for the underlying Data Provider. Default is<br />
adOpenForwardOnly.<br />
EditMode Indicates the editing status of the current record<br />
EOF<br />
Indicates whether the current Record pointer is pointing to the end of the Recordset.<br />
Boolean read-only value.<br />
Locktype Reflects the current locking scheme placed in the Records during editing (Read-<br />
Only, Pessimistic, Optimistic, or BatchOptimistic)<br />
PageCount Indicates how many pages of data the Recordset Object contains<br />
PageSize Indicates how many records constitute one page in the Recordset<br />
RecordCount Returns a Long Value that indicates the current number of records in a Recordset<br />
Object<br />
Source<br />
Indicates the source for the data in a Recordset Object – SQL statement or Table<br />
name<br />
Recordset Object Methods<br />
Method<br />
AddNew<br />
CancelUpdate<br />
Clone<br />
Close<br />
Delete<br />
GetRows<br />
Move<br />
MoveFirst<br />
MoveLast<br />
MoveNext<br />
MovePrevious<br />
Open<br />
Supports<br />
Update<br />
Description<br />
Adds a new record to the recordset and to the underlying data if the recordset is<br />
updateable<br />
Cancels the update to the current record (cancels changes held in memory)<br />
Creates a duplicate of the current Recordset<br />
Closes the current Recordset<br />
Deletes the current Record or group of Records from the Recordset and the<br />
underlying data (if the cursor type of the recordset supports updating)<br />
Retrieves multiple records from a Recordset into an Array<br />
Moves the current record pointer to a certain number of positions forward or<br />
backward frin the current Record. The Recordset must support the forward and<br />
backward movement.<br />
Moves the Record pointer to the first Record in the Recordset<br />
Moves the Record pointer to the last Record in the Recordset<br />
Moves the Record pointer to the next Record in the Recordset<br />
Moves the Record pointer to the previous Record in the Recordset<br />
Defines and opens a Recordset, executes SQL commands<br />
Determines if the Recordset supports certain features<br />
Saves changes the current record into the Database<br />
InduSoft Web Studio 29–35
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
ADOCE and ADOXCE<br />
'ADOCE Cursor types<br />
Const adOpenKeyset = 1<br />
Const adOpenDynamic = 2<br />
Const adOpenStatic = 3<br />
'ADOCE Lock Types<br />
Const adLockReadOnly = 1<br />
Const adLockPessimistic = 2<br />
Const adLockOptimistic = 3<br />
Const adLockBatchOptimistic = 4<br />
Example: Instancing the ADOCE Connection Object and Recordset Object<br />
Dim oConn, oRS<br />
Set oConn = CreateObject(“ADOCE.Connection.3.1”)<br />
Set oRS = CreateObject(“ADOCE.Recordset.3.1”)<br />
29–36 InduSoft Web Studio
ADOVBS Constants<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
ADOVBS Constants<br />
Microsoft provides an ADO Constants Include file for use with VBScript. This file can generally be found in the<br />
C:\Program Files\Common Files\System directory. The contents of this file are documented below for reference<br />
purposes:<br />
'---- CursorTypeEnum Values ----<br />
Const adOpenForwardOnly = 0<br />
Const adOpenKeyset = 1<br />
Const adOpenDynamic = 2<br />
Const adOpenStatic = 3<br />
'---- CursorOptionEnum Values ----<br />
Const adHoldRecords = &H00000100<br />
Const adMovePrevious = &H00000200<br />
Const adAddNew = &H01000400<br />
Const adDelete = &H01000800<br />
Const adUpdate = &H01008000<br />
Const adBookmark = &H00002000<br />
Const adApproxPosition = &H00004000<br />
Const adUpdateBatch = &H00010000<br />
Const adResync = &H00020000<br />
Const adNotify = &H00040000<br />
Const adFind = &H00080000<br />
Const adSeek = &H00400000<br />
Const adIndex = &H00800000<br />
'---- LockTypeEnum Values ----<br />
Const adLockReadOnly = 1<br />
Const adLockPessimistic = 2<br />
Const adLockOptimistic = 3<br />
Const adLockBatchOptimistic = 4<br />
'---- ExecuteOptionEnum Values ----<br />
Const adAsyncExecute = &H00000010<br />
Const adAsyncFetch = &H00000020<br />
Const adAsyncFetchNonBlocking = &H00000040<br />
Const adExecuteNoRecords = &H00000080<br />
Const adExecuteStream = &H00000400<br />
'---- ConnectOptionEnum Values ----<br />
Const adAsyncConnect = &H00000010<br />
'---- ObjectStateEnum Values ----<br />
Const adStateClosed = &H00000000<br />
Const adStateOpen = &H00000001<br />
Const adStateConnecting = &H00000002<br />
Const adStateExecuting = &H00000004<br />
Const adStateFetching = &H00000008<br />
'---- CursorLocationEnum Values ----<br />
Const adUseServer = 2<br />
Const adUseClient = 3<br />
InduSoft Web Studio 29–37
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
ADOVBS Constants<br />
'---- DataTypeEnum Values ----<br />
Const adEmpty = 0<br />
Const adTinyInt = 16<br />
Const adSmallInt = 2<br />
Const adInteger = 3<br />
Const adBigInt = 20<br />
Const adUnsignedTinyInt = 17<br />
Const adUnsignedSmallInt = 18<br />
Const adUnsignedInt = 19<br />
Const adUnsignedBigInt = 21<br />
Const adSingle = 4<br />
Const adDouble = 5<br />
Const adCurrency = 6<br />
Const adDecimal = 14<br />
Const adNumeric = 131<br />
Const adBoolean = 11<br />
Const adError = 10<br />
Const adUserDefined = 132<br />
Const adVariant = 12<br />
Const adIDispatch = 9<br />
Const adIUnknown = 13<br />
Const adGUID = 72<br />
Const adDate = 7<br />
Const adDBDate = 133<br />
Const adDBTime = 134<br />
Const adDBTimeStamp = 135<br />
Const adBSTR = 8<br />
Const adChar = 129<br />
Const adVarChar = 200<br />
Const adLongVarChar = 201<br />
Const adWChar = 130<br />
Const adVarWChar = 202<br />
Const adLongVarWChar = 203<br />
Const adBinary = 128<br />
Const adVarBinary = 204<br />
Const adLongVarBinary = 205<br />
Const adChapter = 136<br />
Const adFileTime = 64<br />
Const adPropVariant = 138<br />
Const adVarNumeric = 139<br />
Const adArray = &H2000<br />
29–38 InduSoft Web Studio
ADOVBS Constants<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
'---- FieldAttributeEnum Values ----<br />
Const adFldMayDefer = &H00000002<br />
Const adFldUpdatable = &H00000004<br />
Const adFldUnknownUpdatable = &H00000008<br />
Const adFldFixed = &H00000010<br />
Const adFldIsNullable = &H00000020<br />
Const adFldMayBeNull = &H00000040<br />
Const adFldLong = &H00000080<br />
Const adFldRowID = &H00000100<br />
Const adFldRowVersion = &H00000200<br />
Const adFldCacheDeferred = &H00001000<br />
Const adFldIsChapter = &H00002000<br />
Const adFldNegativeScale = &H00004000<br />
Const adFldKeyColumn = &H00008000<br />
Const adFldIsRowURL = &H00010000<br />
Const adFldIsDefaultStream = &H00020000<br />
Const adFldIsCollection = &H00040000<br />
'---- EditModeEnum Values ----<br />
Const adEditNone = &H0000<br />
Const adEditInProgress = &H0001<br />
Const adEditAdd = &H0002<br />
Const adEditDelete = &H0004<br />
'---- RecordStatusEnum Values ----<br />
Const adRecOK = &H0000000<br />
Const adRecNew = &H0000001<br />
Const adRecModified = &H0000002<br />
Const adRecDeleted = &H0000004<br />
Const adRecUnmodified = &H0000008<br />
Const adRecInvalid = &H0000010<br />
Const adRecMultipleChanges = &H0000040<br />
Const adRecPendingChanges = &H0000080<br />
Const adRecCanceled = &H0000100<br />
Const adRecCantRelease = &H0000400<br />
Const adRecConcurrencyViolation = &H0000800<br />
Const adRecIntegrityViolation = &H0001000<br />
Const adRecMaxChangesExceeded = &H0002000<br />
Const adRecObjectOpen = &H0004000<br />
Const adRecOutOfMemory = &H0008000<br />
Const adRecPermissionDenied = &H0010000<br />
Const adRecSchemaViolation = &H0020000<br />
Const adRecDBDeleted = &H0040000<br />
'---- GetRowsOptionEnum Values ----<br />
Const adGetRowsRest = -1<br />
'---- PositionEnum Values ----<br />
Const adPosUnknown = -1<br />
Const adPosBOF = -2<br />
Const adPosEOF = -3<br />
InduSoft Web Studio 29–39
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
ADOVBS Constants<br />
'---- BookmarkEnum Values ----<br />
Const adBookmarkCurrent = 0<br />
Const adBookmarkFirst = 1<br />
Const adBookmarkLast = 2<br />
'---- MarshalOptionsEnum Values ----<br />
Const adMarshalAll = 0<br />
Const adMarshalModifiedOnly = 1<br />
'---- AffectEnum Values ----<br />
Const adAffectCurrent = 1<br />
Const adAffectGroup = 2<br />
Const adAffectAllChapters = 4<br />
'---- ResyncEnum Values ----<br />
Const adResyncUnderlyingValues = 1<br />
Const adResyncAllValues = 2<br />
'---- CompareEnum Values ----<br />
Const adCompareLessThan = 0<br />
Const adCompareEqual = 1<br />
Const adCompareGreaterThan = 2<br />
Const adCompareNotEqual = 3<br />
Const adCompareNotComparable = 4<br />
'---- FilterGroupEnum Values ----<br />
Const adFilterNone = 0<br />
Const adFilterPendingRecords = 1<br />
Const adFilterAffectedRecords = 2<br />
Const adFilterFetchedRecords = 3<br />
Const adFilterConflictingRecords = 5<br />
'---- SearchDirectionEnum Values ----<br />
Const adSearchForward = 1<br />
Const adSearchBackward = -1<br />
'---- PersistFormatEnum Values ----<br />
Const adPersistADTG = 0<br />
Const adPersistXML = 1<br />
'---- StringFormatEnum Values ----<br />
Const adClipString = 2<br />
'---- ConnectPromptEnum Values ----<br />
Const adPromptAlways = 1<br />
Const adPromptComplete = 2<br />
Const adPromptCompleteRequired = 3<br />
Const adPromptNever = 4<br />
29–40 InduSoft Web Studio
ADOVBS Constants<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
'---- ConnectModeEnum Values ----<br />
Const adModeUnknown = 0<br />
Const adModeRead = 1<br />
Const adModeWrite = 2<br />
Const adModeReadWrite = 3<br />
Const adModeShareDenyRead = 4<br />
Const adModeShareDenyWrite = 8<br />
Const adModeShareExclusive = &HC<br />
Const adModeShareDenyNone = &H10<br />
Const adModeRecursive = &H400000<br />
'---- RecordCreateOptionsEnum Values ----<br />
Const adCreateCollection = &H00002000<br />
Const adCreateStructDoc = &H80000000<br />
Const adCreateNonCollection = &H00000000<br />
Const adOpenIfExists = &H02000000<br />
Const adCreateOverwrite = &H04000000<br />
Const adFailIfNotExists = -1<br />
'---- RecordOpenOptionsEnum Values ----<br />
Const adOpenRecordUnspecified = -1<br />
Const adOpenOutput = &H00800000<br />
Const adOpenAsync = &H00001000<br />
Const adDelayFetchStream = &H00004000<br />
Const adDelayFetchFields = &H00008000<br />
Const adOpenExecuteCommand = &H00010000<br />
'---- IsolationLevelEnum Values ----<br />
Const adXactUnspecified = &Hffffffff<br />
Const adXactChaos = &H00000010<br />
Const adXactReadUncommitted = &H00000100<br />
Const adXactBrowse = &H00000100<br />
Const adXactCursorStability = &H00001000<br />
Const adXactReadCommitted = &H00001000<br />
Const adXactRepeatableRead = &H00010000<br />
Const adXactSerializable = &H00100000<br />
Const adXactIsolated = &H00100000<br />
'---- XactAttributeEnum Values ----<br />
Const adXactCommitRetaining = &H00020000<br />
Const adXactAbortRetaining = &H00040000<br />
'---- PropertyAttributesEnum Values ----<br />
Const adPropNotSupported = &H0000<br />
Const adPropRequired = &H0001<br />
Const adPropOptional = &H0002<br />
Const adPropRead = &H0200<br />
Const adPropWrite = &H0400<br />
InduSoft Web Studio 29–41
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
ADOVBS Constants<br />
'---- ErrorValueEnum Values ----<br />
Const adErrProviderFailed = &Hbb8<br />
Const adErrInvalidArgument = &Hbb9<br />
Const adErrOpeningFile = &Hbba<br />
Const adErrReadFile = &Hbbb<br />
Const adErrWriteFile = &Hbbc<br />
Const adErrNoCurrentRecord = &Hbcd<br />
Const adErrIllegalOperation = &Hc93<br />
Const adErrCantChangeProvider = &Hc94<br />
Const adErrInTransaction = &Hcae<br />
Const adErrFeatureNotAvailable = &Hcb3<br />
Const adErrItemNotFound = &Hcc1<br />
Const adErrObjectInCollection = &Hd27<br />
Const adErrObjectNotSet = &Hd5c<br />
Const adErrDataConversion = &Hd5d<br />
Const adErrObjectClosed = &He78<br />
Const adErrObjectOpen = &He79<br />
Const adErrProviderNotFound = &He7a<br />
Const adErrBoundToCommand = &He7b<br />
Const adErrInvalidParamInfo = &He7c<br />
Const adErrInvalidConnection = &He7d<br />
Const adErrNotReentrant = &He7e<br />
Const adErrStillExecuting = &He7f<br />
Const adErrOperationCancelled = &He80<br />
Const adErrStillConnecting = &He81<br />
Const adErrInvalidTransaction = &He82<br />
Const adErrUnsafeOperation = &He84<br />
Const adwrnSecurityDialog = &He85<br />
Const adwrnSecurityDialogHeader = &He86<br />
Const adErrIntegrityViolation = &He87<br />
Const adErrPermissionDenied = &He88<br />
Const adErrDataOverflow = &He89<br />
Const adErrSchemaViolation = &He8a<br />
Const adErrSignMismatch = &He8b<br />
Const adErrCantConvertvalue = &He8c<br />
Const adErrCantCreate = &He8d<br />
Const adErrColumnNotOnThisRow = &He8e<br />
Const adErrURLIntegrViolSetColumns = &He8f<br />
Const adErrURLDoesNotExist = &He8f<br />
Const adErrTreePermissionDenied = &He90<br />
Const adErrInvalidURL = &He91<br />
Const adErrResourceLocked = &He92<br />
Const adErrResourceExists = &He93<br />
Const adErrCannotComplete = &He94<br />
Const adErrVolumeNotFound = &He95<br />
Const adErrOutOfSpace = &He96<br />
Const adErrResourceOutOfScope = &He97<br />
Const adErrUnavailable = &He98<br />
Const adErrURLNamedRowDoesNotExist = &He99<br />
Const adErrDelResOutOfScope = &He9a<br />
Const adErrPropInvalidColumn = &He9b<br />
Const adErrPropInvalidOption = &He9c<br />
Const adErrPropInvalidValue = &He9d<br />
Const adErrPropConflicting = &He9e<br />
29–42 InduSoft Web Studio
ADOVBS Constants<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Const adErrPropNotAllSettable = &He9f<br />
Const adErrPropNotSet = &Hea0<br />
Const adErrPropNotSettable = &Hea1<br />
Const adErrPropNotSupported = &Hea2<br />
Const adErrCatalogNotSet = &Hea3<br />
Const adErrCantChangeConnection = &Hea4<br />
Const adErrFieldsUpdateFailed = &Hea5<br />
Const adErrDenyNotSupported = &Hea6<br />
Const adErrDenyTypeNotSupported = &Hea7<br />
Const adErrProviderNotSpecified = &Hea9<br />
Const adErrConnectionStringTooLong = &Heaa<br />
'---- ParameterAttributesEnum Values ----<br />
Const adParamSigned = &H0010<br />
Const adParamNullable = &H0040<br />
Const adParamLong = &H0080<br />
'---- ParameterDirectionEnum Values ----<br />
Const adParamUnknown = &H0000<br />
Const adParamInput = &H0001<br />
Const adParamOutput = &H0002<br />
Const adParamInputOutput = &H0003<br />
Const adParamReturnValue = &H0004<br />
'---- CommandTypeEnum Values ----<br />
Const adCmdUnknown = &H0008<br />
Const adCmdText = &H0001<br />
Const adCmdTable = &H0002<br />
Const adCmdStoredProc = &H0004<br />
Const adCmdFile = &H0100<br />
Const adCmdTableDirect = &H0200<br />
'---- EventStatusEnum Values ----<br />
Const adStatusOK = &H0000001<br />
Const adStatusErrorsOccurred = &H0000002<br />
Const adStatusCantDeny = &H0000003<br />
Const adStatusCancel = &H0000004<br />
Const adStatusUnwantedEvent = &H0000005<br />
InduSoft Web Studio 29–43
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
ADOVBS Constants<br />
'---- EventReasonEnum Values ----<br />
Const adRsnAddNew = 1<br />
Const adRsnDelete = 2<br />
Const adRsnUpdate = 3<br />
Const adRsnUndoUpdate = 4<br />
Const adRsnUndoAddNew = 5<br />
Const adRsnUndoDelete = 6<br />
Const adRsnRequery = 7<br />
Const adRsnResynch = 8<br />
Const adRsnClose = 9<br />
Const adRsnMove = 10<br />
Const adRsnFirstChange = 11<br />
Const adRsnMoveFirst = 12<br />
Const adRsnMoveNext = 13<br />
Const adRsnMovePrevious = 14<br />
Const adRsnMoveLast = 15<br />
'---- SchemaEnum Values ----<br />
Const adSchemaProviderSpecific = -1<br />
Const adSchemaAsserts = 0<br />
Const adSchemaCatalogs = 1<br />
Const adSchemaCharacterSets = 2<br />
Const adSchemaCollations = 3<br />
Const adSchemaColumns = 4<br />
Const adSchemaCheckConstraints = 5<br />
Const adSchemaConstraintColumnUsage = 6<br />
Const adSchemaConstraintTableUsage = 7<br />
Const adSchemaKeyColumnUsage = 8<br />
Const adSchemaReferentialConstraints = 9<br />
Const adSchemaTableConstraints = 10<br />
Const adSchemaColumnsDomainUsage = 11<br />
Const adSchemaIndexes = 12<br />
Const adSchemaColumnPrivileges = 13<br />
Const adSchemaTablePrivileges = 14<br />
Const adSchemaUsagePrivileges = 15<br />
Const adSchemaProcedures = 16<br />
Const adSchemaSchemata = 17<br />
Const adSchemaSQLLanguages = 18<br />
Const adSchemaStatistics = 19<br />
Const adSchemaTables = 20<br />
Const adSchemaTranslations = 21<br />
Const adSchemaProviderTypes = 22<br />
Const adSchemaViews = 23<br />
Const adSchemaViewColumnUsage = 24<br />
Const adSchemaViewTableUsage = 25<br />
Const adSchemaProcedureParameters = 26<br />
Const adSchemaForeignKeys = 27<br />
Const adSchemaPrimaryKeys = 28<br />
Const adSchemaProcedureColumns = 29<br />
Const adSchemaDBInfoKeywords = 30<br />
Const adSchemaDBInfoLiterals = 31<br />
Const adSchemaCubes = 32<br />
Const adSchemaDimensions = 33<br />
Const adSchemaHierarchies = 34<br />
29–44 InduSoft Web Studio
ADOVBS Constants<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Const adSchemaLevels = 35<br />
Const adSchemaMeasures = 36<br />
Const adSchemaProperties = 37<br />
Const adSchemaMembers = 38<br />
Const adSchemaTrustees = 39<br />
Const adSchemaFunctions = 40<br />
Const adSchemaActions = 41<br />
Const adSchemaCommands = 42<br />
Const adSchemaSets = 43<br />
'---- FieldStatusEnum Values ----<br />
Const adFieldOK = 0<br />
Const adFieldCantConvertValue = 2<br />
Const adFieldIsNull = 3<br />
Const adFieldTruncated = 4<br />
Const adFieldSignMismatch = 5<br />
Const adFieldDataOverflow = 6<br />
Const adFieldCantCreate = 7<br />
Const adFieldUnavailable = 8<br />
Const adFieldPermissionDenied = 9<br />
Const adFieldIntegrityViolation = 10<br />
Const adFieldSchemaViolation = 11<br />
Const adFieldBadStatus = 12<br />
Const adFieldDefault = 13<br />
Const adFieldIgnore = 15<br />
Const adFieldDoesNotExist = 16<br />
Const adFieldInvalidURL = 17<br />
Const adFieldResourceLocked = 18<br />
Const adFieldResourceExists = 19<br />
Const adFieldCannotComplete = 20<br />
Const adFieldVolumeNotFound = 21<br />
Const adFieldOutOfSpace = 22<br />
Const adFieldCannotDeleteSource = 23<br />
Const adFieldReadOnly = 24<br />
Const adFieldResourceOutOfScope = 25<br />
Const adFieldAlreadyExists = 26<br />
Const adFieldPendingInsert = &H10000<br />
Const adFieldPendingDelete = &H20000<br />
Const adFieldPendingChange = &H40000<br />
Const adFieldPendingUnknown = &H80000<br />
Const adFieldPendingUnknownDelete = &H100000<br />
'---- SeekEnum Values ----<br />
Const adSeekFirstEQ = &H1<br />
Const adSeekLastEQ = &H2<br />
Const adSeekAfterEQ = &H4<br />
Const adSeekAfter = &H8<br />
Const adSeekBeforeEQ = &H10<br />
Const adSeekBefore = &H20<br />
InduSoft Web Studio 29–45
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
ADOVBS Constants<br />
'---- ADCPROP_UPDATECRITERIA_ENUM Values ----<br />
Const adCriteriaKey = 0<br />
Const adCriteriaAllCols = 1<br />
Const adCriteriaUpdCols = 2<br />
Const adCriteriaTimeStamp = 3<br />
'---- ADCPROP_ASYNCTHREADPRIORITY_ENUM Values ----<br />
Const adPriorityLowest = 1<br />
Const adPriorityBelowNormal = 2<br />
Const adPriorityNormal = 3<br />
Const adPriorityAboveNormal = 4<br />
Const adPriorityHighest = 5<br />
'---- ADCPROP_AUTORECALC_ENUM Values ----<br />
Const adRecalcUpFront = 0<br />
Const adRecalcAlways = 1<br />
'---- ADCPROP_UPDATERESYNC_ENUM Values ----<br />
Const adResyncNone = 0<br />
Const adResyncAutoIncrement = 1<br />
Const adResyncConflicts = 2<br />
Const adResyncUpdates = 4<br />
Const adResyncInserts = 8<br />
Const adResyncAll = 15<br />
'---- MoveRecordOptionsEnum Values ----<br />
Const adMoveUnspecified = -1<br />
Const adMoveOverWrite = 1<br />
Const adMoveDontUpdateLinks = 2<br />
Const adMoveAllowEmulation = 4<br />
'---- CopyRecordOptionsEnum Values ----<br />
Const adCopyUnspecified = -1<br />
Const adCopyOverWrite = 1<br />
Const adCopyAllowEmulation = 4<br />
Const adCopyNonRecursive = 2<br />
'---- StreamTypeEnum Values ----<br />
Const adTypeBinary = 1<br />
Const adTypeText = 2<br />
'---- LineSeparatorEnum Values ----<br />
Const adLF = 10<br />
Const adCR = 13<br />
Const adCRLF = -1<br />
'---- StreamOpenOptionsEnum Values ----<br />
Const adOpenStreamUnspecified = -1<br />
Const adOpenStreamAsync = 1<br />
Const adOpenStreamFromRecord = 4<br />
29–46 InduSoft Web Studio
ADOVBS Constants<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
'---- StreamWriteEnum Values ----<br />
Const adWriteChar = 0<br />
Const adWriteLine = 1<br />
'---- SaveOptionsEnum Values ----<br />
Const adSaveCreateNotExist = 1<br />
Const adSaveCreateOverWrite = 2<br />
'---- FieldEnum Values ----<br />
Const adDefaultStream = -1<br />
Const adRecordURL = -2<br />
'---- StreamReadEnum Values ----<br />
Const adReadAll = -1<br />
Const adReadLine = -2<br />
'---- RecordTypeEnum Values ----<br />
Const adSimpleRecord = 0<br />
Const adCollectionRecord = 1<br />
Const adStructDoc = 2<br />
InduSoft Web Studio 29–47
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Using ADO with VBScript<br />
Exercise: Using ADO with VBScript<br />
This Exercise will read data from an Access Database where Trend data is stored. It will read up to 10 records<br />
and display the results. To use this exercise, you must first have the Trend001 Worksheet configured to store<br />
data into a Microsoft Access Database (MyDB.mdb) located in the Application Folder, storing into the Table<br />
Trend001.<br />
Open the ADO.scr Screen<br />
Add a Button object, with the Caption Read From Trend Data<br />
Add a Command Dynamic Property, and select VBScript as the Type and add the following code:<br />
Dim database, strConn<br />
Dim db, rs, i, msg<br />
database = $GetAppPath() & "myDB.mdb"<br />
strConn = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source=" & database & ";"<br />
Set db = CreateObject("ADODB.Connection")<br />
db.open = strConn<br />
Set rs = CreateObject("ADODB.Recordset")<br />
Set rs = db.Execute("Select * FROM Trend001")<br />
msg = ""<br />
For i = 1 To 10<br />
If Not rs.EOF Then<br />
msg = msg & rs("Time_Stamp") & " "<br />
msg = msg & rs("tank_1_temperature") & " "<br />
msg = msg & rs("tank_2_temperature") & " "<br />
msg = msg & rs("tank_3_temperature") & " "<br />
msg = msg & vbCrLf<br />
rs.MoveNext<br />
End If<br />
Next<br />
MsgBox msg<br />
rs.close<br />
db.close<br />
Set rs = Nothing<br />
Set db = Nothing<br />
Save and Close the Screen<br />
29–48 InduSoft Web Studio
Exercise: Using ADOX to create an blank Access Database<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Using ADOX to create an blank Access Database<br />
This Exercise will add VBScript code to the Startup Script to create a blank Microsoft Access Database named<br />
myDB.mdb stored in the project application folder if the database does not exist. We will use this database to<br />
store data (e.g. from the Trend001 Worksheet) which will be configured to store data into the Table Trend001.<br />
Open the Startup Script from the Script folder in the Tasks tab of the Workspace<br />
Add the following code:<br />
Open the dialog box Project Settings Options Default Database Configure<br />
Put the following in the Connection String field<br />
Provider=Microsoft.Jet.OLEDB.4.0; Data Source= {your app path}\MyDB.mdb<br />
where {your app path} is the path to your application folder.<br />
Configure the Trend Worksheet(s) and Alarm/Events (via Project Settings Options Alarm and Event<br />
Database) to use the Relational Database<br />
InduSoft Web Studio 29–49
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Using ADOX to create an blank Access Database<br />
Notes<br />
29–50 InduSoft Web Studio
Chapter 30.<br />
Reading & Writing XML using VBScript<br />
XML (Extensible Markup Language) has become a commonly used language for transporting data in a crossplatform<br />
environment. It is a companion technology to HTML, but one does not replace the other. HTML is a<br />
standard used for displaying data (e.g. web pages) that has graphics and text, whereas XML is a standard used<br />
for structuring and transferring data. XML is a standard under the control of the World Wide Web Consortium<br />
(W3C), www.w3.org,<br />
In an InduSoft Web Studio (<strong>IWS</strong>) application, Recipes can be saved to or loaded from a file that is in XML<br />
format. These XML recipe files can be created in a separate computer and made available to the PC (or PCs)<br />
using the Recipe Manager.<br />
In addition to the Recipe Manager, <strong>IWS</strong> can create, read from, and write to XML files using VBScript. This is a<br />
powerful capability that can be utilized, for example, to transfer production data records (e.g. summary data,<br />
sample data) and reports from a PC running <strong>IWS</strong> to another PC or PDA that uses an XML Server.<br />
In this Chapter, we will cover two methods to create and manipulate XML files; ADO and the XMLDOM<br />
(Microsoft’s XML Parser). Using ADO is by far the simplest, and the XML file includes<br />
Note:<br />
• XML can be viewed by Microsoft Notepad, Wordpad or Word<br />
• Microsoft XML Notepad 2007 is available free of charge. It is found at www.microsoft.com in the<br />
Downloads section.<br />
Persisting Data in XML Format using ADO<br />
ADO provides the ability to persist in XML format both Recordset Objects and Stream Objects using the<br />
Microsoft OLE DB Persistence Provider. This Provider generates a forward-only, read-only rowset from a saved<br />
XML file or Stream that contains the schema information generated by ADO. Similarly, it can take an ADO<br />
Recordset, generate XML, and save it to a file or any object that implements the COM IStream interface. (A file<br />
is just another example of an object that supports IStream.) ADO uses the Microsoft XML Parser (MSXML) to<br />
load the XML into the Recordset; therefore msxml.dll is required.<br />
Once the Data is in XML format, XSLT (XML Style Sheet Language) can be used to transform the XML data<br />
into an HTML table.<br />
Note:<br />
• XSLT scripts can be used to transform XML into HTML Tables<br />
• Many higher-level databases such as SQL Server can store data in XML format.<br />
• A Recordset can be saved directly into the XML DOM object for further processing.<br />
InduSoft Web Studio 30–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Persisting Data in XML Format using ADO<br />
The following example uses persists an ADO Recordset using adPersistXML<br />
Const adPersistXML = 1<br />
Const adVarChar = 200<br />
Const MaxCharacters = 70<br />
Const adFldIsNullable = 32<br />
Dim fso, XMLRS, i<br />
' Delete any existing XML file<br />
Set fso = CreateObject("Scripting.FileSystemObject")<br />
If fso.fileexists($myXMLFile) Then<br />
fso.deletefile $myXMLFile<br />
End If<br />
' Write to the XML file<br />
Set XMLRS = CreateObject("ADODB.Recordset")<br />
XMLRS.Fields.Append "Line", adVarChar, MaxCharacters, adFldIsNullable<br />
XMLRS.Fields.Append "Machine", adVarChar, MaxCharacters, adFldIsNullable<br />
XMLRS.Fields.Append "Alarms", adVarChar, MaxCharacters, adFldIsNullable<br />
XMLRS.Fields.Append "Output", adVarChar, MaxCharacters, adFldIsNullable<br />
XMLRS.Open<br />
For i = 0 To 3<br />
XMLRS.AddNew<br />
XMLRS("Line") = $eData[i].Line<br />
XMLRS("Machine") = $eData[i].Machine<br />
XMLRS("Alarms") = $eData[i].Alarms<br />
XMLRS("Output") = $eData[i].Output<br />
Next<br />
XMLRS.Update<br />
XMLRS.Sort = "Line"<br />
XMLRS.Save $myXMLFile, adPersistXML<br />
XMLRS.Close<br />
Set XMLRS = Nothing<br />
Set fso = Nothing<br />
The following example saves a ADO Recordset to the XML DOM Object<br />
Dim oConn, oRS, oXMLDOM, stm, StrRst<br />
Const adPersistADO =1<br />
Set oConn = CreateObject("ADODB.Connection")<br />
Set oRS = CreateObject("ADODB.Recordset")<br />
Set oXMLDOM = CreateObject(“MSXML.DOMDocument)<br />
oConn.Provider = "Microsoft.Jet.OLEDB.4.0"<br />
oConn.Properties("Data Source").value = $GetAppPath()& "MachineInfo.mdb"<br />
oConn.Open<br />
Set oRS = oConn.Execute ("Select * From Table1")<br />
oRS.Save oXMLDOM, adPersistADO<br />
Notes:<br />
• adPersistADO indicates that ADO’s own Extensible Markup language format (XML) will be<br />
used.<br />
• The XMLDOM can be used to add additional XML.<br />
30–2 InduSoft Web Studio
Using the XMLDOM<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
The ADO Stream Object, as previously shown, provides the means to read, write, and manage a stream of<br />
bytes. This byte stream may be text or binary and is limited in size only by system resources. Typically, ADO<br />
Stream objects are used to contain the data of a Recordset saved in XML format<br />
This Example saves a Recordset to a file and then to a Stream. It then opens the persisted stream into<br />
another Recordset.<br />
Dim con, rs1, rs2, stm, StrRst<br />
Const adPersistXML =1<br />
Set con = CreateObject("ADODB.Connection")<br />
Set rs1 = CreateObject("ADODB.Recordset")<br />
Set rs2 = CreateObject("ADODB.Recordset")<br />
Set stm = CreateObject("ADODB.Stream")<br />
con.Provider = "Microsoft.Jet.OLEDB.4.0"<br />
con.Properties("Data Source").value = $GetAppPath()& "MachineInfo.mdb"<br />
con.Open<br />
Set rs1 = con.Execute ("Select * From Table1")<br />
rs1.Save $GetAppPath()& "MachineInfo.xml", adPersistXML<br />
rs1.Save stm, adPersistXML<br />
rs2.Open stm<br />
This Example persists a Recordset into a Stream in XML format. It then reads the Stream into a string that you<br />
can examine, manipulate, or display.<br />
Dim con, rs, stm, StrRst<br />
Const adReadAll = -1<br />
Const adPersistXML =1<br />
Set con = CreateObject("ADODB.Connection")<br />
Set rs = CreateObject("ADODB.Recordset")<br />
Set stm = CreateObject("ADODB.Stream")<br />
con.Provider = "Microsoft.Jet.OLEDB.4.0"<br />
con.Properties("Data Source").value = $GetAppPath()& "MachineInfo.mdb"<br />
con.Open<br />
Set rs = con.Execute ("Select * From Table1")<br />
rs.Save stm, adPersistXML<br />
strRst = stm.ReadText (adReadAll)<br />
'Display the XML data.<br />
MsgBox strRst<br />
Using the XMLDOM<br />
Please refer to Application Note AN-00-0004<br />
InduSoft Web Studio 30–3
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Using the XMLDOM<br />
Notes<br />
30–4 InduSoft Web Studio
Chapter 31.<br />
ActiveX Controls and .NET Assemblies<br />
ActiveX Overview<br />
ActiveX is a loosely defined set of Microsoft technologies developed for common program execution and the<br />
sharing of information between two or more applications that run on a Microsoft Windows OS. ActiveX is the<br />
outgrowth of other Microsoft technologies such as OLE (Object Linking and Embedding) and COM (Component<br />
Object Model).<br />
When most people refer to ActiveX, they are referring to ActiveX Controls which are modular programs<br />
designed to execute at the system level in conjunction with an application. ActiveX has a set of rules on how<br />
applications should share information. The power of ActiveX comes from the ability of an ActiveX Control to<br />
have full access to the underlying Windows Operating System. ActiveX Controls must be registered with the<br />
Windows System Registry prior to their use.<br />
<strong>IWS</strong> is a Container for ActiveX Controls. This means that 3 rd party Controls can be added to an <strong>IWS</strong> application,<br />
and <strong>IWS</strong> will have access to their various Properties, Methods and Events.<br />
Installing an ActiveX Control<br />
An ActiveX Control is typically a file with an .OCX (or .DLL) file extension. A single .OCX DLL can contain any<br />
number of ActiveX Controls. The .OCX or .DLL file is generally copied during the installation process of the<br />
ActiveX control, and the location where the file is installed is not important. However, the ActiveX Control must<br />
be registered with the Windows System Registry. This is done using one of a few methods:<br />
• The ActiveX Control is registered during the installation process (this is generally the case)<br />
• Run the Regsvr32 command using the Windows Command Line processor (e.g. Start Run CMD<br />
Regsvr32 file)<br />
• Use the <strong>IWS</strong> Register Controls Tool (from the Main Menu Bar, Tools Register Controls)<br />
• Use another ActiveX Registration Tool (there are several available)<br />
Note:<br />
• If you use an ActiveX Control in an application, you may need to seperately install the ActiveX Control in<br />
the Web Thin Client.<br />
Inserting an ActiveX Control<br />
An ActiveX Control can be used with an <strong>IWS</strong> application by either:<br />
• Using the <strong>IWS</strong> OCX Tool (located in the Active Objects Toolbar) to select and insert an<br />
ActiveX Control onto an Application Screen<br />
• Instantiating an ActiveX Control from VBScript using the CreateObject statement<br />
In order for an ActiveX Control to be viewable on an<br />
Application Screen, it must be inserted using the OCX<br />
Tool. Once the OCX tool is activated, an Insert ActiveX<br />
Control dialog box will appear, allowing you to select the<br />
ActiveX Control that you want to insert on the Screen.<br />
Once the ActiveX Control is inserted on the Application<br />
Screen, the graphical interface object can be selected<br />
and repositioned on the Display Screen. Certain Dynamic<br />
Properties (e.g. Command Dynamic, Position (including<br />
visibility), and Size) can be added to the ActiveX Control.<br />
By double-clicking on the ActiveX object, you can access<br />
its Object Properties. For example, the Microsoft Slider<br />
InduSoft Web Studio 31–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Using the XMLDOM<br />
ActiveX Control (as shown) will have a Object<br />
Properties dialog box as show. The Name of the<br />
Object will have a numeric (integer) value behind it<br />
that changes for each time the ActiveX Control is<br />
used in the Application. This Name can be changed,<br />
but it must be unique within the Application.<br />
The Property Pages button provides access to<br />
settings that change the “look and feel” of the ActiveX<br />
Control. The Configuration button provides access<br />
to the ActiveX Control’s Properties, Methods and<br />
Events.<br />
Once the ActiveX Control is inserted onto an Application Screen, its Properties, Methods and Events can be<br />
accessed from the Object Properties dialog box, and the ActiveX Control’s Properties and Methods can be<br />
accessed from VBScript code in either the Screen Script or in a Command Dynamic associated with an <strong>IWS</strong><br />
object placed on the same Application Screen.<br />
If the ActiveX Control is instantiated using the CreateObject statement from VBScript, it will not be visible on an<br />
Application Screen and can only be used from the VBScript code segment that created it.<br />
ActiveX Properties, Methods and Events<br />
ActiveX Controls can have Properties, Methods and Events. Each of these serves a different purpose.<br />
• Properties<br />
Properties are attributes or characteristics of an ActiveX Control. . ActiveX Controls are not required to<br />
have Properties or expose them to the User Interface, although most ActiveX Controls do include<br />
Properties. Properties can be read only, write only, or read-write.<br />
• Methods<br />
Methods are specific functions that the ActiveX Control performs. ActiveX Controls are not required to<br />
have any Methods, or expose them to the User Interface, although most ActiveX Controls do include<br />
Methods..<br />
• Events<br />
Events are notifications generated by the ActiveX Control, based upon a specified Event (or action)<br />
occurring. ActiveX Controls are not required to have any Events, or expose them to the User Interface,<br />
although most ActiveX Controls do include Events. The ActiveX Control usually “fires” an event based<br />
upon a User action (e.g. click, double click, Error, etc.). The Configuration dialog box has the Events<br />
tab that allows selection of the type of event and what, if any, <strong>IWS</strong> Script or VBScript code should be<br />
executed when the Event “fires”.<br />
31–2 InduSoft Web Studio
Using the XMLDOM<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
From the Configuration dialog box (of the Object Properties) for the ActiveX Control, <strong>IWS</strong> Tags or Expressions<br />
can be used in the Tag/Expression field for the ActiveX Control’s Properties and Methods. Events have a<br />
Parameter field that allows for the triggering of an Event, and a Script field that can be used to define the Script<br />
(<strong>IWS</strong> Script of VBScript) to be executed when the specific Event “fires”.<br />
Notes:<br />
• In the Configuration dialog box, <strong>IWS</strong> Tags and Expressions can be entered in the Tag/Expression field<br />
for Properties and Methods.<br />
• In the Configuration dialog box, <strong>IWS</strong> Script or VBScript can be defined to execute when an Event “fires”<br />
• The ActiveX Object Name can be change in the Object Properties dialog box<br />
• From VBScript, an ActiveX Object inserted on an Application Screen can be used by referencing the<br />
Name of the ActiveX Object and the Property or Method.<br />
• ActiveX Events cannot be accessed from VBScript. You need to use the Configuration dialog box of the<br />
Object Properties<br />
• ActiveX Controls are identified by their Program ID (ProgID) or Class ID (CLSID)<br />
.NET Overview<br />
Microsoft’s .NET architecture is an outgrowth of Microsoft DNA (Distributed Network Architecture), developed to<br />
address network-based applications. The principle concept is that the .NET architecture erases the boundary<br />
between the application and the network. In principle, .NET connects the user to an array of computers and<br />
services that can exchange and combine objects and data. Thus, users will have access to information from<br />
any device, any time, any where using the Internet (or Intranet).<br />
The .NET architecture is built on the following technologies: HTTP (Hypertext Transfer Protocol, the underlying<br />
protocol for transfer of information over the World Wide Web), XML (Extensible Markup Language, a W3C or<br />
World Wide Web Consortium specification for how data is transmitted between applications in an operating<br />
system-independent and applications-independent method), SOAP (Simple Object Access Protocol, a light<br />
weight XML-based messaging protocol used information exchange between applications that are operating<br />
system-independent and applications-independent), and UDDI (Universal Description, Discovery and<br />
Integration, a web-based distributed directory that allows discovery of .NET applications).<br />
In the .NET Framework, a .NET Assembly is the .NET corollary to an ActiveX Control. C# or VB.NET code is<br />
compiled into an intermediate language known as the Common Intermediate Language (CIL). Microsoft’s CIL is<br />
also knows as Microsoft Intermediate Language (MSIL), and is a just-in-time compiled code. This MSIL code is<br />
housed in what is called a .NET Assembly, a portable executable file (.EXE or .DLL). An Assembly is a .NET<br />
unit of deployment, versioning, and security.<br />
Unlike ActiveX Controls, which after being registered have a Program ID and Class ID, .NET Assemblies are<br />
known by their Namespace, a unique identifier.<br />
<strong>IWS</strong> is a Container for .NET Assemblies. This means that 3rd party .NET Assemblies (also called .NET<br />
Controls) can be used in an <strong>IWS</strong> application, and that the <strong>IWS</strong> application will have access to the .NET<br />
Assembly’s Properties, Methods, and Events. The Microsoft .NET 2.0 Framework is required for WS to be a<br />
.NET container. The WS v.6.5 installation installs the .NET 2.0 Framework (updated from 1.1)<br />
InduSoft Web Studio 31–3
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Using the XMLDOM<br />
Installing a .NET Assembly<br />
Unlike ActiveX Controls which can be installed into any folder but need to be registered with the System<br />
Registry, a .NET Assembly must be installed into one of two specific folders but does not need to be registered<br />
with the System Registry. So where does a .NET Assembly go The answer is that it needs to go into one of<br />
two places. The first is the GAC, or Global Assembly Cache. With Windows XP Pro, this can be found in<br />
C:\Windows\Assembly. The second place it can go is into the <strong>IWS</strong> Application folder.<br />
Inserting a .NET Assembly<br />
A .NET Assembly can be inserted onto an <strong>IWS</strong> Application Screen by clicking on the .NET Tool icon<br />
found in the Active Objects Toolbar. A .NET Framework Components dialog box will open, and a<br />
list of .NET Assemblies will appear. Select the Assembly of interest and press OK.<br />
The .NET Assembly graphical interface will now appear on the <strong>IWS</strong> Application Screen. You can double click on<br />
the .NET Assembly to access the Object Properties dialog box, providing access to the Property Pages and the<br />
Members dialog box (provides access to Properties, Methods and Events). As with the ActiveX Control(s), you<br />
can change the name of the .NET Assembly as it is referenced from <strong>IWS</strong> by changing the name in the Name<br />
field.<br />
31–4 InduSoft Web Studio
Using the XMLDOM<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Key differences between ActiveX and .NET Assemblies<br />
• .NET Assemblies don’t have to be registered but… they must be located in GAC (Global Assembly<br />
Cache) or in the Application Folder. Some commentators advise to keep GAC as clean as possible, so<br />
put .NET controls in application folder.<br />
• ActiveX Properties, Methods and Events can be accessed by VBScript. Currently, the Properties,<br />
Methods and Events for .NET Assemblies can only be configured on an <strong>IWS</strong> Screen and the<br />
Tag/Expression field used. VBScript is not an option since VBScript is not a .NET language.<br />
InduSoft Web Studio 31–5
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Inserting an ActiveX Control<br />
Exercise: Inserting an ActiveX Control<br />
In this exercise, we will insert an ActiveX control onto a Screen and read one of its Properties using VBScript.<br />
Open the ActiveX.scr Screen (or create it)<br />
Click on the ActiveX Tool in the Active Objects Toolbar<br />
In the Insert ActiveX Control dialog box, locate the ActiveX control Microsoft Slider Control 6.0 and click<br />
on it to select it.<br />
Click the OK button to insert this Control on to the Screen<br />
Double click on the Slider ActiveX Control (or right mouse click) and when the Object Properties dialog box<br />
opens, change its name to Slider1. Close the Object Properties dialog box.<br />
Move your mouse cursor to a blank area of the Screen and click the right mouse button<br />
Select the Screen Script option.<br />
Insert the VBScript code as shown:<br />
Save and Close the Screen Script. Specify v6 to be an Integer Tag.<br />
31–6 InduSoft Web Studio
Exercise: Inserting an ActiveX Control<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
On the ActiveX.scr Screen, insert a Text Object with the caption Slider value = ####, add a Text I/O<br />
Property with the Tag set to v6.<br />
Save and Close the ActiveX.scr Screen<br />
InduSoft Web Studio 31–7
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
System.Collections<br />
System.Collections<br />
While the general rule is VBScript does not have access to the .NET Framework Classes (i.e. doesn’t support<br />
.NET Assemblies), there are some .NET Classes that have COM-callable wrappers.<br />
One example of these .NET Classes are the System.Collections provided by Microsoft. The Namespace for this<br />
Class is System.Collections and is included in the Mscorlib Assembly (mscorlib.dll). The System.Collections<br />
Class is available for most Windows Platforms including Windows XP, Server 2003, Vista (with .NET 3.0) and<br />
Windows CE (with .NET Compact Framework 1.0 or 2.0).<br />
The System.Collections Class supports certain functions that can be quite useful, depending on your<br />
application. These functions include:<br />
ArrayList<br />
Queue<br />
Stack<br />
HashTable<br />
SortedList<br />
ArrayList<br />
The ArrayList can be useful for creating, copying and sorting an Array.<br />
Methods<br />
Add<br />
AddRange<br />
Clear<br />
Clone<br />
Contains<br />
CopyTo (Array)<br />
CopyTo (Array, Int32)<br />
Get Range<br />
Insert<br />
Insert Range<br />
Remove<br />
Remove At<br />
Remove Range<br />
Repeat<br />
Reverse<br />
Reverse (Int32, Int32)<br />
Estrange<br />
Sort<br />
To Array<br />
Adds an object to the end of the ArrayList. Value can be null (Nothing). Return<br />
value is the ArrayList index at which the value has been added.<br />
Adds the elements of a Collection to the end of the ArrayList Object. The order<br />
of the elements in the Collection is preserved in the ArrayList<br />
Removes all elements from the ArrayList. Count is set to zero, and references<br />
to other objects from elements of the Collection are released. Does not effect<br />
capacity. Not supported when ArrayList is read-only or fixed size.<br />
Creates a shallow copy of the ArrayList (i.e. contains elements of the collection<br />
but does not copy objects referenced)<br />
Determines whether an element is in the ArrayList. Returns true if found,<br />
otherwise false. Performs a linear search<br />
Copies the entire ArrayList to a compatible one-dimensional array, starting at<br />
the beginning index<br />
Copies the entire ArrayList to a compatible one-dimensional Array, starting at<br />
the specified index of the target array.<br />
Returns an ArrayList which represents a subset of the elements in the source<br />
ArrayList<br />
Inserts an element into the ArrayList at a specified index<br />
Inserts elements of a collection into an ArrayList at the specified index<br />
Removes the first occurrence of the specified object<br />
Removes the element at the specified index<br />
Removes a range of elements from the ArrayList<br />
Creates a new ArrayList whose elements are copies of the specified value<br />
Reverses the order of the elements of the entire ArrayList<br />
Reverses the order of the elements in the specified range<br />
Copies the elements of a collection over a range of elements in the ArrayList<br />
Sorts the elements in the entire ArrayList<br />
Copies the elements of the ArrayList to a new Array<br />
31–8 InduSoft Web Studio
System.Collections<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Properties<br />
Capacity<br />
Count<br />
IsFixedSize<br />
IsReadOnly<br />
IsSynchronized<br />
Item<br />
SyncRoot<br />
Gets or sets the number of elements that ArrayList can contain<br />
Gets the number of elements actually contained in the ArrayList<br />
Gets a boolean value indicating whether the ArrayList has a fixed size (true<br />
(default) if fixed size, otherwise false)<br />
Gets a boolean value indicating whether the ArrayList is read-only (true if read<br />
only, otherwise false (default))<br />
Gets a boolean value indicating whether access to the ArrayList is synchronized<br />
(thread safe)<br />
Gets or sets the element at the specified index<br />
Gets an Object that can be used to synchronize access to the ArrayList<br />
Example VBScript<br />
' Create an empty ArrayList, and add some elements.<br />
Dim myAL, i, msg<br />
Set myAL=CreateObject("System.Collections.Arraylist")<br />
myAL.Add("a")<br />
myAL.Add("abc")<br />
myAL.Add("abcdef")<br />
myAL.Add("abcdefg")<br />
myAL.Insert 0, "xyz"<br />
myAL.Insert 1, "uvwxyz"<br />
msg = "Number of elements in the list is " & myAL.Count & vbCrLf<br />
For i = 0 To myAL.count-1<br />
msg = msg & "Element " & i & " Is " & myAL(i) & vbCrLf<br />
Next<br />
MsgBox msg<br />
InduSoft Web Studio 31–9
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
System.Collections<br />
Queue<br />
A Queue is a first-in, first-out collection of Objects and can be useful for storing messages in the order they<br />
were received for sequential processing of the messages. Queue elements can be null values.<br />
Methods<br />
Clear<br />
Contains<br />
CopyTo<br />
Dequeue<br />
Enqueue<br />
Equals<br />
GetEnumerator<br />
ToArray<br />
Removes all objects from the Queue.<br />
Determines whether an element is in the Queue<br />
Copies the Queue elements to an existing one-dimensional Array, starting at the<br />
specified array index<br />
Removes and returns the object at the beginning of the Queue.<br />
Adds an object to the end of the Queue.<br />
Overloaded. Determines whether two Object instances are equal. (inherited from<br />
Object)<br />
Returns an enumerator that iterates through the Queue.<br />
Copies the Queue elements to a new Array<br />
Properties<br />
Count<br />
Gets the number of elements contained in the Queue.<br />
VBScript Example<br />
Dim myQueue, msg<br />
Set myQueue=CreateObject("System.Collections.Queue")<br />
myQueue.Enqueue("one")<br />
myQueue.Enqueue("two")<br />
myQueue.Enqueue("three")<br />
myQueue.Enqueue("four")<br />
myQueue.Enqueue("five")<br />
Msg = "total entries = " & myQueue.count & vbCrLf<br />
Msg = msg & "Peek at first element in queue= " & myQueue.Peek() & vbCrLf<br />
msg = msg & "Deque first entry = " & myQueue.Dequeue() & vbCrLf<br />
msg = msg & "New count = " & myQueue.count & vbCrLf<br />
Msg = msg & "Peek at new first element in queue= " & myQueue.Peek() & vbCrLf<br />
MsgBox msg<br />
31–10 InduSoft Web Studio
System.Collections<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Stack<br />
A Stack is a last-in, first-out collection of Objects (compared to the Queue which is a first-in, first-out collection).<br />
Methods<br />
Clear<br />
Clone<br />
Contains<br />
CopyTo<br />
Equals<br />
GetHashCode<br />
GetType<br />
Peek<br />
Pop<br />
Push<br />
ReferenceEquals<br />
Synchronized<br />
ToArray<br />
ToString<br />
Removes all objects from the Stack.<br />
Creates a shallow copy of the Stack.<br />
Determines whether an element is in the Stack.<br />
Copies the Stack to an existing one-dimensional Array, starting at the specified array<br />
index.<br />
Overloaded. Determines whether two Object instances are equal. (inherited from<br />
Object)<br />
Serves as a hash function for a particular type. (inherited from Object)<br />
Gets the Type of the current instance. (inherited from Object)<br />
Returns the object at the top of the Stack without removing it.<br />
Removes and returns the object at the top of the Stack.<br />
Inserts an object at the top of the Stack.<br />
Determines whether the specified Object instances are the same instance. (inherited<br />
from Object)<br />
Returns a synchronized (thread safe) wrapper for the Stack.<br />
Copies the Stack to a new array.<br />
Returns a String that represents the current Object. (inherited from Object)<br />
Properties<br />
Count<br />
Gets the number of elements contained in the Queue.<br />
VBScript Example<br />
Dim stack<br />
Set stack=CreateObject("System.Collections.Stack")<br />
stack.Push("Hello")<br />
stack.Push("World")<br />
MsgBox "Count = " & stack.count & " Top value = " & stack.Peek<br />
stack.Pop<br />
MsgBox "Count after popping = " & stack.count<br />
InduSoft Web Studio 31–11
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
System.Collections<br />
Random<br />
The System.Random Class provides a pseudo-random generator. While VBScript provides a random number<br />
generator function, the System.Random Class is easier to use.<br />
Methods<br />
Random.Next<br />
Random.Next_2 (Int32, Int32)<br />
Randon.NextDouble<br />
Returns a nonnegative random number.<br />
Returns a random number within a specified range.<br />
Returns a random number between 0.0 and 1.0 (double-precision floating<br />
point)<br />
VBScript Example<br />
Set oRandom=CreateObject("System.Random")<br />
MsgBox oRandom.Next (1,100)<br />
31–12 InduSoft Web Studio
Chapter 32.<br />
Web Thin Clients<br />
<strong>IWS</strong> is built on a Client/Server architecture, and you can support both Thin Clients and Thick Client. The choice<br />
of the type of Client architecture depends upon your system requirements.<br />
Thin Client<br />
A Thin (Lean) Client is a computer that depends primarily on the central Server for processing activities.<br />
The Thin Client needs to have a processor with minimal memory, a browser (Internet Explorer) and a<br />
network connection (e.g. to the Internet or Intranet). InduSoft uses the terminology Web Client to refer to a<br />
Thin Client solution. <strong>IWS</strong> lets you choose the type of browser that is best for your runtime environment:<br />
• Microsoft Internet Explorer. This type of browser is best for desktop or remote access<br />
environments.<br />
• InduSoft’s Secure Viewer, a dedicated viewer for <strong>IWS</strong> applications. Secure Viewer does not let the<br />
user browse to other websites, and will only connect to a specified <strong>IWS</strong> Server. Secure Viewer is<br />
intended for plant floor environments were browsing to other web sites is not required or desired.<br />
Thick Client.<br />
A Thick (Fat) Client is a computer that performs most, if not all, of the processing activity. The Thick Client<br />
has sufficient processing power, memory, memory, graphics, etc. to run the application. The Thick Client<br />
can exchange data with the Server as required (e.g. archival of data, program synchronization). A Server<br />
can also be a Thick Client to another Server.<br />
In this chapter, we will explore using Web Thin Clients with <strong>IWS</strong>. Thick Clients will be covered in a subsequent<br />
chapter.<br />
Web Thin Clients in <strong>IWS</strong><br />
<strong>IWS</strong> allows you to create screens that can be visualized in a remote station a regular web browser (e.g. Internet<br />
Explorer). The station where the user can visualize the graphical interface (screens) on the web browser is<br />
called the Web Thin Client. The Thin Client (Browser) is the host.<br />
Typical Web Thin Client Architecture<br />
<strong>IWS</strong> is installed on the Server station only. Also, the application (screen files, tags database, configuration<br />
worksheets, etc.) is stored on the Server only. You do not need to install <strong>IWS</strong> or the application on the Web<br />
Thin Client. This solution provides a high level of flexibility because any computer physically linked to the Server<br />
station (via a TCP/IP link) can access the graphical screen and online/history data from the Server without<br />
installing <strong>IWS</strong> or the application on the Web Thin Client stations.<br />
InduSoft Web Studio 32–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
System.Collections<br />
All background tasks (Math, Scheduler etc) and communication tasks (e.g. Driver, OPC, DDE TCP/IP) are<br />
executed only on the Server station. The Web Thin Client is able to load the graphical interface configured on<br />
the Server (screens with objects and dynamics) and display the online values from the tags configured in the<br />
server, as well as history data (Alarm, Events and Trend history data).<br />
Note:<br />
• Since VBScript and the <strong>IWS</strong> Scripting Language can be associated with a screen as well as a Command<br />
Dynamic for an Object, these Scripts can execute on a Web Thin Client.<br />
Any computer or device (e.g. a PDA powered with Windows CE) running Microsoft Internet Explorer 6.0 (or<br />
higher) browser or InduSoft’s Secure Viewer browser can be a Web Thin Client for an <strong>IWS</strong> application.<br />
Moreover, <strong>IWS</strong> provides a sophisticated Security System to prohibit unauthorized access to the application<br />
From the Web Thin Client, you are able to visualize data from the Server and capable of changing set points,<br />
acknowledging alarms and/or sending commands to the Server. When configuring the application, you can<br />
optionally enable or disable all commands from the Web Thin Client to the Server. Even if the Server has<br />
disabled all command from the Web Thin Client, the Web Thin Client can still read data from the Server but<br />
cannot send any data to the Server.<br />
InduSoft Web Thin Client Competitive Advantages<br />
InduSoft is built on a Client/Server architecture that supports true Web Thin Clients. This capability is built-in to<br />
<strong>IWS</strong> and is not an add-on. This means that:<br />
• The <strong>IWS</strong> Server supports a large number of concurrent Thin Clients (up to 128 IE-based and 128<br />
Secure Viewer-based). Each Web Thin Client can view the same or different screens as another Web<br />
Thin Client.<br />
• The <strong>IWS</strong> Server knows which display each Web Thin Client viewing and automatically “pushes” any<br />
updated Tag values to the Web Thin Client, keeping the Thin Client display current and eliminating the<br />
need for screen refreshes<br />
• The <strong>IWS</strong> Server can support runtime language switching for each Web Thin Client. This means that<br />
one Web Thin Client can be viewing a screen in English while another Web Thin Client can display the<br />
same screen in Spanish.<br />
Many competitive products offer either a static display on a Thin Client (i.e. it must be manually “refreshed” to<br />
get the latest data), a Terminal Server solution (requires the Server to build multiple instances of the application<br />
to support each Thin Client), or offer a Thin Client solution similar to <strong>IWS</strong> but with expensive “add-on” software<br />
products.<br />
Other InduSoft Web Thin Client advantages include:<br />
• Optional Secure Viewer that does not allow navigation outside the <strong>IWS</strong> application. Secure Viewer is<br />
not based on Microsoft’s Internet Explorer.<br />
• Ability to run VBScript and <strong>IWS</strong> Scripting Language on the Web Thin Client<br />
• Can build Web Thin Client applications using Windows CE devices as the Server.<br />
• Ability to support redundant Web Servers and Data Servers, with automatic switchover.<br />
InduSoft Web Thin Client Licensing<br />
The maximum number of Web Thin Client stations connected simultaneously to the Server depends on the<br />
settings of the license installed on the Server. The user does not have to install any license on the Web Thin<br />
Client.<br />
32–2 InduSoft Web Studio
Building a Simple Web Thin Client Application Step by Step<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Building a Simple Web Thin Client Application Step by Step<br />
As we will see shortly, there is no one way to build a Web Thin Client application. The following procedures<br />
allow you to develop a simple, unsecured Web Thin Client application.<br />
Procedure A: Web Thin Client using NTWebServer, Local Loopback<br />
An easy way to initially develop and test a Web Thin Client application is to use the InduSoft light-weight Web<br />
Server NTWebServer on your development PC, initiate the application runtime and use Microsoft Internet<br />
Explorer on the same PC to display the Web pages.<br />
Step 1: Configure <strong>IWS</strong> Settings<br />
• In the Development Environment, select Project <br />
Settings Web (tab).<br />
- In the Data Server IP Address field, enter 127.0.0.1<br />
- Check the Auto Screen Scaling, Enable File<br />
Compression, and Enable Tooltips checkboxes are<br />
checked<br />
- Click on the IP Security Button. Be sure then<br />
Enable checkbox is unchecked. Click OK.<br />
- Click on the Advanced Button. Be sure the Web<br />
Tunneling Gateway Enabled checkbox is<br />
unchecked. Click OK.<br />
• Select Project Status Execution and be sure the<br />
TCP/IP Server task is set to Automatic<br />
Step 2: Configure Database<br />
• In the Development Environment, select the Database<br />
tab of the Workspace. Open the Applications Tags<br />
folder.<br />
• Be sure the application tags are properly set to either<br />
Server or Local. If the tags are to be exposed to the Web<br />
Client, then set them to Server, otherwise set to Local.<br />
Step 3: Develop your Screens and create HTML screens<br />
• Develop your application screen. Depending on your Web<br />
Thin Client screen size, you may want to develop a<br />
separate set of screens with a different resolution. Auto<br />
Screen scaling is supported (enabled in a prior step), but<br />
auto screen scaling naturally has limitations.<br />
• Save and Close all application screens<br />
• Be sure you have defined a Startup Screen (Project Settings Runtime Desktop (tab). Specify<br />
the Startup Screen in the Startup Screen field (e.g. startup.sg).<br />
• In the Development Environment, select File from the Main Menu Bar. You can save individual display<br />
screens as HTML using the Save as HTML or Save Screen Group as HTML, or save all Screens and<br />
Screen Groups as HTML by selecting the Save All as HTML option.<br />
• If you are just updating a Screen, and especially when you make any configuration changes to the Web<br />
settings, you should run the Verify Application tool (Tools Verify Application) from the Main Menu<br />
Bar.<br />
• The HTML (web) pages will be stored in the \Web sub-folder of your application folder.<br />
InduSoft Web Studio 32–3
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Building a Simple Web Thin Client Application Step by Step<br />
Step 4: Install NTWebServer<br />
• NTWebServer is InduSoft’s light-weight Web Server for Windows NT/XP/2000/Server 2003/Vista<br />
environments. NTWebServer.exe is found in the \Bin folder of the <strong>IWS</strong> program installation folder<br />
(generally c:\Programs and Files\InduSoft Web Studio v6.1\Bin<br />
• Copy NTWebServer.exe from the \Bin folder and paste it into the \Web sub-folder of your Application<br />
folder.<br />
• From the \Web sub-folder, double click on NTWebServer to start it.<br />
• A new window should pop-up. At the bottom, there should be a message indicating that NTWebServer<br />
is listening. If a message appears that NTWebServer failed to open a socket, it is most likely caused by<br />
Microsoft IIS (Web Server) running in a background mode. If this is the case, you will need to stop IIS,<br />
and then restart NTWebServer<br />
Step 5: Start the Application Runtime<br />
• From the Development Environment, click on the Run application button to start the runtime.<br />
Step 6: Launch Microsoft Internet Explorer and connect to the Web Server<br />
• Click on the Start button (or Alt Tab) to access the Microsoft Internet Explorer program.<br />
• Start Internet Explorer, and type the address of the starting (home webpage). E.g.<br />
http://127.0.0.1/startup.html<br />
• Note that the startup.sg (or whatever your startup display or screen group name is) will have a HTML<br />
file extension on it when accessed from Internet Explorer.<br />
• Sign on as Guest with no password, assuming no security has been enabled.<br />
Procedure B: Web Thin Client using NTWebServer, Network IP<br />
Once Procedure A has been completed, the next step is to enable network connected Web Thin Clients,<br />
instead of using the local loopback. You need to know the IP address of your PC, as seen from the network.<br />
You can get this information from the Network Settings in the Control Panel, or putting the function<br />
GetComputerIP() in a Rectangle Object on a screen and running the application.<br />
Step 1: Configure <strong>IWS</strong> Settings<br />
• Stop any active application runtime.<br />
• In the Development Environment, select Project Settings Web (tab). In the Data Server IP<br />
Address field, enter the IP address of your PC (as viewed from the network). E.g. 192.168.1.100<br />
• Run the Verify Application tool (Tools Verify Application). This will set change the Data Server IP<br />
address in the web pages, so that the Web Thin Client will automatically exchange data with the correct<br />
Data Server.<br />
Step 2: Start the Application Runtime<br />
• From the Development Environment, click on the Run application button to start the runtime.<br />
• Be sure NTWebServer is still running.<br />
Step 3: Launch Microsoft Internet Explorer and connect to the Web Server<br />
• Click on the Start button (or Alt Tab) to access the Microsoft Internet Explorer program.<br />
• Start Internet Explorer, and type the address of the starting (home webpage). E.g.<br />
http://192.168.1.100/startup.html<br />
• Sign on as Guest with no password, assuming no security has been enabled.<br />
32–4 InduSoft Web Studio
Building a Simple Web Thin Client Application Step by Step<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Procedure C: Web Thin Client using IIS, Network IP<br />
Once Procedure B has been completed, the next step is to enable IIS to become the Web Server for your Web<br />
Thin Clients instead of NTWebServer. The following are the basic steps to configuring IIS, although depending<br />
on your network and Operating System environment, additional settings may need to be configured such as<br />
user security.<br />
Step 1: Configure <strong>IWS</strong> Settings<br />
• Be sure NTWebServer is terminated.<br />
• Click the Start button, then Control Panel Administrative Tools<br />
• Select (click on) Internet Information Services<br />
• Expand the Web Sites tree structure to see the Default Web Site<br />
• Right click on the Default Web Site and select Properties to get the Default Web Site Properties dialog<br />
box.<br />
InduSoft Web Studio 32–5
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Building a Simple Web Thin Client Application Step by Step<br />
• Click on the Home Directory tab. Click on the Local Path Browse button and point to your<br />
application’s \Web subfolder.<br />
• Click on the Web Site tab. Make sure the TCP port is set to 80. You can click the Advanced button to<br />
enable the IIS Web Server to respond to specific IP addresses and IP Port numbers.<br />
• If your Web Server is behind a Proxy, be sure to check the HTTP Keep-Alives Enabled checkbox. It<br />
does not hurt anything if this is always checked.<br />
32–6 InduSoft Web Studio
Building a Simple Web Thin Client Application Step by Step<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
• Click on the HTTP Headers tab. Click on the MIME Map File Types button to open the File Types<br />
dialog box. Next, click on the New Type button to add a new MIME type. Put the file extension in the<br />
Associated Extension field. In the Content type (MIME) field, put MIME type followed by a /<br />
character, followed by the file extension name (application/<strong>IWS</strong>). E.g.<br />
Associated Extension: .scc<br />
Content Type: application/<strong>IWS</strong><br />
.<br />
InduSoft Web Studio 32–7
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Building a Simple Web Thin Client Application Step by Step<br />
About MIMEs<br />
• MIME, or Multipurpose Internet Mail Extensions, types instruct a Web browser how to handle files<br />
received from a server. For example, when a Web browser requests an item on a server, it also requests<br />
the MIME type of the object. Some MIME types, like graphics, can be displayed inside the browser.<br />
Others, such as word processing documents, require an external helper application to be displayed.<br />
When IIS delivers a Web page to a client Web browser, it also sends the MIME type of the data it is<br />
sending. If there is an attached or embedded file in a specific format, IIS also tells the client application<br />
the MIME type of the embedded or attached file. The client application then knows how to process or<br />
display the data being received from IIS.<br />
IIS serves only files with known extensions registered in the MIME types list or with the operating system.<br />
IIS allows you to configure additional MIME types and change or remove MIME types. Removing a MIME<br />
type in IIS does not block access to that MIME type by other applications if it is also registered with the<br />
operating system.<br />
IIS is preconfigured to recognize a default set of global MIME types. These MIME types are recognized<br />
by all Web sites you create in IIS. MIME types can also be defined at the Web site and directory levels,<br />
independent of one another or the types defined globally. When you view MIME types at the Web site or<br />
directory level, only the types unique to that level are displayed, not all types inherited from the next level<br />
up.<br />
• IIS returns a 404.3 error if a client request refers to a file name extension that is not defined in the MIME<br />
types<br />
• MIME configuration is usually only required for Windows Server 2003, not Windows XP or Vista due to<br />
Windows 2003 default settings.<br />
• MIME types should include all file extensions found in the \Web directory. These include:<br />
- .app<br />
- .bin<br />
- .csv<br />
- .gis<br />
- .html<br />
- .ico<br />
- .ini<br />
- .lst<br />
- .scc<br />
- .sg<br />
- .stmp<br />
- .tra<br />
- .txt<br />
• Click on the Directory Security tab. From this tab, you can change the settings for Anonymous User<br />
Access and Authentication Control as well as Secure Communications (i.e. using SSL 3.0).<br />
• Click on the Anonymous User Access and Authentication Control Edit button to get the<br />
Authentication Methods dialog box. Normally, you do not have to do anything in this dialog box but<br />
depending on the Security system your network administrator has installed, you may need to adjust<br />
settings in this dialog box.<br />
• The Secure Communications Server Certificate button opens a wizard that lets you define a<br />
Certificate for support of secure communications using SSL.<br />
32–8 InduSoft Web Studio
Building a Simple Web Thin Client Application Step by Step<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Step 2: Start IIS and start the <strong>IWS</strong> Application<br />
• Be sure NTWebServer is terminated.<br />
• Click on the IIS Start button<br />
• Start up the <strong>IWS</strong> Application<br />
InduSoft Web Studio 32–9
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Building a Simple Web Thin Client Application Step by Step<br />
Notes:<br />
• If IIS is not installed on your PC, you can add it (to Windows XP Pro/Windows 2000 or Windows Server<br />
2003) by opening the Control Panel, then selecting Add/Remove Programs Add/Remove Windows<br />
Components and checking the Internet Information Services (IIS) checkbox in the Windows Components<br />
Wizard. You can click on the Details button to select various components of IIS to install. Note that you<br />
may need to have your Windows installation disk.<br />
• You can get more information on IIS by opening a browser and entering http://localhost/iishelp in the<br />
browser navigation address bar. Note that IIS must be running.<br />
• NTWebServer is a Windows Application, while IIS is a Windows Service.<br />
• It is STRONGLY SUGGESTED that you use IIS instead of NTWebServer in a runtime mode. It is more<br />
reliable and higher performance than NTWebServer.<br />
Troubleshooting:<br />
• If you get a Cannot find Server error message,<br />
- From the browser, ping the server IP address (primary and/or backup). You can ping using the IP<br />
address or use the NetBios name to ping the server (e.g. from a command prompt enter<br />
Ping 152.57.100.25 or Ping ServerName.<br />
- Be sure IIS is running<br />
- Be sure your <strong>IWS</strong> application is running<br />
- Make sure the TCP/IP Server (in the <strong>IWS</strong> Application) is running<br />
- Be sure IIS is set to the correct Home Page (root directory).<br />
- Be sure the Port addresses are correct (HTTP – Port 80, HTTPS (SSL) – Port 443, Data – Port 1234)<br />
- Make sure you firewall has these ports open<br />
- If you are using a Windows CE-based device, be sure ISSymbol is properly loaded and registered<br />
- Be sure your runtime license supports the Web Client configuration<br />
• If you get a Page cannot be displayed error message,<br />
- From the browser, ping the server IP address<br />
- Stop and restart IIS<br />
- Be sure the MIME types are properly set<br />
- Make sure you updated your web pages (i.e. Save as HTML) and use the Verify Application tool if you<br />
change any Web settings.<br />
- Verify the Windows security settings are properly set<br />
- Be sure that the Screen name (and Web Page name) do not have any spaces in the name<br />
• If the web pages are incorrect:<br />
- Be sure you are pointing to the correct primary URL<br />
- Be sure your backup URL (if you use it) has the correct (updated) web pages<br />
32–10 InduSoft Web Studio
Web Thin Clients – The Underlying Technology<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Web Thin Clients – The Underlying Technology<br />
In an <strong>IWS</strong> Application, there are several components used to implement the Web Thin Client capability.<br />
Server – <strong>IWS</strong> Application<br />
Web Client<br />
Data Server<br />
<strong>IWS</strong> TCP/IP Server<br />
TCP/IP Port 1234<br />
ISSymbol (<strong>IWS</strong>)<br />
ActiveX<br />
Data Push<br />
Downloads:<br />
- Screens<br />
- Database files<br />
<strong>IWS</strong> Tag Database<br />
Server – Web Pages<br />
Web Server<br />
E.g. <strong>IWS</strong> NTWebServer,<br />
CEWebServer, IIS,<br />
Apache<br />
Web Tunneling<br />
Gateway (WTC)<br />
HTTP: TCP/IP Port 80<br />
SSL (HTTPS): Port 443<br />
Performs security<br />
Launches virtual<br />
TCP/IP Client to<br />
communicate<br />
between Data<br />
Server and Web<br />
Client<br />
Will exchange<br />
Tag data based<br />
on settings<br />
IE 6/IE 7<br />
Web Browser<br />
or<br />
Secure Viewer<br />
Screen HTML Files<br />
These components are:<br />
Data Server<br />
The Data Server is built-in to the <strong>IWS</strong> runtime. The Data Server has direct access to the <strong>IWS</strong><br />
Application Tags Database (runtime) and is responsible for working with ISSymbol to make sure any<br />
Tag data being displayed on a Web page at any Web Thin Client is updated with the latest value(s).<br />
<strong>IWS</strong> can support a backup or secondary Data Server that will be used should the Primary Data Server<br />
become unavailable. The Web Thin Client will automatically switch over to the Secondary without user<br />
intervention required.<br />
Web Server<br />
The Primary Web Server is responsible for providing Web pages on demand (i.e. when requested by<br />
the Client) through navigation to various application screens by the Web Thin Client. The Web Server<br />
communicates with the Web Thin Client via HTTP protocol over TCP/IP. SSL (Secure Socket Layer)<br />
encrypted communications can be enabled. The Web Server does not need to reside on the same PC<br />
as the <strong>IWS</strong> runtime application. In fact, the Web Server could be a non-Windows corporate Web<br />
Server. However, the Web Server needs to have access to the HTML files that are the application Web<br />
pages.<br />
<strong>IWS</strong> supports a Secondary Web Server that will be automatically switched to (by the Client) in case the<br />
Primary Web Server becomes unavailable. However, if the runtime application environment is Windows<br />
CE 3.0, the Backup URL field specifies the address of the Primary Web Server (due to Windows CE 3.0<br />
limitations).<br />
InduSoft Web Studio 32–11
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Web Thin Clients – The Underlying Technology<br />
Web Browser<br />
The Web Browser is located on the Web Thin Client PC and provides the graphical interface function<br />
with the user. Web pages (HTML) is passed to the browser via demand (“pull”) and data is “pushed” to<br />
the browser by the Data Server whenever a Tag or Tags referenced on the Screen displayed on the<br />
Web Client is updated in the Tag Database.<br />
ISSymbol<br />
ISSymbol is an InduSoft-provided ActiveX Control that facilitates the interaction between the browser<br />
on the Web Client and the Web Server as well as the Data Server. There are ISSymbol ActiveX Control<br />
versions for Windows XP/2000/NT/Server 2003/Vista and all Windows CE platforms.<br />
The ISSymbol ActiveX Control is used for both the Internet Explorer-based and Secure Viewer-based<br />
browsers.<br />
Web Tunneling Gateway<br />
The (Primary) Web Tunneling Gateway is a bridge between the Web Server and the Data Server that is<br />
used in one of two situations. The first is whenever data security is required (e.g. <strong>IWS</strong> data exchanged<br />
with the Web Thin Client needs to be encrypted). The second situation is when the Data Server is “hid”<br />
behind a corporate firewall, and only the Web Server IP address (or URL) is exposed.<br />
<strong>IWS</strong> supports a backup (Secondary) Web Tunneling Gateway to be used if the Primary Web Tunneling<br />
Gateway becomes unavailable. The Web Thin Client will automatically switch over to the secondary<br />
Web Tunneling Gateway.<br />
The Web Tunneling Gateway is automatically installed when <strong>IWS</strong> is installed on your PC if the<br />
installation program detects that IIS is present.<br />
Notes:<br />
• The Web Tunneling Gateway is automatically installed if IIS is detected during the installation process.<br />
Otherwise, it must be manually installed.<br />
• The main function of the Web Tunneling gateway is to encapsulate data packets in HTTP or HTTPS for<br />
communication through a firewall.<br />
32–12 InduSoft Web Studio
ISSymbol ActiveX Control<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
ISSymbol ActiveX Control<br />
ISSymbol is an ActiveX Control designed by InduSoft used to display the screens created with <strong>IWS</strong> on the web<br />
browser and exchange data (tag values and history data) using the TCP/IP server module of <strong>IWS</strong>. It is a central<br />
component in the operation of a Web Thin Client. On the Web Thin Client station, the web browser (e.g.<br />
Internet Explorer) is the container that hosts the ISSymbol ActiveX Control.<br />
ISSymbol works as a control layer between the <strong>IWS</strong> application and the web browser – equivalent to the Java<br />
Virtual Machine for Java-based applications. This approach provides a high level of security because ISSymbol<br />
does not allow the application to access the operating system directly.<br />
When the web browser downloads the HTML page specified by the user, it checks for ISSymbol control<br />
registration (Certificate of Authenticity) on the current computer. If it does not find it, the browser attempts to<br />
download registration from the URL specified in the Project Settings Web Advanced dialog box. The<br />
web browser is not able to display the screens from the <strong>IWS</strong> application if the ISSymbol control is not properly<br />
registered in the Web Thin Client station.<br />
Note:<br />
• Make sure your web browser is enabled to download signed ActiveX controls, in order to download<br />
ISSymbol automatically. Otherwise, you will need to register ISSymbol manually in the Web Thin Client<br />
station. Check your web browser’s documentation about security settings if you have questions about<br />
how to configure these settings.<br />
Configuring the Web Server for automatic download of ISSymbol<br />
As long as your Windows browser (Web Client) platform is not based on Windows CE, and your browser is<br />
configured to allow downloading of ActiveX controls, you can configure the Web Client and Web Server to<br />
automatically download the ISSymbol ActiveX Control to a Web Client. Windows CE-based platforms do not<br />
currently support downloading and automatic registration of ActiveX Controls, this must be done manually.<br />
InduSoft Web Studio 32–13
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
ISSymbol ActiveX Control<br />
By selecting Project Settings Web tab and clicking on the Advanced tab, you open the Web<br />
Configuration Advanced dialog box. In the ISSymbol URL field, there is a default URL pointing to InduSoft’s<br />
website to a path for downloading the ISSymbol ActiveX Control if it is not already installed on your Web Thin<br />
Client.<br />
But what do you do if your Web Client does not have Internet connectivity No problem, you simply put a copy<br />
of the ISSymbolVM.cab file (found in the C:\Program Files\InduSoft Web Studio v6.1\Bin folder) into your Web<br />
Server’s root folder (i.e. the folder or path where the Web Server (e.g. IIS) is pointing to for HTML files). Then,<br />
you change the path in the ISSymbol URL field (in the Advanced Dialog box) to reflect the URL or IP address of<br />
your Web Server. E.g. http://152.30.75.100. Then, when a Web Client (without ISSymbol installed and<br />
registered) connects to the Web Server, ISSymbol can be automatically downloaded and will self-register.<br />
Installing the ISSymbol control manually<br />
You can install the ISSymbol ActiveX Control manually in a Web Thin Client PC. The procedure to install<br />
ISSymbol in each operating system is described below:<br />
<br />
<br />
<br />
Windows XP/2000/NT/Server 2003/ Vista:<br />
Copy the files ISSymbolReg.exe and ISSymbolVM.cab from the \BIN sub-folder of Indusoft Web<br />
Studio v6.1 (C:\Program Files\Indusoft Web Studio v6.1) folder and paste them in any directory of the<br />
Web Thin Client station. Make sure that both files are stored in the same directory.<br />
Run ISSymbolReg.exe to register ISSymbol control in the Web Thin Client station.<br />
Windows CE:<br />
Copy the file ISSymbolCE.ocx and IndHTTP.dll from the \Redist\\\<br />
sub-folder of Indusoft Web Studio v6.1, and paste them in any directory of the Web Thin Client<br />
station.<br />
Execute the following command from the Prompt window: regsvrce.exe<br />
“\\ISSymbolCE.ocx” (e.g. regsvrce.exe “\Storage Card\ISSymbolCE.ocx”)<br />
Save the registry settings to keep ISSymbolCE.ocx registered when you reboot the Windows CE<br />
device.<br />
Windows CE PocketPC:<br />
Copy the files RegSvrCE.exe, ISSymbolCE.ocx and ndHTTP.dll from the \Redist\\\ sub-folder of Indusoft Web Studio v6.1 and paste them in any directory<br />
of the Web Thin Client station. Make sure that both files are stored in the same directory.<br />
Execute the RegSvrCE.exe program on the Web Thin Client device. To register ISSymbolCE.ocx, do<br />
the following:<br />
• Select the \\ISSymbolCE.ocx file<br />
• Select the option Register<br />
• Click the OK button<br />
Note:<br />
• Internet Explorer is not able to download ActiveX controls automatically from Windows CE and Windows<br />
CE PocketPC. Therefore, before using Windows CE devices as Web Thin Clients, you must register the<br />
ISSymbolCE.ocx control manually.<br />
32–14 InduSoft Web Studio
ISSymbol ActiveX Control<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
How ISSymbol Operates with the Web Thin Client<br />
After you open the browser on the Web Thin Client, you enter the URL for the startup web page in the Web<br />
Server (e.g. http://192.168.1.100/startup.html) into the Address field. {Note: the Secure Viewer does not<br />
require the entry of the URL for the startup Web page}. At this point, the Web Thin Client executes the following<br />
process:<br />
1. The browser downloads the HTML page of the screen you specified from the Web Server.<br />
2. The browser checks for ISSymbol ActiveX Control registration in the local computer. If it does not find it,<br />
or if the ISSymbol ActiveX Control is an out of date version, the browser attempts to download the<br />
ISSymbol component from the URL configured in the application (settings are embedded in the HTML<br />
page). If the ISSymbol control is properly registered in the Web Thin Client station, the browser loads it.<br />
From this point on, ISSymbol takes over the communication with the Web Server, and the browser is<br />
used only as a host for ISSymbol.<br />
3. ISSymbol now connects to the Data Server. The Data Server IP Address was initially configured in the<br />
Project Settings Web dialog window. This setting is now embedded in the HTML page.<br />
4. ISSymbol prompts a window on the Web Thin Client, asking for the User Name and Password. The<br />
data you enter is encrypted and sent to the server. The Web Server checks the validity of the data and<br />
whether you have the rights to open the startup screen. If so, the process continues. If not, you are<br />
prompted with an error message indicating that the User Name and/or Password are invalid. In this<br />
case, the process will not continue.<br />
Note:<br />
• Step 4 is skipped if the Security System is disabled during the configuration of the application. If the<br />
Security System is disable, use Guest as the User Name (with no Password).<br />
5. ISSymbol downloads the necessary files to display the screen specified by the user (screen files, tags<br />
database, translation files, etc.).<br />
6. ISSymbol connects to the Data Server and reads the value of the tags that are displayed in the screen<br />
you specified.<br />
7. ISSymbol displays the screen on the browser and keeps updating the objects according to the values<br />
read from the Data Server. Whenever the value of any tag displayed on the open screen(s) changes on<br />
the Data Server, the new value is sent to the Web Thin Client (and vice-versa). Therefore, there is no<br />
pooling between the Web Thin Client and the server station. This method increases the communication<br />
performance and optimizes the traffic in the network.<br />
InduSoft Web Studio 32–15
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Web Server Configuration<br />
Web Server Configuration<br />
There are several different Web Servers that can be used with an <strong>IWS</strong> application to support Web Thin Clients.<br />
The choice of Web Server depends on the platform used. As previously mentioned, the Web Server is not<br />
required to be on a Microsoft Windows OS platform, it could be on a Linux corporate web server. However, if<br />
you require the Web Tunneling Gateway (designed by InduSoft), the Web Server must be Microsoft IIS (Internet<br />
Information Services).<br />
Examples of Web Servers include:<br />
Web Server Operating System Comments<br />
NTWebServer Windows NT, 2000, XP, Server 2003,<br />
Vista<br />
InduSoft provided light weight Web<br />
Server. An application, not a Service.<br />
CEWebServer Windows CE InduSoft provided light weight Web<br />
Server. An application, not a Service.<br />
IIS 4.0<br />
Windows NT<br />
IIS 5.0 Windows 2000<br />
IIS 5.1 Windows 2000, XP Pro Max. 10 simultaneous connections<br />
IIS 6.0 Windows Server 2003 No limit on connections<br />
IIS 7.0 Windows Vista No limit on connections<br />
IIS for CE.NET Windows CE.NET 4.x, 5.0, 6.0 Must be included in Platform Builder.<br />
Default is 10 maximum simultaneous<br />
connections.<br />
Apache 2.0 for Windows Windows XP, 2000, Server 2003 Can run as an Application or Service<br />
NTWebServer is located in the \Bin sub-folder of the <strong>IWS</strong> program folder following installation. CEWebServer is<br />
located in the \Redist\\ sub-folder of the <strong>IWS</strong> program folder following<br />
installation. Regardless of which InduSoft Web Server you use, it needs to be copied to the \Web sub-folder of<br />
your application folder and executed from this folder. The home directory (Web Root directory) for both of these<br />
Web Servers is the directory where they are executed. NTWebServer and CEWebServer were designed<br />
primarily for simple tests and/or for demos. InduSoft recommends using third-party commercial Web Servers<br />
such as IIS (Internet Information Services) from Microsoft or Apache for real-world applications.<br />
A commercial Web Server must be configured prior to use. One of the key settings for the Web Server is to<br />
assign a home directory (or Web Root directory), which should be the \Web sub-folder located in the application<br />
folder. Consult your Web Server’s documentation for further information about its configuration.<br />
32–16 InduSoft Web Studio
Web Tunneling Gateway Configuration<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Web Tunneling Gateway Configuration<br />
Web Thin Clients are commonly connected to the Web Server via the Internet. However, the Data Server(s)<br />
(PC where the <strong>IWS</strong> is running) is often not directly connected to the Internet. In this case, the Data Server<br />
computer does not have an IP address recognized on the internet. Therefore, the Data Server cannot be<br />
connected directly through the Internet.<br />
The Web Tunneling Gateway (WTG), developed by InduSoft, provides the routing capabilities to solve this<br />
problem. The WTG must be installed in the PC with the Fixed IP Address on the Internet. Generally, this is the<br />
Web Server. Consult your ISP provider for further information about how to get a Fixed IP Address for your PC<br />
on the Internet. The PC where the WTG is running must have the Microsoft IIS Web Server installed and<br />
running. The WTG is an ISAPI extension for IIS.<br />
The Web Tunneling Gateway also provides the ability to encapsulate the data packets between the Data Server<br />
and the Web Client in HTTP or HTTPS.<br />
Follow the procedure below to install the WTG on the Web Server computer:<br />
<br />
<br />
Copy the WebGtw.exe file from the \BIN sub-folder of <strong>IWS</strong> into any directory of the web server<br />
computer.<br />
Execute the WebGtw.exe file on the web server computer.<br />
The WTG works as a router between the Web Thin Clients (connected to the Internet) and the Data Server PC<br />
(connected to the Intranet). The same WTG can route information for more than one Data Server<br />
simultaneously.<br />
InduSoft Web Studio 32–17
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Web Browser Configuration<br />
Web Browser Configuration<br />
<strong>IWS</strong> supports two types of Web Browsers for use with Web Thin Clients; Microsoft Internet Explorer, which<br />
supports ActiveX Controls, and the InduSoft-developed Secure Viewer. Both browsers can use used<br />
concurrently with the Web Server, and the choice of browser depends on the application requirements. The<br />
Secure Viewer browser is targeted at plant floor use, while the Internet Explorer browser is generally more<br />
appropriate for desktop applications or where the Web Thin Client needs to browse different Web Servers.<br />
Configuring Microsoft Internet Explorer<br />
There is really very little that needs to be done to configure Microsoft Internet Explorer to be used as a Web<br />
Browser for an <strong>IWS</strong> Web Thin Client. The primary items are:<br />
• Make sure ActiveX Controls are enabled.<br />
The settings to control this are generally found in Tools Internet Options Security. Click on the<br />
Custom Level button and be sure to allow the ISSymbol ActiveX Control to be installed, then you can<br />
return to a higher security level. (Otherwise, be sure to install the ISSymbol ActiveX Control manually).<br />
• Be sure VBScript is supported on your PC. This is generally not an issue with Windows<br />
XP/NT/2000/Server2003/Vista based PCs, but can be an issue on Windows CE-based devices. You<br />
will need to be sure the VBRun.dll is installed and registered on your PC.<br />
If you are going to use Microsoft Internet Explorer as your web browser for Web Thin Client applications, you<br />
may want to remove some navigation bars and buttons to reduce the amount of space taken up by these items.<br />
You can create an icon on the desktop that is a shortcut to your startup web page on the Web Server. This will<br />
take you to the web page when you click on the icon. Additionally, you can put this shortcut in the Startup folder<br />
so that the Web page is automatically started whenever the browser is started.<br />
Installing the Secure Viewer Browser on Windows XP/2000/Vista PC<br />
You will need to install the Secure Viewer browser from your CD (or download from the InduSoft website).<br />
Follow the following steps:<br />
Request the Secure Viewer installer from your software vendor, save it to the designated computer, and<br />
start it.<br />
Follow the instructions of the installation wizard. There are only two settings that must be configured<br />
during installation:<br />
• URL: Enter the URL or filepath of the application file (*.app) on the Web Server.<br />
32–18 InduSoft Web Studio
Web Browser Configuration<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
• Server IP: Enter the IP address or hostname of the TCP/IP Server.<br />
Finish the installation and click Finish to close the installer.<br />
The installation wizard automatically installs and registers the Web Thin Client ActiveX component<br />
(ISSymbol.ocx), so if you have correctly configured the URL and Server IP settings, then the Secure Viewer<br />
should be ready to go.<br />
Note:<br />
• For additional security of the runtime environment, add a shortcut to the Secure Viewer (Viewer.exe) to<br />
the Startup directory in Windows. Viewer.exe will install into the \Bin sub-folder where the <strong>IWS</strong> program<br />
installs.<br />
Installing the Secure Viewer Browser on Windows CE<br />
You can also install the Secure Viewer on a Windows CE device, by copying the necessary files to the device’s<br />
non-volatile memory. To install Secure Viewer:<br />
Create and configure a viewer.ini file with the appropriate settings for the Windows CE device. (For<br />
more information about creating this file, see the previous section.)<br />
Determine the OS version and processor type of the Windows CE device, and then find the<br />
corresponding sub-folder in the InduSoft Web Studio program directory. For example, for Windows CE<br />
v4.0 running on a MIPS processor, find the \Indusoft Web Studio v6.1\Redist\WinCEv4.0\MIPS\ subfolder.<br />
Select the Secure Viewer program (Viewer.exe) and ISSymbol control (ISSymbolCE.ocx) from this<br />
sub-folder, as well as the viewer.ini file you’ve already created, and copy all three to non-volatile<br />
memory on the Windows CE device.<br />
Register the ISSymbol control on the Windows CE device by executing the following command from the<br />
Prompt window:<br />
regsvrce.exe "\\ISSymbolCE.ocx"<br />
Example — regsvrce.exe "\Storage Card\ISSymbolCE.ocx"<br />
Save the registry settings to keep ISSymbolCE.ocx registered when you reboot the Windows CE<br />
device.<br />
Start the Secure Viewer by running Viewer.exe.<br />
Tip: Check the device manufacturer’s documentation for how to save the registry settings.<br />
InduSoft Web Studio 32–19
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Web Browser Configuration<br />
Changing the Secure Viewer Configuration<br />
After initial installation, the configuration of the Secure Viewer is saved in the viewer.ini file, which should be in<br />
the same directory as Viewer.exe. (This should be in the \Bin sub-folder where the Secure Viewer program is<br />
installed). There are two ways to change the configuration of the Secure Viewer after it has been installed. First,<br />
you can run the Viewer configuration utility (ViewerCfg.exe) that was also installed.<br />
The configuration utility provides the following options:<br />
Load button: Click to load a viewer.ini file into the utility for editing.<br />
Save button: Click to save your changes to the viewer.ini file.<br />
Data Server IP field: Enter the IP address (or host name) of your data server station.<br />
The data server station is the computer or device where the TCP/IP Server module is running.<br />
TCP Port field: Enter the port number of the Data Server, if it is different than the default port of 1234.<br />
URL field: Enter the URL or filepath of the application file (*.app) on the Web Server.<br />
Enable Splash Window option: Check (enable) this option to see a splash window when you start the<br />
Secure Viewer.<br />
Enable Progress Bar option: Check (enable) this option to see a progress bar while the Secure Viewer<br />
loads the application file.<br />
• Advanced button: Click to access additional configuration options:<br />
Secure Viewer Configuration Utility — Advanced Settings<br />
– Secondary Data Server IP field: Type the IP address (or host name) of the secondary data server<br />
station. If the primary data server fails, the Secure Viewer will attempt to connect to the secondary<br />
data server automatically.<br />
32–20 InduSoft Web Studio
Web Browser Configuration<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
– Web Tunneling Gateway: If you have configured a Web Tunneling Gateway to bridge your intranet<br />
to the Internet (see “Architecture 4: Web server and Web Thin Clients in different networks” on<br />
page 13–8), then enter the addresses for the gateway here.<br />
– Log on as Guest option: Check (enable) to have the Secure Viewer automatically log on as Guest,<br />
eliminating the need to enter a Username or Password.<br />
The second way to change the configuration of the Secure Viewer is to manually edit the viewer.ini file with a<br />
text editor. The structure of the file is as follows:<br />
[Options]<br />
nosplash =<br />
// Enable (0) or disable (1) the splash window<br />
noprogressbar = // Enable (0) or disable (1) the progress bar<br />
ds1 =<br />
// Data Server Primary<br />
ds2 =<br />
// Data Server Secondary<br />
dsp =<br />
// Data Server Port<br />
wtg1 =<br />
// Web Tunneling Gateway Primary<br />
wtg2 =<br />
// Web Tunneling Gateway Secondary<br />
url =<br />
// URL from application file (*.app)<br />
proxyip =<br />
// Proxy Address<br />
proxyp =<br />
// Proxy Port<br />
ceemul =<br />
// Enable (1) or disable (0) CEView emulation<br />
Example:<br />
PC with <strong>IWS</strong> Runtime Application (has both Web Server (NTWebServer or IIS) and Data Server)<br />
IP Address is 192.168.1.106<br />
Project is called SecureViewerTest<br />
Application is SecureViewerTest.app<br />
Secure Viewer configuration dialog box<br />
Data Server IP = 192.168.1.106<br />
TCP Port = 1234<br />
URL = http://192.168.1.106//SecureViewerTest.app<br />
Alternatively, you could edit the viewer.ini file<br />
[Options]<br />
url= http://192.168.1.106//SecureViewerTest.app<br />
noprogressbar=1<br />
ds1=192.168.1.106<br />
nosplash=1<br />
ds2=<br />
dsp=1234<br />
wtg1=<br />
wtg2=<br />
user=Guest<br />
[OEM]<br />
Splash=Splash.bmp<br />
//this is a splash screen<br />
Notes:<br />
• Your <strong>IWS</strong> runtime license must support a Secure Viewer (Thin Client) otherwise the connection to the<br />
Data Server will be refused.<br />
• Be sure to put NTWeb Server in the application root folder (not \Web subfolder) or point IIS to the<br />
application root folder.<br />
• The Secure Viewer Configurator is not available for Windows CE. Modify the Viewer.ini file settings<br />
instead.<br />
InduSoft Web Studio 32–21
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Data Server and Web Client Configuration<br />
Data Server and Web Client Configuration<br />
<strong>IWS</strong> has a couple dialog boxes that are used for configuration of the Data Server and the Web Server<br />
configuration to be used. This information is embedded in the HTML web pages that correspond the screens.<br />
The Data Server is part of the <strong>IWS</strong> runtime application and uses the TCP/IP Server module. There are three (3)<br />
basic steps to this configuration:<br />
1: Web Settings dialog box configuration<br />
• In the Main Menu toolbar, click on Project Settings and select the Web tab.<br />
• Enter the IP address of the PC where the <strong>IWS</strong> application runtime will reside in the Data Server IP<br />
Address field.<br />
• Check the checkboxes for Auto Screen Scaling, Enable File Compression and Enable<br />
Tooltips. If you want to disable the Web Client from issuing commands to the Server, check the<br />
Disable Remote Client Commands checkbox.<br />
• If the Web Client is to use a Virtual Keyboard, check the Virtual Keyboard checkbox and any<br />
additional settings for the Virtual Keyboard at the Thin Client.<br />
• By clicking on the Advanced button, you can define a backup URL (i.e. backup Website for web<br />
pages) and a Secondary Data Server IP address. This is for a redundant Web Server and/or a<br />
redundant Data Server, respectively. Web Tunneling can also be enabled in this dialog box. The<br />
URL for the ISSymbol OCX can also be defined if it is not found on the Web Server<br />
• By click on the IP Security button, you can define a range of IP addresses that will be accepted by<br />
the Data Server. If a request for data comes from an IP address outside of the defined ranges, the<br />
request will not be acknowledged. This is an Embedded Firewall function.<br />
32–22 InduSoft Web Studio
Data Server and Web Client Configuration<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
2: Communication Settings dialog box configuration<br />
• In the Main Menu toolbar, click on Project Settings and select the Communication tab.<br />
• Enter the Port number (1234 is the default) for the Data Server. You can also define the Data Send<br />
Period (i.e. time period for updated communication of data values to the Web Client).<br />
• Optionally enable Binary Control of the data. It is more secure, but is slower. The default is<br />
disabled.<br />
3: Enable the TCP/IP task<br />
• In the Main Menu toolbar, click on Project Status and select the Execution Tasks tab.<br />
• Be sure the TCP/IP Server is set to Automatic. This should be the default state, but can be<br />
manually configured by selecting the Startup button.<br />
• Be sure the TCP Port number is properly set (see Communication Settings above), otherwise the<br />
TCP/IP Server will start then stop.<br />
InduSoft Web Studio 32–23
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Data Server and Web Client Configuration<br />
Notes:<br />
• This configuration information (from Step 1 & 2) gets embedded in the Web Pages generated from the<br />
<strong>IWS</strong> development environment when you Save As HTML.<br />
• If you change any of these settings, you MUST run the Verify Application tool<br />
Using the SetWebConfig Function<br />
The <strong>IWS</strong> SetWebConfig() built-in function allows the developer to programmatically configure the Data Server<br />
and Web Client configuration, and the resulting configuration settings are automatically updated in the<br />
application’s HTML files (located in the \Web subfolder). This function always runs on the <strong>IWS</strong> Server, and<br />
works in both a Windows XP and Windows CE environment.<br />
The function is called as follows:<br />
SetWebConfig( strServerIP, strOptBackupURL, strOptPath, numOptHostPort, strOptSecondaryServerIP,<br />
numOptProtocolFlag, numOptGtwPort, strOptGtwIP, strOptSecondaryGtwIP, strOptISSymbolURL), where:<br />
strServerIP<br />
Data Server IP Address. IP address (or hostname) of the computer where the TCP Server module of<br />
<strong>IWS</strong> is running.<br />
strOptBackupURL<br />
Optional alternative URL for the application web pages. The Web Thin Client will look for the web pages<br />
in this URL if it does not find them in the same URL written in the Address field of the web browser.<br />
strOptPath<br />
Optional path where the web pages that must be updated are stored.<br />
Note: You can specify an individual file (e.g. you only want to update one file. This is especially<br />
useful for Windows CE applications.<br />
numOptHostPort<br />
Optional TCP Port number that the Web Thin Client must use to exchange data with the TCP Server<br />
module of <strong>IWS</strong>.<br />
strOptSecondaryServerIP<br />
Optional alternative data server IP address. The Web Thin Client will attempt to connect to the TCP<br />
Server module of <strong>IWS</strong> in this IP Address if it is not able to connect to the TCP Server module running in<br />
the IP Address specified in the strServerIP parameter.<br />
numOptProtocolFlag<br />
Optional When you use the Web Tunneling Gateway option, this parameter specifies whether the Web<br />
Thin Client will use either HTTP to exchange data with the Web Server or HTTPS (SSL – Secure<br />
Socket Layer). If this flag has the value 0, the Web Thin Client will use HTTP. If this flag has the value<br />
1, the Web Thin Client will use HTTPS (SSL).<br />
numOptGtwPort<br />
Optional TCP Port number that the Web Thin Client must use to exchange data with the Web Server<br />
when using the Web Tunneling Gateway.<br />
strOptGtwIP<br />
Optional IP Address (or hostname) of the computer where the Web Tunneling Gateway is running.<br />
strOptSecondaryGtwIP<br />
Optional Alternative IP Address (or hostname) of the computer where the Web Tunneling Gateway is<br />
running. The Web Thin Client will attempt to connect to the Web Tunneling Gateway in this IP Address<br />
if it is not able to connect to the Web Tunneling Gateway running in the IP Address specified in the<br />
strOptGtwIP parameter.<br />
strOptISSymbolURL<br />
Optional URL from where the updated version of ISSymbol (ActiveX control) must be downloaded if it is<br />
not properly registered in the Web Thin Client station.<br />
32–24 InduSoft Web Studio
Data Server and Web Client Configuration<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Configuring the Web Server to support IE and Secure Viewer Browsers<br />
<strong>IWS</strong> is capable of supporting both Interned Explorer (IE)-based browsers and Secure Viewer-based browser at<br />
the same time. To do this however, you need to take some care in how you configure your system.<br />
From the Web-Server side<br />
• All HTML files go into the Project Application \Web subfolder<br />
• Put a copy of any translation file(s) in the \Web subfolder and the Project Application folder.<br />
• In the Project Settings Options dialog box, have the Automatic Translation – Translation File<br />
Name point to the translation file in the \Web subfolder<br />
• Configure your Web Server (e.g. IIS) to have its root folder point to the Project Application folder<br />
• Put ISSymbolVM.cab in the Project Application folder if an internet connection to InduSoft’s Web Site is<br />
not available and the ISSymbol ActiveX control is not installed on the IE-based Web Client.<br />
From the Web-Client side<br />
• The Secure Viewer-based browser should be configured to point to the .APP file in the Project Application<br />
folder<br />
• The IE-based browser should have as an initial URL something like as follows:<br />
http://192.168.1.100/Web/startup.html, where startup.html is your startup web page.<br />
InduSoft Web Studio 32–25
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Example Web Server/Thin Client Architectures<br />
Example Web Server/Thin Client Architectures<br />
This section describes some example architectures applied for web-based solutions and provides information<br />
on how to configure the <strong>IWS</strong> application for each architecture. This section does not describe all possible<br />
architectures, but it provides the concepts necessary to design and configure different scenarios based on the<br />
basic architectures illustrated below<br />
The Web Settings are configured by the Web tab of the Project Settings dialog. To open this dialog, in the<br />
development environment select from the Main Menu Bar Project Settings Web (tab). By pressing the<br />
Advanced button, you access additional settings. The following pictures illustrate these dialog boxes:<br />
The following table describes the meaning of the main Web settings illustrated in the above dialog boxes:<br />
Setting<br />
Data Server IP Address<br />
Secondary Data Server IP<br />
Address<br />
Web Tunneling Gateway<br />
IP Address<br />
Web Tunneling Gateway<br />
Secondary IP Address<br />
Description<br />
When the Web Tunneling Gateway is disabled: The Web Thin Client Control (ISSymbol)<br />
uses the Data Server IP Address to connect to the Studio TCP/IP Server Task.<br />
When the Web Tunneling Gateway is enabled: The Web Tunneling Gateway uses the Data<br />
Server IP Address to connect to the Studio TCP/IP Server Task.<br />
Same as the Data Server IP Address. However, the Secondary IP Address is used only when<br />
the connection with the Data Server IP Address fails.<br />
The Web Thin Client Control (ISSymbol) uses the Web Tunneling Gateway IP Address to<br />
connect to the Web Tunneling Gateway.<br />
Same as the Web Tunneling Gateway IP Address. However, the Web Tunneling Gateway<br />
Secondary IP Address is used only when the connection with the Web Tunneling Gateway IP<br />
Address fails.<br />
The Secondary addresses can be used in the following scenarios:<br />
- When the Web Thin Clients can connect to either one of two redundant Servers (Web or Data); or<br />
- When the Web Thin Clients can connect to the Server through the Intranet (LAN – Local Area Network) or<br />
through the Internet (WAN – Wide Area Network). In this case, the Primary addresses should be<br />
configured based on the network used more often by the Web Thin Clients. In the following examples, the<br />
LAN addresses are used as Primary and the WAN addresses are used as Secondary.<br />
32–26 InduSoft Web Studio
Example Web Server/Thin Client Architectures<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
The following table describes the meaning from some terms used in the next examples:<br />
Term<br />
LAN<br />
WAN<br />
Server<br />
Web Thin Client LAN<br />
Web Thin Client WAN<br />
IP_SERVER_LAN<br />
IP_SERVER_WAN<br />
IP_ROUTER_LAN<br />
IP_ ROUTER_WAN<br />
ScreenName<br />
Local Area Network (for example, Intranet)<br />
Wide Area Network (for example, Internet)<br />
Description<br />
Station where the following components are running:<br />
- Studio (TCP/IP Server task)<br />
- Web Server (for example, Internet Information Services from Microsoft – IIS)<br />
- Web Tunneling Gateway for IIS (if enabled)<br />
Although Studio does not need to run in the same station where the other components are<br />
running, the following examples assume that it is.<br />
Web Thin Client station (Web Browser + ISSymbol control) that connects the Server via the<br />
LAN.<br />
Web Thin Client station (Web Browser + ISSymbol control) that connects the Server via the<br />
WAN.<br />
IP Address of the Server on the LAN.<br />
IP Address of the Server on the WAN.<br />
IP Address of the Router on the LAN.<br />
IP Address of the Router on the WAN.<br />
Name of the application screen, saved as HTML, that is open on the Web Thin Client station.<br />
InduSoft Web Studio 32–27
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Example Web Server/Thin Client Architectures<br />
Example 1: Web Server and Web Thin Client in the same Intranet (LAN)<br />
IP_SERVER_LAN<br />
LAN<br />
Web Thin Client<br />
LAN<br />
Server<br />
This is the very common architecture, as well as the simplest to configure. In this architecture, both the Web<br />
Server (e.g. IIS) and the Data Server (<strong>IWS</strong> TCP/IP Server module) are running in the same PC. The Web Thin<br />
Client connects to the Web Server to download the HTML screen file(s). Then it connects to the Data Server to<br />
exchange data with the <strong>IWS</strong> runtime application. Since both the Web Thin Client and the Server station are<br />
connected to the same network, the Web Thin Client can access the Server station directly through its IP<br />
address (or host name).<br />
Configuration:<br />
Setting WTG Enabled Web Gateway Disabled<br />
Data Server IP Address IP_SERVER_LAN IP_SERVER_LAN<br />
Secondary Data Server IP Address - -<br />
Web Tunneling Gateway IP Address IP_SERVER_LAN -<br />
Web Tunneling Gateway Secondary IP Address - -<br />
Remarks:<br />
• URL From Web Thin Client LAN: http://IP_SERVER_LAN/ScreenName.html<br />
• Home directory of the web server (HTTP server) on the server station: \Web sub-folder of the<br />
application<br />
-<br />
32–28 InduSoft Web Studio
Example Web Server/Thin Client Architectures<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Example 2: Web Server with Intranet (LAN) and Internet (WAN) Connections<br />
WAN<br />
IP_SERVER_LAN<br />
Web Thin Client<br />
WAN<br />
IP_SERVER_WAN<br />
Web Thin Client<br />
LAN<br />
LAN<br />
Server<br />
This architecture has both the Web Server (e.g. IIS) and the Data Server (<strong>IWS</strong> TCP/IP Server module) running<br />
in the same PC. Web Thin Clients can connect to the Server through either an Intranet (LAN) connection to the<br />
Server or an Internet (WAN) connection to the Server (e.g. two different Ethernet ports).<br />
Configuration:<br />
Setting<br />
Web Gateway Enabled Web Gateway Disabled<br />
Data Server IP Address IP_SERVER_LAN IP_SERVER_LAN<br />
Secondary Data Server IP Address IP_SERVER_LAN IP_SERVER_WAN<br />
Web Tunneling Gateway IP Address IP_SERVER_LAN -<br />
Web Tunneling Gateway Secondary IP Address IP_SERVER_WAN -<br />
Remarks:<br />
• URL From Web Thin Client LAN: http://IP_SERVER_LAN/ScreenName.html<br />
• URL From Web Thin Client WAN: http://IP_SERVER_WAN/ScreenName.html<br />
• Home directory of the Web Server (HTTP server) on the Server station: \Web sub-folder of the<br />
application<br />
• You must assign a Fixed IP address to the Web Server on the Internet (WAN), and the application must<br />
be running in this Server. Consult your ISP provider or IT department for further information about how<br />
to get a Fixed IP address for your Server.<br />
InduSoft Web Studio 32–29
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Example Web Server/Thin Client Architectures<br />
Example 3: Web Server with Intranet (LAN) and Router Internet (WAN) Connections<br />
WAN<br />
Web Thin Client<br />
LAN<br />
Server<br />
Web Thin Client<br />
WAN<br />
IP_ROUTER_WAN<br />
Router<br />
LAN<br />
IP_SERVER_LAN<br />
IP_ROUTER_LAN<br />
This architecture has both the Web Server (e.g. IIS) and the Data Server (<strong>IWS</strong> TCP/IP Server module) running<br />
in the same PC. Web Thin Clients can connect to the Server through either an Intranet (LAN) connection or an<br />
Internet (WAN) connection. There is a Router between the Intranet (LAN) and the Internet (WAN).<br />
Configuration:<br />
Setting<br />
Web Gateway Enabled Web Gateway Disabled<br />
Data Server IP Address IP_SERVER_LAN IP_SERVER_LAN<br />
Secondary Data Server IP Address IP_SERVER_LAN IP_ROUTER_WAN<br />
Web Tunneling Gateway IP Address IP_SERVER_LAN -<br />
Web Tunneling Gateway Secondary IP Address IP_ROUTER_WAN -<br />
Remarks:<br />
• URL From Web Thin Client LAN: http://IP_SERVER_LAN/ScreenName.html<br />
• URL From Web Thin Client WAN: http://IP_ROUTERR_WAN/ScreenName.html<br />
• The Router must be configured to forward the TCP Port(s) from its public IP (IP_ROUTER_WAN) to the<br />
Server private IP (IP_SERVER_LAN).<br />
If the Web Gateway is enabled, only the HTTP Port (80, by default) or the HTTPS Port (SSL Port 443,<br />
by default) must be forwarded from IP_ROUTER_WAN to the IP_SERVER_LAN.<br />
If the Web Gateway is disabled, both the HTTP Port (80, by default) and the InduSoft TCP/IP Server<br />
Port (1234, by default) must be forwarded from IP_ROUTER_WAN to the IP_SERVER_LAN. Consult<br />
the Router documentation for further information about how to configure Port Forwarding on it.<br />
• Home directory of the Web Server (HTTP server) on the Server station: \Web sub-folder of the<br />
application<br />
• You must assign a Fixed IP address to the Router on the Internet (WAN), and the application must be<br />
running in this Server. Consult your ISP provider or IT department for further information about how to<br />
get a Fixed IP address for your Server.<br />
32–30 InduSoft Web Studio
Security for Web Based Applications<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Security for Web Based Applications<br />
There are various methods for implementing security of Web based Applications. The approach that you require<br />
can depend on a number of factors, and may involve one or more methods of implementing Security.<br />
1. Password Protection<br />
<strong>IWS</strong> provides the ability to create Groups of Users and individual Users within a Group. Each Group (e.g.<br />
Operators, Supervisors, Maintenance) can have different security levels and access different levels of<br />
functionality. Individual passwords can be configured for each User.<br />
In addition, Groups can have advanced settings, allowing features like minimum password size, password<br />
aging, e-signature on Objects with Command Dynamics, Account Auto-lockup (e.g. lock up after a number<br />
of invalid attempts to access), and User Account blocking (temporarily disable – e.g. when employee is on<br />
vacation).<br />
InduSoft Web Studio 32–31
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Security for Web Based Applications<br />
If System Security is enabled, these Password Protection features are also available at the Web Thin Client<br />
station. When a User at a Web Thin Client station attempts to connect to the Web Server, they will be<br />
prompted for a User Name and a Password. If either is invalid, the User will not be let on to the system.<br />
Within an application, the various Objects and their Dynamics, and Screen access can have a security level<br />
assigned to it. The current User logged on must have a access level range which matches the desired<br />
Object or Screen. The following is a representative method of assigning security access levels by Group.<br />
32–32 InduSoft Web Studio
Security for Web Based Applications<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
2. Disabling Web Thin Client Commands<br />
<strong>IWS</strong> allows bi-directional data exchange between the Web Thin Client and the Data Server. However, for<br />
security reasons it may be advantageous to only allow the Web Thin Client to view the process or machine<br />
data, and not send any data back to the Data Server.<br />
By checking the Disable Remote Client Commands check-box from the Project Settings Web dialog<br />
window of the <strong>IWS</strong> development environment, this will insures that all commands coming from a Web Thin<br />
Client station are blocked. The communication becomes unidirectional (from the Server to the Web Thin<br />
Clients):<br />
InduSoft Web Studio 32–33
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Security for Web Based Applications<br />
3. Embedded Firewall<br />
This feature allows the user to filter access to the application based on the Web Thin Clients IP Address.<br />
When a Web Thin Client attempts to connect to the Server station, the Server checks if the IP Address of<br />
the Web Thin Client station is authorized to access the application. The ranges of authorized IP Addresses<br />
can be configured in the Server station by pressing the IP Security button from the Project → Settings →<br />
Web dialog window of the Studio development environment:<br />
4. Encrypted Communications (SSL)<br />
By enabling the Web Tunneling Gateway (WTG), you can enable all communications between the Data<br />
Server + Web Server and the Web Thin Client to be encrypted using RC6, a highly-secure 128-bit<br />
encryption standard. To use SSL, you must do the following:<br />
• From the <strong>IWS</strong> development environment, select<br />
Project Settings Web (tab). Click on the<br />
Advanced button. Check the Web Tunneling Gateway<br />
Enabled check-box. Click on the SSL radio button and<br />
be sure the SSL port is set to 442. Click OK.<br />
• In your Web Server, be sure SSL capabilities are<br />
enabled and that a SSL Certificate of Authentication is<br />
present.<br />
• Be sure SSL is enabled in the Web Client<br />
• Set up all other Web configurations to support the<br />
WTG.<br />
32–34 InduSoft Web Studio
Security for Web Based Applications<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
5. VPN<br />
A VPN is a Virtual Private Network. It is called virtual since it really uses the public Internet to transport<br />
data from one computer to another. But since this network is encrypted and uses other security<br />
mechanisms enabled by the ISP, is it a very secure Private Network. While VPN’s are inherently secure,<br />
they are more costly that a simple public Internet connection.<br />
InduSoft Web Studio 32–35
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Port Usage<br />
Port Usage<br />
There are various ports that are used by <strong>IWS</strong> and/or related software. These are:<br />
Port # Application<br />
20 FTP Server (Data)<br />
21 FTP Server (Command)<br />
25 SMTP Server<br />
80 Microsoft IIS Server for HTTP packets<br />
110 POP3<br />
118 Microsoft SQL Server Services<br />
161 SNMP<br />
162 SNMP Trap<br />
389 LDAP<br />
443 Microsoft IIS Server for HTTPS packets (SSL)<br />
502 Modbus TCP/IP protocol<br />
663 LDAP over SSL<br />
1028 FTP Client (Command)<br />
1029 FTP Client (Data)<br />
1234 <strong>IWS</strong> TCP/IP Server<br />
1443 Microsoft SQL Server<br />
1444 Microsoft SQL Server default port (Monitor)<br />
1521 Oracle<br />
1526 Oracle<br />
2030 Oracle<br />
3001 A-B Ethernet TCP/IP Protocol (default)<br />
3306 MySQL (can be configured to use 3306-3309)<br />
3872 Oracle Management Remote Agent<br />
3997 <strong>IWS</strong> ADO Gateway<br />
4322 <strong>IWS</strong> Remote Agent (CEServer)<br />
5432 PostgreSQL<br />
47808 BACNet UDP Protocol (default)<br />
You may need to accommodate one or more of these port’s usage in your Firewall settings.<br />
32–36 InduSoft Web Studio
Exercise: Viewing Your Application on the Web<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Viewing Your Application on the Web<br />
To view your application, use the following steps:<br />
Expand the Screens folder and double-click on your Main.scr screen.<br />
Selecting a Screen<br />
Select File →Save as HTML to save the screen in HTML format.<br />
Web files are stored in the Web folder, so open the folder and verify that you saved the Main<br />
screen successfully. You should see main.html.<br />
main.html<br />
InduSoft Web Studio 32–37
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Viewing Your Application on the Web<br />
Select Project→Settings from main menu bar, and then select the Web tab.<br />
Open the Project Settings Dialog<br />
Configure the Data Server IP Address to use the IP Address of the Server station<br />
(computer on which you are running) at runtime.<br />
The Web Thin Client station exchanges on-line data (tag values) with the station specified in this<br />
field.<br />
Type the URL path to your main.html file (in the Web folder) into the URL field.<br />
The URL depends on the Home directory configured in the Web Server of your Server station.<br />
Note:<br />
Microsoft provides Web Servers for any Microsoft operating system. Consult your<br />
Microsoft documentation about installing and configuring a Web Server.<br />
After configuring the Web settings, click OK to close the Project Settings dialog.<br />
Close all screens in the screen editor (Window → Close All) and execute the Tools →Verify<br />
Application command to update the Web settings to your Web page.<br />
Caution:<br />
You must execute the Tools →Verify Application again after changing any settings<br />
in the Project Settings menu.<br />
32–38 InduSoft Web Studio
Exercise: Viewing Your Application on the Web<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
To test your Web-based application, use the following steps:<br />
Click the Run Application button (<br />
) to execute the application locally on the Server station.<br />
Open an Internet Browser (Microsoft Internet Explorer or Netscape) and type the URL address to open<br />
your main.html screen from the Server station.<br />
When the Log On dialog displays in the Browser, type guest into the User Name field, then click OK to<br />
open the main.html screen in the Browser.<br />
Log On Dialog<br />
Notice that you can modify the level of any tank locally (Server station) using the Viewer run-time<br />
module or remotely (Web Thin Client) using the Browser.<br />
Note:<br />
A Web Thin Client requires an ActiveX component (ISSymbol.ocx) to handle screens on<br />
the Browser. If you connect the Web Thin Client to the Internet, this component is<br />
downloaded and registered automatically.<br />
.<br />
InduSoft Web Studio 32–39
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Viewing Your Application on the Web<br />
Notes<br />
32–40 InduSoft Web Studio
Chapter 33.<br />
Web Thick Clients<br />
The <strong>IWS</strong> TCP/IP Client/Server modules enable two or more InduSoft applications to keep their databases<br />
synchronized. These modules use TCP/IP protocol to make the communication between the applications.<br />
Before using the <strong>IWS</strong> TCP/IP Client/Server modules, you must install and configure the TCP/IP protocol on the<br />
machines that will run these modules.<br />
Configuring the Server<br />
On the server machine, you do not have to configure anything. You just have to run the <strong>IWS</strong> TCP/IP Server<br />
module. In the development environment window, go to the Project Settings dialog and set the TCP/IP<br />
Server to run automatically. When running this program, a small icon will display in your system tray.<br />
To close the <strong>IWS</strong> TCP/IP Server module, right-click on the icon in the system tray, and select Exit.<br />
Configuring the Client<br />
On the client machine, you must use the TCP/IP Client Configuration worksheet to configure the Server IP<br />
address and the tags you want to share with the server.<br />
In the Workspace, select the COMM tab and right-click the TCP folder to insert a new TCP worksheet.<br />
Configure the following fields:<br />
Description:<br />
Type a description of the worksheet for documentation purposes only. The TCP/IP Client module ignores<br />
this field.<br />
Connection Status:<br />
Type a tag name. The TCP/IP Client Configuration module updates this tag according to connection status.<br />
If the tag value is 0 (zero), then the connection is OK. Otherwise, the Windows Socket library returns an<br />
error code.<br />
Server IP Address:<br />
Type the server IP Address. The entry can be a string or you can use a tag enclosed by brackets. For<br />
example, if you fill this field with {tag_name}, the TCP/IP Client module will try to connect to the server<br />
indicated by the tag_name tag.<br />
Tag Name:<br />
Type the tags you want to share with the server. If the tag is an array or a class (or both), every element<br />
and member is shared. You should type the tag name only in this field—without specifying the index or<br />
class member. If you specify an index or a class, the TCP/IP Client module ignores it.<br />
Remote Tag:<br />
Type the name of the tag to be linked with the tag specified in the Tag Name field. This field is optional. If<br />
you leave it in blank, the same tag name will be used for both the client and the server.<br />
Notes:<br />
• If you need to share an array, then the tag in the server should contain the same number of elements<br />
as the tag in the client. If the tag is a class, then the class definition should be the same in both server<br />
and client applications. If you do not follow these rules, unpredictable results will occur.<br />
InduSoft Web Studio 33–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Viewing Your Application on the Web<br />
RUNNING THE TCP/IP CLIENT MODULE<br />
You can choose to run the module automatically. Select Project → Status, Runtime Tasks Table, and enter<br />
TCP/IP Client. After running this program, a small icon will display in your system tray.<br />
Setting Custom Parameters<br />
You can configure the following parameters for the Application Configuration (.app) file:<br />
[TCP] Port:<br />
TCP/IP port number. Default is 1234. This parameter should be the same in both the client and server<br />
machines.<br />
SendPeriod:<br />
Time in milliseconds before the client/server module will update the tag values of the other machine. Default<br />
is 250.<br />
ConnectRetryTimeout:<br />
Time in seconds before the client should retry to connect to the server. Default is 30. Only the client module<br />
uses the ConnectionRetryTimeout.<br />
33–2 InduSoft Web Studio
Exercise: Viewing Your Application on the Web<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Notes<br />
InduSoft Web Studio 33–3
Chapter 34.<br />
System Level Redundancy<br />
In this section, we will cover system level redundancy. Database redundancy and Web Server/Data Server<br />
redundancy have been covered previously.<br />
System level redundancy is simply an extension of a Thick Client application, combined with some Script (e.g.<br />
VBScript in a Background Script) along with the Scheduler. To implement System-level redundancy (of <strong>IWS</strong><br />
Servers), you will need two or more <strong>IWS</strong> Servers with identical applications. To illustrate how this works,<br />
consider the following:<br />
Server 1<br />
TCP/IP Client<br />
TCP/IP Server<br />
Communications<br />
Server 2<br />
TCP/IP Server<br />
TCP/IP Client<br />
Communications<br />
PLC<br />
We have two <strong>IWS</strong> Servers (Server 1 and Server 2), each with the same application. These are common<br />
elements between the two Servers applications:<br />
• Server 1 knows the IP address for Server 2<br />
• Server 2 knows the IP address for Server 1<br />
• Server 1 and Server 2 have a Scheduler function to create a “heartbeat” that will be enabled if the<br />
Server is the Primary<br />
• Server 1 has a TCP/IP Client Worksheet to check the heartbeat of Server 2. This will be triggered<br />
periodically if Server 1 is the Hot Standby.<br />
• Server 2 has a TCP/IP Client Worksheet to check the heartbeat of Server 1. This will be triggered<br />
periodically if Server 2 is the Hot Standby.<br />
• Server 1 has a TCP/IP Client Worksheet to read the application tags of Server 2. This will be enabled if<br />
Server 1 is the Hot Standby<br />
• Server 2 has a TCP/IP Client Worksheet to read the application tags of Server 1. This will be enabled if<br />
Server 2 is the Hot Standby<br />
• Both Server 1 and Server 2 have Communication Worksheet(s) to read from the PLCs, but only the<br />
Primary will have the Communication Worksheets enabled.<br />
To implement System-level redundancy, the following logic sequence must take place<br />
• The first Server to power-up checks to see if another Server is running, If not, it will asserts itself as the<br />
Primary. If there is a Master already running (with a heartbeat), the Server asserts itself as the Hot<br />
Standby<br />
• The Hot Standby periodically checks the heartbeat of the Primary. If it goes away, the Hot Standby<br />
asserts itself as the Master.<br />
InduSoft Web Studio 34–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Viewing Your Application on the Web<br />
Using this scenario, each Server is running the same application but one Server (the Primary) is getting the<br />
data from “real world” devices while the other Server (the Hot Standby) is getting data from the Tags Database<br />
of the Primary. The redundancy switch-over time is a function of the heartbeat rate and the frequency of the Hot<br />
Standby Server checking the heartbeat of the Master.<br />
Each Thick Client will appear as though it is operationally controlling (monitoring) the machine or process, while<br />
in reality only one Server is communicating with the real-world devices.<br />
34–2 InduSoft Web Studio
Exercise: Viewing Your Application on the Web<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Notes<br />
InduSoft Web Studio 34–3
Chapter 35.<br />
FTP<br />
<strong>IWS</strong> supports FTP (File Transfer Protocol) via <strong>IWS</strong> built-in functions, allowing uploading or downloading of files<br />
to/from a remote FTP Server.<br />
FTP Server<br />
<strong>IWS</strong> Client<br />
The FTP Server<br />
A FTP Server is located in a remote PC with a TCP/IP connection to the <strong>IWS</strong> Server. The FTP Server provides<br />
the file transfer service through Microsoft IIS (Internet Information Services - FTP), or any one of several<br />
commercially available or freeware FTP Servers (e.g. FileZilla Server, zFTPServer)<br />
FTP is a TCP-based Service (exclusively), there is no UDP data component. On the PC that has the FTP<br />
Server, there are generally two ports dedicated to the FTP Server; a Command port (also known as a Control<br />
port) – usually port 21, and a Data Port – usually port 20 (for the Active Mode, may be another port number for<br />
the Passive Mode).<br />
With an Active Mode FTP, the Client (the <strong>IWS</strong> Application) uses an unprivileged port number N (N>1023) to<br />
connect to the FTP Server’s Command port (port 21). The Client then begins to listen on port N+1. The Client<br />
sends the Client N+1 port number to the FTP Server’s Command port, and the FTP Server will connect back to<br />
the Client’s specified Data port (N+1) from the FTP Server’s local port (Port 20).<br />
Server<br />
Client<br />
Port 20<br />
Data<br />
Port 21<br />
Command<br />
Port 1028<br />
Command<br />
Port 1029<br />
Data<br />
1<br />
2<br />
3<br />
4<br />
Active Mode FTP Connection Sequence<br />
InduSoft Web Studio 35–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Viewing Your Application on the Web<br />
The above diagram illustrates the connection sequence between the Client and the FTP Server:<br />
• Step 1<br />
In Step 1, the Client’s Command port (1028) connects to the FTP Server’ s Command Port (21) and<br />
sends the command Port 1029 (to specify the Client’s Data port to the FTP Server). The Client begins<br />
listening on Data port 1029.<br />
• Step 2<br />
The FTP Server sends an Ack to the Client’s Command port<br />
• Step 3<br />
The FTP Server initiates a connection from its local Data port (Port 20) to the Client’s specified Data<br />
port (Port 1029).<br />
• Step 4<br />
The Client sends an Ack to the Server’s Data port.<br />
Any Server-side Firewall needs to have the following ports opened:<br />
• Port 21 from anywhere (allowing a Client initiated connection)<br />
• Port 21 to Port N (the Client Command Port)<br />
• Port 20 to Port N+1 (the Client Data Port)<br />
• Port 20 from Port N+1<br />
An Active Mode FTP can create problems when there is a Firewall on the Client-side. Since it is the Server’s<br />
Data port (Port 21) connecting to the Client’s Data port (e.g. Port 1029), instead of the Client’s Data port making<br />
the connection to the FTP Server’s Data port, it appears to a Client-side Firewall that an outside system is<br />
initiating a connection to an internal client, and this will usually be blocked. This can be accommodated for by<br />
opening up the Data port on the Client side (via the Firewall).<br />
There is a Passive Mode FTP connection that can be used to resolve the problem of the FTP Server initiating<br />
the connection to the Client’s Data port. With a Passive Mode FTP, the Client initiates both connections to the<br />
Server. When the connection to the FTP Server is initiated, the Client will open up two ports, N (where N ><br />
1023) and N+1. The Client (on Port N) will connect to the FTP Server’s Command port (Port 20) and issue a<br />
Port command (specifying the Client’s Data Port). Next, the Client (from port N+1) will issue a Pasv to the FTP<br />
Server, which will open up a random unprivileged port (P > 1023) and send a Port P command back to the<br />
Client. The Client then initiates a connection from it’s Data port N+1 to the FTP Server’s port P to transfer files<br />
(data).<br />
Server<br />
Client<br />
Port 20<br />
Data<br />
Port 2020<br />
Data<br />
Port 21<br />
Command<br />
Port 1028<br />
Command<br />
Port 1029<br />
Data<br />
1<br />
2<br />
3<br />
4<br />
Passive Mode FTP Connection Sequence<br />
35–2 InduSoft Web Studio
Exercise: Viewing Your Application on the Web<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
The above diagram illustrates the connection sequence between the Client and the FTP Server:<br />
• Step 1<br />
In Step 1, the Client’s Command port (1028) connects to the FTP Server’ s Command Port (21) and<br />
sends the command Pasv command. The Client begins listening on Data port 1029.<br />
• Step 2<br />
The FTP Server sends a Port 2020 command (or another port number P) to the Client, telling the Client<br />
which port to listen for the Data connection<br />
• Step 3<br />
The Client initiates a connection from its local Data port (Port 1029) to the FTP Server’s specified Data<br />
port (Port 2020).<br />
• Step 4<br />
The FTP Server (Port 2020) sends an Ack to the Client’s Data port.<br />
Any Server-side Firewall needs to have the following ports opened:<br />
• Port 21 from anywhere (allowing a Client initiated connection)<br />
• Port 21 to Port N (the Client Command Port)<br />
• Port P (the Server Data Port) to remote Port N+1 (the Client Data Port)<br />
• Port P (the Server Data Port) from Port N+1<br />
While this Passive FTP Server solves the problems of the Client-side connection, it can open up other problem.<br />
That is the need to allow remote connections to high numbered ports on the FTP Server. This can be resolved<br />
by specifying the Port range the FTP Server is allowed to use.<br />
Notes:<br />
• Most Web Browsers only support Passive Mode FTP<br />
• Active Mode FTP does not function when used in conjunction with Client-side devices that implement<br />
NAT (Network Address Translation).<br />
• Active Mode FTP is beneficial to the administration of the FTP Server, but can impose problems at the<br />
Client<br />
• Passive Mode FTP is beneficial to the administration of the Client, but can impose problems at the FTP<br />
Server.<br />
• Port and Pasv commands actually send the IP address and the Port number .<br />
• For an <strong>IWS</strong> application, the Active Mode FTP should work sufficiently<br />
• See Microsoft Knowledge Base KB189262 for Passive Mode FTP with IIS<br />
InduSoft Web Studio 35–3
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Viewing Your Application on the Web<br />
Configuring <strong>IWS</strong> to work with the FTP Server<br />
<strong>IWS</strong> provides a built-in function to configure the FTP connection on the PC that is running <strong>IWS</strong>. This function is<br />
CN<strong>FF</strong>tp and is supported on Windows XP (NT, 2000, Server 2003, Vista), Windows CE and Web Thin Clients.<br />
You must configure the FTP Server connection prior to executing ftpPut or ftpGet.<br />
CN<strong>FF</strong>tp Function<br />
Usage CN<strong>FF</strong>tp(strServer, strUser, strPwd, numPassiveMode, numPort)<br />
Parameters strServer<br />
The FTP Server Name<br />
strUser<br />
The User Name. Default is “Anonymous”.<br />
strPwd<br />
The User Password. Default is blank<br />
numPassiveMode<br />
0 = Active Mode (default)<br />
1 = Passive Mode<br />
numPort<br />
The FTP Server’s Command (Control) Port number the FTP Client is to use. Default is 21<br />
Return Values 0 = Successful connection<br />
-1 = Invalid number of parameters<br />
-2 = Invalid Server Name<br />
-3 = Invalid User Name<br />
Example CN<strong>FF</strong>tp(“ftp.myFTPServer.com”, “admin”, “12345”) //Configures the FTP Connection for<br />
Active Mode<br />
Note:<br />
• The CNNFtp function does not establish a connection with the FTP Server. Instead, it defines the FTP<br />
Server/Client connection.<br />
Uploading and Downloading Files to/From an FTP Server<br />
Once the CN<strong>FF</strong>tp function has been executed (to specify the FTP Server/Client connection parameters), you<br />
are ready to upload or download files from the FTP Server. This is accomplished through the <strong>IWS</strong> built-in<br />
functions ftpGet (retrieves a file from the FTP Server) and ftpPut (sends a file to the FTP Server). Both the<br />
ftpGet and ftpPut functions execute asynchronously, so you may need to execute the <strong>IWS</strong> built-in function<br />
ftpStatus to determine the state of the transfer.<br />
The ftpGet function retrieves a file from the FTP Server and will store it in a local file.<br />
ftpGet Function<br />
Usage ftpGet(strRemoteFile, strLocalFile, numOverWrite, numTransferType)<br />
Parameters<br />
strRemoteFile<br />
This is a String Tag or Expression representing the fully qualified name of the remote file<br />
(as it is referenced on the FTP Server). The FTP Server will have a FTP Site Directory that<br />
will contain the files available for FTP, and may have a default file listing style<br />
(Windows/DOS or Unix). Some FTP Servers are case-sensitive.<br />
strLocalFile<br />
This is a String Tag or Expression representing the fully qualified name of the remote file<br />
(as it is referenced on the FTP Server). The FTP Server will have a FTP Site Directory that<br />
will contain the files available for FTP, and may have a default file listing style<br />
35–4 InduSoft Web Studio
Exercise: Viewing Your Application on the Web<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
(Windows/DOS or Unix).<br />
numOverWrite<br />
Defines whether a file is to be overwritten if it exists.<br />
0 = Do not overwrite. Error generated if the LocalFile already exists (default)<br />
1 = Overwrite<br />
numTransferType<br />
Defines the type of file being transferred<br />
0 = Unknown (default)<br />
1 = ASCII<br />
2 = Binary<br />
Returned Value 0 = Success<br />
1 = Failed to create FTP thread<br />
-1 = Invalid number of parameters<br />
-2 = Unknown system error<br />
-3 = Invalid remote file<br />
-4 = Invalid local file<br />
-5 = Invalid transfer type<br />
Example<br />
ftpGet(“\Reports\040307.txt”, “C:\Report040307.txt”)<br />
The ftpPut function stores a file on the FTP Server.<br />
ftpPut Function<br />
Usage ftpPut(strLocalFile, strRemoteFile, numTransferType)<br />
Parameters<br />
Returned Value<br />
Example<br />
strLocalFile<br />
This is the fully qualified name of the remote file (as it is referenced on the FTP Server).<br />
The FTP Server will have a FTP Site Directory where the files that are sent via FTP will be<br />
stored. The FTP Server may have a default file listing style (Windows/DOS or Unix).<br />
strRemoteFile<br />
This is a String Tag or Expression representing the fully qualified name of the remote file<br />
(as it is referenced on the FTP Server). The FTP Server will have a FTP Site Directory that<br />
will contain the files available for FTP, and may have a default file listing style<br />
(Windows/DOS or Unix). Some FTP Servers are case-sensitive.<br />
numTransferType<br />
Defines the type of file being transferred<br />
0 = Unknown (default)<br />
1 = ASCII<br />
2 = Binary<br />
0 = Success<br />
1 = Failed to create FTP thread<br />
-1 = Invalid number of parameters<br />
-2 = Unknown system error<br />
-3 = Invalid remote file<br />
-4 = Invalid local file<br />
-5 = Invalid transfer type<br />
ftpPut(“C:\Report040307.txt”, “\Reports\040307.txt”)<br />
InduSoft Web Studio 35–5
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Viewing Your Application on the Web<br />
The ftpStatus function returns the current status of an FTP transaction initiated by a ftpGet or ftpPut function.<br />
The ftpStatus function is required since the ftpGet and ftpPut functions operate asynchronously.<br />
ftpStatus Function<br />
Usage ftpStatus(strTagName)<br />
Parameters<br />
Returned Value<br />
strTagName<br />
This is a string expression representing the name of a String Tag that will receive a status<br />
description.<br />
0 = No transaction is being executed<br />
1 = Transaction executed successfully<br />
2 = Resolving Name<br />
3 = Name Resolved<br />
4 = Connecting to Server<br />
5 = Connected to Server<br />
6 = Closing Connection<br />
7 = Connection Closed<br />
8 = Sending Request<br />
9 = Request Sent<br />
10 = Receiving Response<br />
11 = Intermediate Response Received<br />
12 = Response Received<br />
13 = Request Completed<br />
-2 = Invalid opttagErrorDescription<br />
-6 = Error Opening Connection (see Status String for Details)<br />
-7 = Error Establishing Connection (see Status String for Details)<br />
-8 = Error receiving the file (see Status String for Details)<br />
-9 = Transfer Pending<br />
Example Tag Name Expression<br />
numStat ftpStatus(“strStatusDescription”)<br />
35–6 InduSoft Web Studio
Chapter 36.<br />
SNMP<br />
SNMP (Simple Network Management Protocol) is a new capability added to <strong>IWS</strong> Version 6.1 Service Pack 2.<br />
SNMP is an applications layer protocol used to facilitate the exchange of management information with network<br />
devices (e.g. Servers, Printers, Hubs, Switches, Routers) and network Administrators or network Management<br />
software. SNMP is part of the TCP/IP (Transmission Control Protocol/Internet Protocol) protocol suite.<br />
In a typical SNMP architecture, there are three major components; the Managed Devices, Agents, and the<br />
Network Management Systems.<br />
Managed Devices<br />
A Managed Device is a node on a managed network that contains an SNMP Agent and is performs<br />
some sort of function that can be configured or monitored by the Network Management Systems.<br />
Examples of Managed Devices include Servers (e.g. an <strong>IWS</strong> Server), Routers, Switches, Hubs, and<br />
Printers.<br />
Agents<br />
An Agent is a network management software module that resides on a Managed Device, and provides<br />
information about the Managed Device to the Network Management System in Management<br />
Information Bases (MIBs). The Agent responds to requests from the SNMP requestor (Network<br />
Management System, or Manager).<br />
Network Management Systems<br />
The Network Management System is a set of applications that monitor and control the Managed<br />
Devices. One or more Network Management Systems (or SNMP Manager(s)) can exist on any<br />
managed network.<br />
The SNMP Manager communicates with the Managed Device using Read and Write Commands. The Managed<br />
Device uses Trap Commands to asynchronously report events to the SNMP Manager when a specified Event<br />
occurs. A device can operate as an SNMP Manager, Agent or both.<br />
SNMP lacks any authentication capabilities, and is therefore vulnerable to a variety of security threats. Often,<br />
Managed Devices (and their Agents) will not implement any Set operations, thereby reducing SNMP to a<br />
monitoring function.<br />
SNMP with <strong>IWS</strong><br />
Using <strong>IWS</strong> or CEView, you can provide real-time data from the devices connected to the SCADA/HMI system<br />
through the native communication drivers and OPC interfaces e.g. from controllers, machines, etc.) to a thirdparty<br />
SNMP Manager, such as Microsoft Operations Manager (MOM), HP Openview, Novell NMS, IBM<br />
NetView, or Sun Net Manager. When used in this mode, <strong>IWS</strong> becomes the SNMP Agent, working as a gateway<br />
between the devices on the plant-floor and the corporative equipment management system (the SNMP<br />
Manager) at the ERP level.<br />
InduSoft Web Studio 36–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Viewing Your Application on the Web<br />
<strong>IWS</strong> can also be configured as an SNMP Manager, requesting data from third-party SNMP Agents and<br />
displaying this information through its graphical interface, locally or remotely to Thin Client stations.<br />
Installing SNMP<br />
The SNMP interface from <strong>IWS</strong> uses the standard SNMP Service from Microsoft. The installation procedure<br />
depends on the operating system where you install the system and some dialogs illustrated in this document<br />
may vary depending on the OS version/type that you are using.<br />
Installation on Microsoft Windows 2000, Windows XP or Windows 2003 Server<br />
• Step 1: Install the Microsoft SNMP Service<br />
Note: Follow the following procedures if Microsoft SNMP Service is not installed on your OS. You may<br />
need your Operating System CD-ROM for this procedure.<br />
Open the Control Panel (Start Control Panel) and double-click on the Add/Remote Programs<br />
icon. Select the option Add/Remove Windows Components, click on the Management and<br />
Monitoring Tools option and then click on the button Details. Check the option Simple Network<br />
Management Protocol, then click Ok and Next to install the Microsoft SNMP.<br />
• Step 2: Configure the Microsoft SNMP Service<br />
After installing the Microsoft SNMP Service, you must configure its settings. Open the Control Panel<br />
(Start Control Panel), double-click on the Administrative Tools icon and then double-click on the<br />
Services icon. Right-click on the SNMP Service name and click on Properties. Make sure that the<br />
Local System Account radio button is selected in the Log On tab.<br />
36–2 InduSoft Web Studio
Exercise: Viewing Your Application on the Web<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Select the Traps tab and add the Community Name called public (in case it does not exist yet) and add<br />
to the Trap destinations box the host name or IP address of the station(s) that must receive traps from<br />
the SNMP Agent (i.e. the host name or IP address of the station(s) where the SNMP Manager is<br />
running).<br />
Note:<br />
• The SNMP protocol supports “unsolicited messages” (traps) from the SNMP Agent to the SNMP<br />
Manager (e.g.: change os status, alarm condition, etc) in order to optimize the communication in the<br />
network.<br />
InduSoft Web Studio 36–3
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Viewing Your Application on the Web<br />
Select the Security tab and either select the option Accept SNMP packets from any host or select<br />
and option Accept SNMP packets from these hosts and add the list of host(s) where the SNMP<br />
Manager is running.<br />
• Step 3: Configure the InduSoft Web Studio SNMP Agent<br />
Open the Registry Editor (Start Run RegEdit). Select the key<br />
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SNMP\Parameters\ExtensionAge<br />
nts. This key lists the SNMP Agents linked to the Microsoft SNMP Service. Add a new String Value with<br />
the next sequential number available for the list and set its data value to SOFTWARE\Studio\SNMP.<br />
36–4 InduSoft Web Studio
Exercise: Viewing Your Application on the Web<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Next, create the Key HKEY_LOCAL_MACHINE\SOFTWARE\Studio\SNMP and add a new String<br />
value with the name Pathname, whose value must be set with the path of the Studio SNMP Agent DLL<br />
file (StudioSnmp.dll) – for example: c:\Program Files\InduSoft Web Studio v6.1\bin\StudioSnmp.dll.<br />
Close the Registry Editor.<br />
Open the ProgramSettings.INI file with a text editor (e.g.: Notepad). The ProgramSettings.INI file is<br />
located on the \BIN sub-folder of the Indusoft Web Studio installation path (e.g.: c:\Program<br />
Files\InduSoft Web Studio v6.1\bin\Program Settings.ini).<br />
Create the following settings in the Program Settings.INI file:<br />
[SNMP]<br />
OidEnterpriseNumber=26640<br />
TrapInterval=1<br />
ApplicationTcpPort=1234<br />
Save the changes and close the file editor.<br />
Notes:<br />
• OidEnterpiseNumber: Unique number, which defines the position in the SNMP tree where the Studio data<br />
will be exposed (.1.3.6.1.4.1.[OidEnterpriseNumber]). The Studio number is 26640.<br />
• TrapInterval: Interval (in seconds) used to send traps to the remote SNMP Manager(s). This parameter<br />
must be configured with a integer positive number. The default value is 1.<br />
• ApplicationTcpPort: TCP Port number used to exchange data with the TCP/IP Server task from InduSoft<br />
Web Studio. The default value is 1234.<br />
After configuring all settings, re-start the SNMP Service by rebooting the computer or by right-clicking<br />
on the SNMP Service ( _ Control Panel _ Administrative Tools _ Service) and clicking on the<br />
option Restart.<br />
Note:<br />
• The Studio SNMP Agent exchanges data with the TCP/IP Server task from InduSoft Web Studio.<br />
Therefore, the TCP/IP Server task MUST be running in order to provide data to the SNMP Agent module.<br />
Make sure to set the TCP/IP Server task to Automatic in the InduSoft Web Studio menu (Project <br />
Status.<br />
InduSoft Web Studio 36–5
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Viewing Your Application on the Web<br />
Installation on Microsoft Windows CE<br />
• Step 1: Install the Microsoft SNMP Service<br />
The SNMP Server must be previously enabled in the image of the Windows CE device. If your<br />
Windows CE device does not provide the SNMP Agent, please consult your hardware vendor and ask<br />
them to add this Service to the image of the device.<br />
• Step 2: Configure the InduSoft Web Studio (CEView) SNMP Agent<br />
Copy the following files into a non-volatile directory of the Windows CE device (preferentially, the same<br />
directory where CEView.exe is installed):<br />
- StudioSnmp.dll<br />
- StudioSnmpReg.exe<br />
Note:<br />
• The files mentioned above are stored in the following sub-folder after installing InduSoft Web Studio in<br />
your computer: \Redist\\ (e.g.: C:\Program Files\InduSoft Web Studio<br />
v6.1\Redist\Wince 4.0\x86). You can use the Send Files command from the Exeuction Environment<br />
dialog of InduSoft Web Studio to download these files to your Windows CE device.<br />
•<br />
Optionally, you ca create a text file with a Text Editor (e.g.: Notepad) and save it with the name<br />
StudioSnmpReg.ini. This file must follow the structure illustrated in the example below:<br />
[SNMP]<br />
SnmpAgentPath=<br />
ProductPath=<br />
OidEnterpriseNumber=<br />
ApplicationTcpPort=<br />
TrapInterval=<br />
SNMPDriverOrder=<br />
[Trap Destination]<br />
1=<br />
2=<br />
3=<br />
The StudioSnmpReg.ini file allows you to customize some settings before installing the Studio SNMP<br />
Agent on your Windows CE device. If this file does not exit, the Studio SNMP Agent is installed with the<br />
default settings as described in the following table:<br />
Key Default Value Description<br />
Key Default Value Description<br />
SnmpAgentPath Same directory where<br />
StudioSnmpReg.exe is executed<br />
Path where the StudioSnmp.dll is stored.<br />
ProductPath<br />
from.<br />
Same directory where<br />
StudioSnmpReg.exe is executed<br />
from.<br />
Path for the \BIN sub-folder of CEView (same folder<br />
where CEView.exe is stored)<br />
OidEnterpriseNumber 26640 Unique number, which defines the position in the<br />
SNMP tree where the Studio data will be exposed<br />
(.1.3.6.1.4.1.[OidEnterpriseNumber]).<br />
TrapInterval 1 Interval (in seconds) used to send traps to the<br />
remote SNMP Manager(s). This parameter must be<br />
configured with a integer positive number.<br />
ApplicationTcpPort 1234 TCP Port number used to exchange data with the<br />
TCP/IP Server task from InduSoft Web Studio.<br />
SNMPDriverOrder<br />
Order to load the SNMP Driver. Usually, this<br />
parameter is not required. Consult you software<br />
vendor if you have problems during the installation<br />
of the <strong>IWS</strong> SNMP Agent.<br />
36–6 InduSoft Web Studio
Exercise: Viewing Your Application on the Web<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
In addition to the parameters mentioned above, the Key [Trap Destination] list the Host Name or IP<br />
Address of the station(s) that must receive traps from the SNMP Agent. In other words, the host name<br />
or IP address of the station(s) where the SNMP Manager is running.<br />
Copy the StudioSnmpReg.ini (if any) to the same directory where the StudioSnmpReg.exe is stored (on<br />
the Windows CE device) and execute the StudioSnmpReg.exe program to install the Studio SNMP<br />
Agent on the Windows CE device. Wait until a message is displayed indicating the completion of the<br />
installation.<br />
Save the Registry and reboot the Windows CE device and the Studio SNMP Agent must be<br />
automatically loaded by the SNMP Service from the operating system.<br />
Notes:<br />
• It is strongly recommended copying the StudioSnmpReg.ini, StudioSnmpReg.exe and StudioSnmp.dll in<br />
the same directory where CEView.exe is stored (e.g.: \HardDisk\Studio\BIN\).<br />
• The Studio SNMP Agent exchanges data with the TCP/IP Server task from CEView. Therefore, the<br />
TCP/IP Server task MUST be running in order to provide data to the SNMP Agent module. Make sure to<br />
set the TCP/IP Server task to Automatic in the InduSoft Web Studio menu Project Status.<br />
• Step 3: Configure the InduSoft Web Studio (CEView) SNMP Agent<br />
The Studio SNMP Agent exposes data from the current application via the SNMP protocol. The Studio<br />
SNMP Agent has a unique ID number. Each data value exposed by the Studio SNMP Agent has an<br />
address (OID). The root of the OID space is .1.3.6.1.4.1.[EN] or<br />
(iso.org.dod.internet.private.enterprise.[EN]), where [EN] is the number configured in the parameter<br />
OidEnterpriseNumber of the file Program Settings.INI (Windows 2K/XP/2K3) or StudioSnmpReg.ini<br />
(Windows CE). By default, the EN number is 26640.<br />
The OIDs exposed by Studio SNMP Agent are listed below:<br />
Name OID Type Description<br />
Name OID Type Description<br />
studioVersion 1.3.6.1.4.1.[EN].1.1.0 String Studio version number<br />
studioLicense 1.3.6.1.4.1.[EN].1.2.0 String Studio license type<br />
applicationName 1.3.6.1.4.1.[EN].1.3.0. String Name of the application being executed by Studio<br />
applicationRevision 1.3.6.1.4.1.[EN].1.4.0 String Revision Number of the application being executed<br />
by Studio.<br />
tagTable 1.3.6.1.4.1.[EN].1.5 Table Table containing a list of the tags used in the current<br />
application and exposed to the SNMP Manger.<br />
The Table tagTable has 5 columns with the following information:<br />
Column Name De<br />
Column Name Description<br />
1 tagName String. The tag name.<br />
2 tagType String. The Tag Type (“bool”, “integer”, “real” or “string”).<br />
3 tagValue String. The current tag value.<br />
4 tagQuality String. The quality of the tag value. (“good” or “bad”).<br />
5 tagTrap String. A number that indicates if the tag fires a trap when its value changes. “1”<br />
means trap is active; “0” means trap is inactive.<br />
You must configure the tags that will be exposed by the Studio SNMP Agent (by default, no tags are<br />
exposed). In order to configure the tags that will be exposed by the Studio SNMP Agent, just create a<br />
Text File with the CSV (Comma Separated Value) format. The file name must be SNMP.csv and it must<br />
be saved in the \Config sub-folder of your application.<br />
InduSoft Web Studio 36–7
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Viewing Your Application on the Web<br />
You can configure one tag in each line of the file, according to the following syntax:<br />
TagName, Trap<br />
Where:<br />
- TagName: Name of the tag that will be exposed by the Studio SNMP Agent.<br />
- Trap: Flag indicating if the Studio SNMP Agent must generate traps when this tag changes of<br />
value (0=trap disabled; 1=trap enabled).<br />
The following example illustrates a valid SNMP.CSV file, which makes three tags available to remote<br />
SNMP Manager (TagLevel, Alarm and Second) and generates traps automatically when the tag Alarm<br />
changes of value.<br />
TagLevel,0<br />
Alarm,1<br />
Second.0<br />
36–8 InduSoft Web Studio
Chapter 37.<br />
Using the Remote Agent<br />
After configuring an application and testing it locally (on your development workstation), you can download the<br />
application to a remote run-time workstation that is running under Windows NT/2000/XP or CEView under<br />
Windows CE.<br />
Exercise: Configuring the Remote Agent<br />
Before you begin, verify that the Remote Agent (CEServer.exe) is running on the remote target<br />
workstation.<br />
Note:<br />
The CESERVER.EXE file is located in the following directory on Windows<br />
NT/2000/XP computers:<br />
\InduSoft Web Studio\Redist\CEView\\BIN<br />
The file should be located in the \ folder on WinCE device.<br />
Run the CEServer.exe to launch the Remote Agent dialog on the remote workstation.<br />
Remote Agent Dialog<br />
Click the Setup button in the Remote Agent dialog on the run-time workstation.<br />
When the Setup dialog opens, specify the device connection method (Serial or TCP/IP) for connecting<br />
to the development workstation.<br />
Remote Agent Setup Dialog<br />
InduSoft Web Studio 37–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Exercise: Configuring the Remote Agent<br />
Note:<br />
We recommend using TCP/IP instead of Serial Link for performance reasons.<br />
Click OK to close the Setup dialog, but leave the Remote Agent program running in the remote<br />
workstation.<br />
Select Project → Execution Environment from <strong>IWS</strong> (on the development workstation).<br />
Execution Environment Dialog<br />
Specify a link type for the Target Station (Network IP or Serial Port). If you select<br />
Network IP, type the IP address of the remote workstation into the text box.<br />
Specifying Link Type and IP Address<br />
Click the Connect button to connect to the remote workstation.<br />
Note:<br />
If the remote workstation is a WinCE device, you can click on the Install System<br />
Files button to download the CEView runtime files to the remote workstation.<br />
In the Workspace window, select the Application tab and click the Send to Target button to download<br />
the application to the remote workstation.<br />
After downloading all application files, click the Run button to execute the application in the remote<br />
target workstation.<br />
37–2 InduSoft Web Studio
Downloading a CEView Application<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Downloading a CEView Application<br />
You must use the Project Settings dialog to configure the CEServer.EXE for TCP/IP communications<br />
before running your CE unit.<br />
In the development environment (on the development workstation), click the Execution Environment<br />
button.<br />
When the Execution Environment dialog displays, type the IP address of the CE unit, and then click the<br />
Connect button.<br />
Execution Environment Dialog<br />
When the Status field display indicates that you are connected, click the Install system files button to<br />
install the CEView on the remote workstation.<br />
After installing CEView, click the Application tab.<br />
Click the Application Tab<br />
InduSoft Web Studio 37–3
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Downloading a CEView Application<br />
Click the Browse button, located next to the Target field, when the Browse Target dialog displays, and<br />
choose the remote directory where you will download the application.<br />
Select the Remote Directory<br />
Click the Send to Target button to download the application. Note: The CE unit must be running<br />
CEServer.exe.<br />
After downloading the application, you can click the Run button to start the application and click Stop to<br />
stop the application while connected to the CE unit.<br />
The Status field displays the last operation status.<br />
Other notes:<br />
A. Remote Agent – CEServer<br />
• Needs to be installed on the target machine<br />
• Can be used for Windows XP/2000/NT machines or Windows CE<br />
• Note: Windows CE-based systems may not automatically update the system registry following<br />
a file download. If not, the registry must be updated (saved) manually using CECP, SaveReg,<br />
RegSave or some other utility provided by the hardware manufacturer.<br />
B. Allows download of system files, application and license files<br />
• License information embedded in registry<br />
• Application and system files installed in same directory as CEServer<br />
37–4 InduSoft Web Studio
Downloading a CEView Application<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Notes<br />
InduSoft Web Studio 37–5
Chapter 38. Runtime Configuration<br />
After configuring an application and testing it locally (on your development workstation), you can download the<br />
application to a remote run-time workstation that is running under Windows NT/2000/XP or CEView under<br />
Windows CE.<br />
Automatic booting of application at runtime<br />
For XP/2000/NT-based systems: Put a shortcut to RunStartUp (in <strong>IWS</strong> \Bin folder) into the<br />
Windows StartUp folder.<br />
For CE-based systems: Under Path:\\ put CE_Start.exe and CE_Start.ini into this<br />
folder. When the WinCE device launches, it executes the file in CE_Start.ini. This file needs to be<br />
provided by the hardware manufacturer, and is not provided by InduSoft. Another file in this folder<br />
is CEApp.ini, which contains the path of the InduSoft application. This file is updated by InduSoft<br />
Remote Agent. See ImageforCEView Technote.<br />
InduSoft Web Studio 38–1
Appendix A. VBScript Examples<br />
The following are examples of VBScript code used with <strong>IWS</strong> for various purposes.<br />
Using WSDL & SOAP (Windows XP)<br />
WSDL (Web Services Description Language, pronounced “”wiz-dull”) is an XML-based language used for<br />
communication of data with Web-based services. It is generally used in conjunction with SOAP and XML<br />
Schema to provide web services over an Internet connection. The Client device connects to the web service,<br />
and can read the WSDL to determine what functions are available on the Server. Any special data types used<br />
are embedded in the WSDL file in the form of XML Schema. The client can then use SOAP to actually call one<br />
of the functions listed in the WSDL.<br />
SOAP (Simple Object Access Protocol) is a protocol used for exchanging XML-based messages over a<br />
computer network, normally using HTTP (can also work with SMTP). SOAP is often used with Web Services.<br />
This application calls a Web Service to convert between temperatures (C F, FC)<br />
$tempC = 37<br />
Set oXML = CreateObject("MSSOAP.SoapClient")<br />
oXML.ClientProperty ("ServerHTTPRequest") =True<br />
WSDL = "http://developerdays.com/cgi-bin/tempconverter.exe/wsdl/ITempConverter"<br />
oXML.mssoapinit WSDL<br />
$tempF = oXML.CtoF (CInt($tempC))<br />
Set oXML = Nothing<br />
This application calls a Web Service to generate random lottery<br />
If $trigger_flag = 1 Then<br />
$trigger_flag = 0<br />
WSDL = "http://reto.checkit.ch/scripts/lotto.dll/wsdl/IgetNumbers"<br />
lotto_min = 1<br />
lotto_max = 48<br />
lotto_number = 6<br />
lotto_count = 1<br />
Set oXML = CreateObject("MSSOAP.SoapClient")<br />
oXML.ClientProperty ("ServerHTTPRequest") =True<br />
oXML.mssoapinit WSDL<br />
$lotto_result = oXML.getLottoNumbers (lotto_min, lotto_max, lotto_number, lotto_count)<br />
Set oXML = Nothing<br />
End If<br />
InduSoft Web Studio A–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Using the WSHShell Object (Windows XP)<br />
Using the WSHShell Object (Windows XP)<br />
WSH (Windows Scripting Host) allows you to run Command Line tools (via the Shell Object) similar to<br />
CMD.exe, and to conduct system administration tasks (via COM Objects). WSHShell can provide access to the<br />
System Registry, environmental variables, location of System Folders and start Processes.<br />
Dim WSHShell<br />
Set WSHShell = CreateObject("WScript.Shell")<br />
' Define the path for the special folder<br />
MsgBox WSHShell.SpecialFolders("Startup")<br />
' Allows access to System environment variables, Types are System, User, Volatile or Process<br />
Set WSHEnv = WSHShell.Environment("System")<br />
MsgBox WSHEnv("Path")<br />
MsgBox WSHEnv("Processor_Architecture")<br />
' Runs an application and send the application keystrokes (as if they were typed<br />
WSHShell.Run ("%windir%\notepad.exe")<br />
WSHShell.AppActivate "Notepad"<br />
' Puts Data in the Application<br />
WSHShell.SendKeys "Hello World"<br />
WSHShell.SendKeys "{Enter}"<br />
Set WSHNetwork = CreateObject("WScript.Network")<br />
msg = "UserName:" & WSHNetwork.Username & vbCrLf<br />
msg = msg & "ComputerName:" & WSHNetwork.ComputerName & vbCrLf<br />
' msg = msg & "Domain:" & WSHNetwork.Domain & vbCrLf<br />
MsgBox msg<br />
The following example is from Microsoft and has not yet been tested<br />
This WSH script uses ADSI, (Active Directory) to create a new User Account<br />
Set objOU = Wscript.GetObject("LDAP://OU=management,dc=fabrikam,dc=com")<br />
Set objUser = objOU.Create("User", "cn=MyerKen")<br />
objUser.Put "sAMAccountName", "myerken"<br />
objUser.SetInfo<br />
A–2 InduSoft Web Studio
Using the Windows Shell (Windows XP)<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Using the Windows Shell (Windows XP)<br />
Windows also provides a Shell.LocalMachine COM class that allows access to information about your local PC.<br />
Dim objComputer, msg<br />
Set objComputer = CreateObject("Shell.LocalMachine")<br />
msg = ""<br />
msg = msg & "Computer name: " & objComputer.MachineName & vbCrLf<br />
msg = msg & "Shutdown allowed: " & objComputer.IsShutdownAllowed & vbCrLf<br />
msg = msg & "Friendly UI enabled: " & objComputer.IsFriendlyUIEnabled & vbCrLf<br />
msg = msg & "Guest access mode: " & objComputer.IsGuestAccessMode & vbCrLf<br />
msg = msg & "Guest account enabled: " & objComputer.IsGuestEnabled(0) & vbCrLf<br />
msg = msg & "Multiple users enabled: " & objComputer.IsMultipleUsersEnabled & vbCrLf<br />
msg = msg & "Offline files enabled: " & objComputer.IsOfflineFilesEnabled & vbCrLf<br />
msg = msg & "Remote connections enabled: " & objComputer.IsRemoteConnectionsEnabled &_ vbCrLf<br />
msg = msg & "Undock enabled: " & objComputer.IsUndockEnabled & vbCrLf<br />
MsgBox msg<br />
InduSoft Web Studio A–3
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Using the WinMgmts and WMIServices Object (Windows XP)<br />
Using the WinMgmts and WMIServices Object (Windows XP)<br />
WMI (or Windows Management Instrumentation) provides an interface between an <strong>IWS</strong> application and the<br />
Operating System (Windows 2000/XP/Server 2003/Vista). It is not fully supported on Windows NT, and not<br />
supported on Windows CE. WMI is Microsoft’s implementation of the Common Information Model (CIM)<br />
initiative, promoted by an association of vendors including Microsoft, Cisco, and HP. WMI exposes a collection<br />
of COM (Component Object Modules) modules to a Scripting language such as VBScript. It support access to<br />
local and remote computers.<br />
You can use WMI to access and manipulate basic system settings (e.g what would be available through the<br />
Control Panel), display and control the hardware attached to the computer, and display security settings (e.g.<br />
firewall).<br />
Dim objWMIService, objWMIService2, objService, objComputer, objCSItem, objOS, objOSItem<br />
Dim objItem, objOperatingSystem<br />
Dim colSettings colOSes, colOSItems, colServices, colCSItems, colItems, colSettings<br />
Dim msg, strComputer<br />
strComputer = "."<br />
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & _<br />
strComputer & "\root\cimv2")<br />
'Verify if SQL is installed on this PC<br />
Set colServices = objWMIService.ExecQuery ("Select * from Win32_Service Where Name =_ 'MSSQLServer'")<br />
If colServices.Count > 0 Then<br />
For Each objService In colServices<br />
MsgBox "SQL Server is " & objService.State & "."<br />
Next<br />
Else<br />
MsgBox "SQL Server is not installed on this computer."<br />
End If<br />
msg = ""<br />
Set colSettings = objWMIService.ExecQuery ("Select * from Win32_ComputerSystem")<br />
For Each objComputer In colSettings<br />
msg = msg & "System Name: " & objComputer.Name & vbCrLf<br />
msg = msg & "Total Physical Memory: " & objComputer.TotalPhysicalMemory & vbCrLf<br />
Next<br />
Set colOSes = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")<br />
For Each objOS In colOSes<br />
msg = msg & "Computer Name: " & objOS.CSName & vbCrLf<br />
msg = msg & "Caption: " & objOS.Caption & vbCrLf 'Name<br />
msg = msg & "Version: " & objOS.Version & vbCrLf 'Version & build<br />
msg = msg & "Build Number: " & objOS.BuildNumber & vbCrLf 'Build number<br />
msg = msg & "Build Type: " & objOS.BuildType & vbCrLf ' Build type<br />
msg = msg & "OS Type: " & objOS.OSType & vbCrLf<br />
msg = msg & "Other Type Description: " & objOS.OtherTypeDescription & vbCrLf<br />
msg = msg & "Service Pack: " & objOS.ServicePackMajorVersion & "." & objOS.ServicePackMinorVersion &<br />
vbCrLf<br />
Next<br />
Set objWMIService2 = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")<br />
Set colCSItems = objWMIService2.ExecQuery("SELECT * FROM Win32_ComputerSystem")<br />
For Each objCSItem In colCSItems<br />
msg = msg & "Total Physical Memory: " & objCSItem.TotalPhysicalMemory & vbCrLf<br />
A–4 InduSoft Web Studio
Using the WinMgmts and WMIServices Object (Windows XP)<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Next<br />
Set colOSItems = objWMIService2.ExecQuery("SELECT * FROM Win32_OperatingSystem")<br />
For Each objOSItem In colOSItems<br />
msg = msg & "Free Physical Memory: " & objOSItem.FreePhysicalMemory & vbCrLf<br />
msg = msg & "Total Virtual Memory: " & objOSItem.TotalVirtualMemorySize & vbCrLf<br />
msg = msg & "Free Virtual Memory: " & objOSItem.FreeVirtualMemory & vbCrLf<br />
msg = msg & "Total Visible Memory Size: " & objOSItem.TotalVisibleMemorySize & vbCrLf<br />
Next<br />
MsgBox msg<br />
Set objWMIService = GetObject("winmgmts:" _<br />
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")<br />
strComputer = "."<br />
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" _<br />
& strComputer & "\root\cimv2")<br />
Set colSettings = objWMIService.ExecQuery ("Select * from Win32_OperatingSystem")<br />
For Each objOperatingSystem In colSettings<br />
MsgBox "Available Physical Memory: " & objOperatingSystem.FreePhysicalMemory<br />
Next<br />
strComputer = "."<br />
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")<br />
Set colItems = objWMIService.ExecQuery("Select * from Win32_CDROMDrive")<br />
msg = ""<br />
For Each objItem In colItems<br />
msg = msg & "Device ID: " & objItem.DeviceID & vbCrLf<br />
msg = msg & "Description: " & objItem.Description & vbCrLf<br />
msg = msg & "Name: " & objItem.Name & vbCrLf<br />
Next<br />
MsgBox msg<br />
This example displays each System-level Service and it’s status<br />
strComputer = "."<br />
Set objSWbemServices = GetObject("winmgmts:\\" & strComputer)<br />
Set colSWbemObjectSet = objSWbemServices.InstancesOf("Win32_Service")<br />
For Each objSWbemObject In colSWbemObjectSet<br />
s = "Display Name: " & objSWbemObject.DisplayName & vbCrLf &<br />
" State: " & objSWbemObject.State & vbCrLf & _<br />
" Start Mode: " & objSWbemObject.StartMode<br />
MsgBox s<br />
Next<br />
InduSoft Web Studio A–5
Using CDO (Windows XP)<br />
CDO (or Collaboration Data Objects) is a Microsoft technology for building messaging (Email) or collaboration<br />
application. Several components are included with Microsoft Windows (2000, NT, XP) while others are only<br />
included with Microsoft Exchange. The following example will send an email.<br />
Const cdoSendUsingMethod= "http://schemas.microsoft.com/cdo/configuration/sendusing"<br />
Const cdoSendUsingPort = 2<br />
Const cdoSMTPServer = "http://schemas.microsoft.com/cdo/configuration/smtpserver"<br />
Const cdoSMTPServerPort = "http://schemas.microsoft.com/cdo/configuration/smtpserverport"<br />
Const cdoSMTPConnectionTimeout = _<br />
"http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout"<br />
Const cdoSMTPAuthenticat = "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"<br />
Const cdoBasic = 1<br />
Const cdoSendUserName = "http://schemas.microsoft.com/cdo/configuration/sendusername"<br />
Const cdoSendPassword = "http://schemas.microsoft.com/cdo/configuration/sendpassword"<br />
Dim objConfig<br />
Dim objMessage<br />
Dim Fields<br />
'CDO.Configuration<br />
'CDO.Message<br />
'ADODB.Fields<br />
' Get a handle on the config object and it's fields<br />
Set objConfig = CreateObject("CDO.Configuration")<br />
Set Fields = objConfig.Fields<br />
' Set config fields we care about<br />
With Fields<br />
' .Item(cdoSendUsingMethod) = cdoSendUsingPort<br />
.Item(cdoSMTPServer)<br />
= "smtp.ameritech.yahoo.com"<br />
.Item(cdoSMTPServerPort) = 25<br />
.Item(cdoSMTPConnectionTimeout) = 10<br />
.Item(cdoSMTPAuthenticate) = cdoBasic<br />
.Item(cdoSendUserName)<br />
= "name@ameritech.net"<br />
.Update<br />
End With<br />
.Item(cdoSendPassword)<br />
Set objMessage = CreateObject("CDO.Message")<br />
Set objMessage.Configuration = objConfig<br />
= "password"<br />
With objMessage<br />
.To = "name@indusoft.com"<br />
.From = "Display Name "<br />
.Subject = "SMTP Relay Test"<br />
.TextBody = "SMTP Relay Test Sent @ " & Now()<br />
.Send<br />
End With<br />
Set Fields = Nothing<br />
Set objMessage = Nothing<br />
Set objConfig = Nothing<br />
InduSoft Web Studio A–1
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Using Office <strong>Automation</strong> (Windows XP)<br />
Using Office <strong>Automation</strong> (Windows XP)<br />
While VBA is typically used to automation Microsoft Office applications, VBScript can do the job as well. This<br />
(lengthy) application that reads data from a Microsoft Access Database, uses the data to populate an Excel<br />
Spreadsheet, generate a Graph of the data, send the Graph as an picture object to Microsoft Word and print a<br />
report.<br />
Const xlPrimary = 1<br />
Const xlCategory =1<br />
Const xlValue = 2<br />
Const xlLocationAsNewSheet=1<br />
Const wdOrientPortrait = 0<br />
Const wdOrientLandscape = 1<br />
Const wdPrinterDefaultBin = 0<br />
Const wdSectionNewPage = 2<br />
Const wdAlignVerticalTop = 0<br />
Const wdAlignParagraphLeft = 0<br />
Const wdAlignParagraphCenter = 1<br />
Const wdAlignParagraphRight = 2<br />
Const wdAlignParagraphFull = 1<br />
Const wdMainTextStory = 1<br />
Const wdVerticalPositionRelativeToPage = 6<br />
Const xlLine = 4<br />
Const adOpenKeyset = 1<br />
Const adLockOptimistic = 3<br />
Const adUseServer = 2<br />
Dim xlsapp, xlsBook, xlsdoc, xlschart, db<br />
Dim xlsAxisCategory, xlsAxisValue, xlsSeries<br />
Dim fso, rc<br />
Dim strConn<br />
Dim strPathToMDB, myStr<br />
Dim strSQL<br />
Dim DBRowCount<br />
Dim OldMyDbRead1Line<br />
Sub MSAccessReadDB(TableNum)<br />
strPathToMDB = $InfoAppDir() & "\Data\MyDB.mdb"<br />
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & strPathToMDB & ";"<br />
Set db = CreateObject ("ADODB.Connection")<br />
db.open strConn<br />
If TableNum = 0 Then strSQL = "Select * From Table1" ' read from table 1<br />
If TableNum = 1 Then strSQL = "Select * From Table2" ' read from table 2<br />
Set rs = db.Execute (strSQL)<br />
DbRowCount = -1<br />
While Not rs.EOF<br />
DbRowCount = DbRowCount + 1<br />
$ProdStat[DbRowCount].Time= CStr(rs("Time"))<br />
$ProdStat[DbRowCount].Total = CInt(rs("Total"))<br />
$ProdStat[DbRowCount].Good = CInt(rs("Good"))<br />
$ProdStat[DbRowCount].Marginal = CInt(rs("Marginal"))<br />
$ProdStat[DbRowCount].Bad = CInt(rs("Bad"))<br />
rs.MoveNext<br />
Wend<br />
db.close<br />
Set db = Nothing<br />
A–2 InduSoft Web Studio
Using Office <strong>Automation</strong> (Windows XP)<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
End Sub<br />
Function InchesToPoints(Inches)<br />
InchesToPoints = Inches * 72<br />
End Function<br />
'This procedure is executed just once when this screen is open.<br />
Sub Screen_OnOpen()<br />
$MyReportLine = 1<br />
$MyDbRead1Line = 0<br />
OldMyDbRead1Line = $MyDbRead1Line<br />
MSAccessReadDB($MyDbRead1Line)<br />
$myProdName[0] = "Batch 1234"<br />
$myProdName[1] = "Batch ABCD"<br />
End Sub<br />
'This procedure is executed continuously while this screen is open.<br />
Sub Screen_WhileOpen()<br />
If $MyDBRead = 1 Then ' Read the CSV file<br />
$MyDBRead = 0<br />
myFolder = $InfoAppDir() & "\Data"<br />
strConn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & myFolder & ";"<br />
strConn = strConn & "Extended Properties=""text;HDR=Yes;FMT=CSVDelimited"""<br />
Set Conn = CreateObject("ADODB.Connection")<br />
Conn.open = strConn<br />
Set rs = CreateObject("ADODB.Recordset")<br />
strSql = "Select * FROM MyData.txt"<br />
Set rs = Conn.Execute(strSql)<br />
recStr=""<br />
Do Until rs.EOF<br />
recStr = recStr & "value1= " & rs.Fields.Item("val1")<br />
recStr = recStr & " val2= " & rs.Fields.Item("val2")<br />
recStr = recStr & " val3= " & rs.Fields.Item("val3") & vbCrLf<br />
rs.Movenext<br />
Loop<br />
MsgBox recStr<br />
rs.close<br />
Conn.close<br />
Set rs = Nothing<br />
Set Conn = Nothing<br />
End If<br />
' The example below calls a routine that reads from a MS Access file and stores the information into a Class tag<br />
' The class tag is then displayed in a Grid Object on the Screen<br />
If OldMyDbRead1Line $MyDbRead1Line Then ' Check for a change in the radio button being pressed to<br />
read a different table<br />
OldMyDbRead1Line = $MyDbRead1Line<br />
MSAccessReadDB(CInt($MyDbRead1Line))<br />
End If<br />
' The code below generates a sample production report using MS Word. Production data is put into an<br />
InduSoft Web Studio A–3
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Using Office <strong>Automation</strong> (Windows XP)<br />
' Excel chart and the chart is copied into the Word document<br />
If $genReport = 1 Then ' see if the report key has been set<br />
$genReport = 0<br />
' Yes. Reset the key and generate the report.<br />
Set fso = CreateObject("Scripting.FileSystemObject")<br />
WordName = $InfoAppDir() & "\Data" & "\MyNewReport.doc"<br />
XLSName = $InfoAppDir() & "\Data" & "\MyNewChart.xls"<br />
If fso.fileexists(WordName) Then fso.deletefile WordName<br />
If fso.fileexists(XLSName) Then fso.deletefile XLSName<br />
Set xlsapp = CreateObject("Excel.Application")<br />
Set xlsBook = xlsapp.Workbooks.Add<br />
Set xlsdoc = xlsBook.Worksheets.Add<br />
xlsdoc.name = "Production Data"<br />
Set xlschart = xlsBook.Charts.Add<br />
xlschart.name = "Production Chart"<br />
xlsapp.visible = True<br />
strPathToMDB = $InfoAppDir() & "\Data" & "\MyDB.mdb"<br />
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & strPathToMDB & ";"<br />
Set db = CreateObject ("ADODB.Connection")<br />
db.open strConn<br />
If $MyReportLine = 1 Then<br />
strSQL = "Select * From Table1" ' read from table 1<br />
$FixTable = "Table1"<br />
End If<br />
If $MyReportLine = 2 Then<br />
strSQL = "Select * From Table2" ' read from table 2<br />
$FixTable = "Table2"<br />
End If<br />
Set rs = db.Execute (strSQL)<br />
$line_total = 0<br />
$line_good = 0<br />
$line_marginal = 0<br />
$line_bad = 0<br />
With xlsdoc<br />
row_val = 1 ' Add Column headers<br />
.Range("A" & CStr(row_val)).Value = "Production ID"<br />
.Range("C" & CStr(row_val)).Value = $myProdName[$MyReportLine]<br />
row_val = 3 ' Add Column headers<br />
.Range("A" & CStr(row_val)).Value = "Time"<br />
.Range("B" & CStr(row_val)).Value = "Total"<br />
.Range("C" & CStr(row_val)).Value = "Good"<br />
.Range("D" & CStr(row_val)).Value = "Marginal"<br />
.Range("E" & CStr(row_val)).Value = "Bad"<br />
row_val = 4<br />
While Not rs.EOF<br />
' Fill cells with values to build chart<br />
.Range("A" & CStr(row_val)).Value = CStr(rs("Time"))<br />
$line_total = $line_total + rs("Total")<br />
.Range("B" & CStr(row_val)).Value = CInt(rs("Total"))<br />
$line_good = $line_good + rs("Good")<br />
A–4 InduSoft Web Studio
Using Office <strong>Automation</strong> (Windows XP)<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
.Range("C" & CStr(row_val)).Value = CInt(rs("Good"))<br />
$line_marginal = $line_marginal + rs("Marginal")<br />
.Range("D" & CStr(row_val)).Value = CInt(rs("Marginal"))<br />
$line_bad = $line_bad + rs("Bad")<br />
.Range("E" & CStr(row_val)).Value = CInt(rs("Bad"))<br />
row_val = row_val +1<br />
rs.MoveNext<br />
Wend<br />
End With<br />
db.close<br />
Set db = Nothing<br />
' Set chart parameters<br />
Set xlsSeries = xlschart.SeriesCollection<br />
With xlschart<br />
.ChartType = xlLine<br />
' Set type of chart we want (XL Line)<br />
.SetSourceData(xlsdoc.Range("A4:E" & row_val-1)) ' Range from where the chart will be built<br />
Set xlsAxisCategory = .Axes (, xlPrimary)<br />
xlsAxisCategory.Item(xlCategory).HasTitle = True<br />
xlsAxisCategory.Item(xlCategory).AxisTitle.Characters.Text = "Time"<br />
xlsAxisCategory.Item(xlCategory).HasMajorGridlines = True<br />
xlsAxisCategory.Item(xlCategory).HasMinorGridlines = False<br />
Set xlsAxisValue = .Axes(, xlPrimary)<br />
xlsAxisValue.Item(xlValue).HasTitle = True<br />
xlsAxisValue.Item(xlValue).AxisTitle.Characters.Text = "Widgets Production - Line #" &_<br />
$MyReportLine<br />
xlsAxisValue.Item(xlValue).HasMajorGridlines = True<br />
xlsAxisValue.Item(xlValue).HasMinorGridlines = False<br />
.PlotArea.Interior.ColorIndex = 2<br />
.ChartArea.Interior.ColorIndex = 2<br />
.ChartArea.Interior.PatternColorIndex = 1<br />
xlsSeries.Item(1).Name = "Total Production"<br />
xlsSeries.Item(2).Name = "Total Good"<br />
xlsSeries.Item(3).Name = "Total Marginal"<br />
xlsSeries.Item(4).Name = "Total Bad"<br />
.Location(xlLocationAsNewSheet)<br />
xlsBook.SaveAs(XLSName)<br />
End With<br />
Dim app, doc, myRange, mydoc, vert_pos<br />
Set app = CreateObject ("Word.Application")<br />
Set doc = app.Documents.Add<br />
app.Visible = True<br />
' Set up Report Page<br />
With app.ActiveDocument.PageSetup<br />
.LineNumbering.Active = False<br />
.Orientation = wdOrientPortrait<br />
.TopMargin = InchesToPoints(0.5)<br />
.BottomMargin = InchesToPoints(0.5)<br />
.LeftMargin = InchesToPoints(0.7)<br />
.RightMargin = InchesToPoints(0.7)<br />
.Gutter = InchesToPoints(0)<br />
.HeaderDistance = InchesToPoints(0.5)<br />
.FooterDistance = InchesToPoints(0.5)<br />
.PageWidth = InchesToPoints(8.5)<br />
InduSoft Web Studio A–5
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Using Office <strong>Automation</strong> (Windows XP)<br />
.PageHeight = InchesToPoints(11)<br />
.FirstPageTray = wdPrinterDefaultBin<br />
.OtherPagesTray = wdPrinterDefaultBin<br />
.SectionStart = wdSectionNewPage<br />
.OddAndEvenPagesHeaderFooter = False<br />
.DifferentFirstPageHeaderFooter = False<br />
.VerticalAlignment = wdAlignVerticalTop<br />
.SuppressEndnotes = False<br />
.MirrorMargins = False<br />
End With<br />
' Fill the document with appropriate information<br />
Set myRange = app.ActiveDocument.Range<br />
With myRange<br />
.ParagraphFormat.Alignment = wdAlignParagraphLeft<br />
.Font.Name = "Arial"<br />
.Font.Size = 11<br />
.bold = False<br />
.InsertAfter "My Company, Inc" & vbCrLf<br />
.InsertAfter "Production Report" & vbCrLf<br />
.InsertAfter Now() & vbCrLf & vbCrLf<br />
.InsertAfter "Production ID : " & $myProdName[$MyReportLine] &vbCrLf &vbCrLf<br />
.InsertAfter "Total Number Produced = " & $line_total & vbCrLf<br />
.InsertAfter "Total Number Good = " & $line_good & vbCrLf<br />
.InsertAfter "Total Number Marginal = " & $line_marginal & vbCrLf<br />
.InsertAfter "Total Number Bad = " & $line_bad & vbCrLf<br />
End With<br />
' Format the document<br />
myRange.SetRange app.ActiveDocument.Paragraphs(1).Range.Start,<br />
app.ActiveDocument.Paragraphs(3).Range.End<br />
With myRange<br />
.ParagraphFormat.Alignment = wdAlignParagraphCenter<br />
End With<br />
myRange.SetRange app.ActiveDocument.Paragraphs(1).Range.Start,<br />
app.ActiveDocument.Paragraphs(1).Range.End<br />
With myRange<br />
.Font.Size = 24<br />
.bold = True<br />
End With<br />
myRange.SetRange app.ActiveDocument.Paragraphs(2).Range.Start,<br />
app.ActiveDocument.Paragraphs(3).Range.End<br />
With myRange<br />
.Font.Size = 14<br />
End With<br />
myRange.SetRange app.ActiveDocument.Paragraphs(11).Range.Start,<br />
app.ActiveDocument.Paragraphs(11).Range.End<br />
vert_pos = myRange.Information(wdVerticalPositionRelativeToPage)<br />
With doc<br />
.Shapes.AddOLEObject , XLSName, , , , , , , CStr(vert_pos +25), "400", "320"<br />
End With<br />
doc.SaveAs WordName<br />
End If<br />
Set doc = Nothing<br />
A–6 InduSoft Web Studio
Using Office <strong>Automation</strong> (Windows XP)<br />
<strong>IWS</strong> <strong>Training</strong> <strong>Guide</strong><br />
Set app=Nothing<br />
Set xlsapp = Nothing<br />
InduSoft Web Studio A–7
Appendix B. Application Notes<br />
Application Note AN-00-0001 “Using the Div & Add and Max & Min Parameters in a Main or Standard Driver<br />
Sheet”<br />
Application Note AN-00-0002 “Dynamically Loading Pictures on a Screen using an ActiveX Control and<br />
VBScript”<br />
Application Note AN-00-0003 “Using the Radio Button and Check Box Objects”<br />
Application Note AN-00-0004 “Using XML in InduSoft Web Studio”<br />
Application Note AN-00-0005 “Manipulating Collections, Folders and Files with InduSoft Web Studio Built-in<br />
Functions”<br />
Application Note AN-00-0006 “Manipulating Collections, Folders and Files with VBScript’s FileSystemObject”<br />
Application Note AN-00-0007 “Using InduSoft Web Studio with TouchScreen PCs”<br />
InduSoft Web Studio B–1