* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download AppForge MobileVB™ Manual
Survey
Document related concepts
Oracle Database wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Microsoft Access wikipedia , lookup
Navitaire Inc v Easyjet Airline Co. and BulletProof Technologies, Inc. wikipedia , lookup
Microsoft SQL Server wikipedia , lookup
Functional Database Model wikipedia , lookup
Ingres (database) wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
Concurrency control wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Open Database Connectivity wikipedia , lookup
Relational model wikipedia , lookup
ContactPoint wikipedia , lookup
Transcript
AppForge MobileVB™ Manual Version 3.2.0 December 19, 2002 Contents 1 AppForge MobileVB Manual Overview 1 2 Getting Started with AppForge MobileVB™ 2 Minimum PC Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 AppForge Booster™ Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Before You Install . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Installing AppForge MobileVB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 3 Introduction To AppForge MobileVB™ 3.2.0 4 4 AppForge Ingots 5 4.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 4.2 AFAlarm (MobileVB™ Only) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 4.3 AFButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 4.4 AFCheckBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 ™ 4.5 AFClientSocket (MobileVB Only) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 4.6 AFComboBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 4.7 AFCommandBtnAreaNS80 (Nokia Series 9200 Communicator Only) . . . . . . . . . . 13 4.8 AFDatePicker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 4.9 AFFilmstrip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 4.10 AFGraphic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 4.11 AFGraphicButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 4.12 AFGrid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 4.13 AFHScrollBar (MobileVB™ Only) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 4.14 AFINetHTTP (MobileVB™ Only) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 4.15 AFLabel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 4.16 AFListBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 4.17 AFMovie (MobileVB™ Only) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 I 4.18 AFOwnerDrawGrid (MobileVB™ Only) . . . . . . . . . . . . . . . . . . . . . . . . . . 27 4.19 AFRadioButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 ™ 4.20 AFScanner (MobileVB Only) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 4.21 AFSerial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 4.22 AFShape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 4.23 AFSignatureCapture (MobileVB™ Only) . . . . . . . . . . . . . . . . . . . . . . . . . 40 4.24 AFSlider (MobileVB™ Only) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 4.25 AFSpriteField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 4.26 AFSpriteTemplate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 4.27 AFTextBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 4.28 AFTimePicker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 4.29 AFTimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 4.30 AFTitleBarNS80 (Nokia Series 9200 Communicator Only) . . . . . . . . . . . . . . . . 49 4.31 AFTone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 4.32 AFUpDown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 4.33 AFVScrollBar (MobileVB™ Only) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 4.34 AFWidget (MobileVB™ Only) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 4.35 AFWindowBkgNS80 (Nokia Series 9200 Communicator Only) . . . . . . . . . . . . . . 54 5 AppForge Classes 55 6 AppForge Libraries 62 6.1 AppForge Libraries Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 6.2 AppForge Numeric Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 6.3 AppForge System Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 6.4 AppForge Palm OS Extensibility Library (MobileVB™ , Palm OS Only) . . . . . . . . . 65 6.5 AppForge Palm OS Extended Functions Library (Palm OS Only) . . . . . . . . . . . . . 65 6.6 AppForge PIM Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 6.7 AFCore Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 II 6.8 7 AppForge Telephony Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 AppForge MobileVB™ Data Synchronization 110 7.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 7.2 AppForge Universal Conduit Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Installation on the Developer’s System . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 Configuring a Universal Conduit Descriptor . . . . . . . . . . . . . . . . . . . . . . . . 114 Installation on the End User’s System . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 Using UCConfigCmd.exe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Understanding Key Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 8 9 AppForge Fuser Technology 128 8.1 Introduction To Fusers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 8.2 Fuser Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 8.3 Creating a Fuser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 8.4 Calling A Fuser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 8.5 Building and Running the Fuser Samples . . . . . . . . . . . . . . . . . . . . . . . . . 133 8.6 AppForge Fuser Functions Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 AppForge MobileVB™ Support for Visual Basic 136 9.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 9.2 Data Type Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 9.3 User-defined Classes and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 9.4 Scoping and Visibility Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 9.5 Controls Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 9.6 Flow-of-control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 9.7 Debugging and Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 9.8 MsgBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 III 9.9 InputBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 9.10 ReDim Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 9.11 VarPtr Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 9.12 Customizing Toolbars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 9.13 Event Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 9.14 Reserved Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 9.15 MobileVB Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 9.16 MobileVB Screen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 9.17 Supported Visual Basic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 9.18 Unsupported Visual Basic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 10 AppForge MobileVB™ Tutorial 153 10.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 10.2 Lesson 1: Creating a MobileVB™ Project . . . . . . . . . . . . . . . . . . . . . . . . . 156 10.3 Lesson 2: Adding Database Connectivity and Creating an Error Form . . . . . . . . . . 169 10.4 Lesson 3: Creating a Category Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 10.5 Lesson 4: Adding Connectivity to the Program Database . . . . . . . . . . . . . . . . . 183 10.6 Lesson 5: Displaying Programs by the Hour . . . . . . . . . . . . . . . . . . . . . . . . 191 10.7 Lesson 6: Providing Control Over the Program Timeframe . . . . . . . . . . . . . . . . 198 10.8 Lesson 7: Creating a Program Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204 10.9 Lesson 8: Displaying Program Information . . . . . . . . . . . . . . . . . . . . . . . . 209 10.10Lesson 9: Creating the Preview Form . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 10.11Lesson 10: Displaying Program Previews . . . . . . . . . . . . . . . . . . . . . . . . . 221 10.12Lesson 11: Uploading the MobileVB™ Project . . . . . . . . . . . . . . . . . . . . . . 226 11 AppForge MobileVB™ Add-In Guide 232 11.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232 11.2 Compile and Validate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233 11.3 Deploy To Device . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 IV 11.4 Save Project Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 11.5 MobileVB Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 Setting the Application Icon and Name . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 Setting Project Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 Setting Palm OS Project Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 Setting Pocket PC Project Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246 Setting Nokia Series 80 Project Settings . . . . . . . . . . . . . . . . . . . . . . . . . . 247 Setting Compiler Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 Setting My Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 11.6 Install Booster To Device . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252 11.7 Open MobileVB Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 11.8 Zoom Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 11.9 MobileVB Messages Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256 11.10MobileVB User’s Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 11.11AppForge Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 11.12Samples and Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 11.13AppForge on the Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258 12 AppForge Data Storage 259 12.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 12.2 Using the Database Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260 Creating the Database Access Manager . . . . . . . . . . . . . . . . . . . . . . . . . . 260 Opening a Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 Executing a SQL Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 Read-Only, Updatable, and Writable Recordsets . . . . . . . . . . . . . . . . . . . . . . 262 Field Properties of Recordsets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 12.3 Using the Database Model with SQL Server CE . . . . . . . . . . . . . . . . . . . . . . 265 Database Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 Connection Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 V Working in Hosted Mode versus Running on the Device . . . . . . . . . . . . . . . . . . 267 Programmer’s Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267 Synchronization Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269 SQL Server CE Administration Library Reference . . . . . . . . . . . . . . . . . . . . . 269 12.4 Using the Database Model with Pocket Access . . . . . . . . . . . . . . . . . . . . . . 270 Database Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 Connection Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 Working in Hosted Mode versus Running on the Device . . . . . . . . . . . . . . . . . . 271 Programmer’s Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 Synchronization Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 Pocket Access Administration Library Reference . . . . . . . . . . . . . . . . . . . . . 272 12.5 Using the Database Model with Symbian OS Databases . . . . . . . . . . . . . . . . . . 273 Database Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 Connection Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 Working in Hosted Mode versus Running on the Device . . . . . . . . . . . . . . . . . . 274 Programmer’s Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 Synchronization Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 Symbian OS Database Administration Library Reference . . . . . . . . . . . . . . . . . 276 12.6 Using the Database Model with PDBs . . . . . . . . . . . . . . . . . . . . . . . . . . . 276 Database Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276 Connection Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276 Working in Hosted Mode versus Running on the Device . . . . . . . . . . . . . . . . . . 277 Programmer’s Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 Synchronization Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 12.7 The Database Library vs. the PDB Library . . . . . . . . . . . . . . . . . . . . . . . . . 277 Tables versus Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 VI Retrieving Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 Modifying Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278 PDB Function Counterparts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278 12.8 Database Library Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280 Finding the Field Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280 Reading Record Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 Updating Record Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 Adding New Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 Deleting Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284 A Generic Record Reader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284 12.9 AppForge PDB Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286 12.10AppForge Database Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288 12.11AppForge SQLCE Administration Library . . . . . . . . . . . . . . . . . . . . . . . . . 290 12.12AppForge Pocket Access Administration Library . . . . . . . . . . . . . . . . . . . . . 292 12.13AppForge Symbian OS Database Administration Library . . . . . . . . . . . . . . . . . 293 VII List of Tables 5 Sync Type Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 6 Sync Type Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 7 Sync Table Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 8 Sync Key Glossary Entry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 9 Numeric Types Supported . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 10 String Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 11 Reserved Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 13 Functions and Subroutines not Supported in Visual Basic . . . . . . . . . . . . . . . . . 152 14 File Locations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 15 Lesson Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 16 Lesson 1 - Save Setttings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 17 Lesson 1 - Ingot Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 18 Lesson 1 - shpRect1 Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 19 Lesson 1 - shpRect2 Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 20 Lesson 1 - gphLogo Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 21 Lesson 1 - btnShowMe, gphArrowRight Properties . . . . . . . . . . . . . . . . . . . . 165 22 Lesson 1 - Save Setttings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 23 Lesson 2 - Ingot List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 24 Lesson 2 - Copied Ingot Name Changes . . . . . . . . . . . . . . . . . . . . . . . . . . 175 25 Lesson 2: Copied Ingot Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 26 Lesson 2 - AFTextBox Property Settings . . . . . . . . . . . . . . . . . . . . . . . . . . 176 27 Lesson 3 - Save Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 28 Lesson 3 - Ingot List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 29 Lesson 3: Top Property Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 30 Lesson 3 - New Ingot Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 31 Lesson 3 - Save Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 32 Lesson 4 - Ingots Added . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 VIII 33 Lesson 4 - Ingot Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 34 Lesson 6 - Ingots to Add . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 35 Lesson 6 - New Ingot Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200 36 Lesson 7 - Ingots to Add . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 37 Copied Ingots Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 38 Lesson 7 - New Ingot Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 39 Lesson 7 - New Form Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 40 Lesson 8 - Ingots to Add . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 41 Lesson 8 - Ingot Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 42 Lesson 9 - Ingots to Add . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 43 Lesson 9 - Copied Ingots Property Changes . . . . . . . . . . . . . . . . . . . . . . . . 216 44 Lesson 9 - New Ingot Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 45 Lesson 10 - New Ingots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 46 Lesson 10 - New Ingot Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 47 Frames Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224 48 Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228 49 Add-In Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233 IX 1 AppForge MobileVB Manual Overview The AppForge MobileVB™ Manual is designed to help you get the most out of AppForge. The table below describes each different section. Getting Started Introduction To AppForge MobileVB 3.2.0 What’s New In AppForge MobileVB 3.2.0 AppForge Ingots™ AppForge Classes AppForge Libraries AppForge MobileVB Data Synchronization AppForge Fuser Technology AppForge MobileVB Support for Visual Basic AppForge MobileVB Tutorial AppForge MobileVB Add-In Guide AppForge Data Storage Minimum PC Requirements and Installation Instructions for AppForge. An introduction to version 3.2.0 of AppForge, with a brief description of how AppForge works. Describes the new features and functionality of AppForge 3.2.0. An overview of the Ingots provided with AppForge. An overview of the classes used by several AppForge Ingots. An overview of the libraries provided with AppForge. A list of data synchronization options supported by MobileVB. Also includes the AppForge Universal Conduit Guide. Details on the AppForge Techology, that enables programmers to pass information in and out of a MobileVB Visual basic program to an external software module. Documentation of Visual Basic features available in AppForge. Also includes information on supported and unsupported functions, as well as an overview of the MobileVB Form and Screen objects. An 11-lesson tutorial that steps through building and uploading an application using MobileVB. A walk through the AppForge MobileVB Add-In for Visual Basic® , including its features and functionality. Information on AppForge’s data storage solutions. Visual Basic is a registered trademark of Microsoft Corporation in the United States and/or other countries. Palm OS is a registered trademark of Palm, Inc. 1 2 Getting Started with AppForge MobileVB™ Minimum PC Requirements • Intel Pentium® or equivalent, 90+ MHz, 32 MB RAM • Windows® 95, 98, NT® , 2000, ME, or XP operating system • Microsoft® Visual Basic® 6.0 (Service Pack 4 required, Service Pack 5 recommended) • VGA adapter with 256 colors (16-bit color recommended) • 40 MB of available hard drive space • Palm Desktop (Palm® OS), ActiveSync (Pocket PC), or Nokia PC Suite (Nokia 9210/9290) are required to load applications on the corresponding device. (You can still debug and run AppForge applications within the Visual Basic® IDE without a device.) • Serial or USB ports, as needed • Windows Installer AppForge Booster™ Requirements Palm OS® Devices • Palm Powered® device • Palm OS 3.1 (3.5 is recommended) • 2MB RAM (4MB is Recommended) • Palm HotSync Manager software and cable Pocket PC Devices • StrongARM® processor devices such as Compaq IPAQ® • SH3 processor devices such as HP Jornada® • ActiveSync® software and cable 2 Symbian OS Devices • Nokia 9210/9290 Series Communicator • Nokia PC Suite software and cable Before You Install • Visit www.microsoft.com for the latest Windows® Service Packs: – If you are running Windows® 95, you will need Windows® 95 Service Pack 1. – If you are running Windows NT® 4.0, you need Windows NT4 Service Pack 4 or higher. • Palm OS® version 3.1 or later is required to run AppForge™ applications on your Palm OS® handheld device. Palm OS® can be downloaded from the Palm™ web site (www.palm.com). Installing AppForge MobileVB • Insert the AppForge MobileVB CD-ROM into your PC. • If your system automatically runs CDs, the AppForge MobileVB Getting Started guide will open in your default Web browser. If it does not open, click Start, then Run, then type D:\index.htm, where D is your CD-ROM’s drive letter designation. • If your system does not automatically run CDs, or Internet Explorer is not your default Web browser, you may need to launch the installer manually. Click Start, then Run, then type D:\MobileVB3.exe, where D is your CD-ROM’s drive letter designation. AppForge MobileVB is a trademark of AppForge, Inc. Windows and Visual Basic are registered trademarks of Microsoft Corporation in the United States and/or other countries. Palm OS and HotSync are registered trademarks, and Palm is a trademark of Palm, Inc. 3 3 Introduction To AppForge MobileVB™ 3.2.0 AppForge MobileVB™ software offers the fastest way to create applications for mobile computers, phones, barcode scanners, and other devices running Palm OS® , Microsoft® Pocket PC, or Symbian OS (Nokia Only). Our software integrates into Microsoft® Visual Basic® 6.0 to give you the power to turn your ideas into finished products in record time. With MobileVB, you can run and test mobile and wireless applications in Visual Basic. The controls that you use to create mobile programs will work on a mobile device and under Windows. This means that, as a developer, you don’t need to have a wireless device to test and develop an application - you simply run the application from within Visual Basic, saving hours of development time. MobileVB™ marks the first time programmers can write a single application and deploy it to multiple handheld platforms without modification. Simply choose which platform(s) to deploy to within Visual Basic once the program is complete; a project will run the same in both operating systems, with no extra coding required. How AppForge MobileVB™ works 1. Install it - Load MobileVB™ software on a PC and you are ready to start developing handheld applications. The next time you launch Visual Basic, a new MobileVB menu appears in the main menu bar. 2. Write it - Use Visual Basic to create the application. First, use the MobileVB™ project template to open a new project and display the Ingots™ palette. Next, use the Ingots (ActiveX controls) to build the interface. Finally, write Visual Basic code to make the application functional. 3. Compile it - To test, simply choose the standard Run menu option in Visual Basic. The application compiles in Windows so you can accurately test and evaluate it without leaving the Visual Basic IDE. 4. Upload it - After completing the application, choose Upload in the MobileVB™ menu and transfer the application to a handheld device with AppForge Booster™ installed. 5. Run it - The project runs the same whether in Palm OS® , Pocket PC, or Symbian OS. 4 4 4.1 AppForge Ingots Overview AppForge provides a set of Ingots™ for use in Visual Basic® . Ingots are AppForge ActiveX components that are analagous to standard Visual Basic controls. They provide the feel and functionality of standard Visual Basic controls, and are programmed using properties, events and methods, just like standard controls. The only difference is that they work in Windows and on any handheld device supported by AppForge. The following table lists the Ingots included in AppForge, with a brief description of each. For full details on a specific Ingot, see the on line help. Ingot AFAlarm * AFButton AFCheckBox AFClientSocket * AFComboBox AFCommandBtnAreaNS80 ** AFDatePicker AFFilmstrip AFGraphic AFGraphicButton AFGrid AFHScrollBar * AFINetHTTP * AFLabel AFListBox AFMovie * AFOwnerDrawGrid * AFRadioButton AFScanner * AFSerial AFShape AFSignatureCapture * AFSlider * AFSpriteField AFSpriteTemplate AFTextBox Description Launches application and fires events at specified times. A command button that registers user clicks Prompts for true/false selection of an item Provides for socket-based communication Combines features of the text box and list box Provides means for consistently labelling Nokia Series 9200 Communicator menu buttons. Displays an AFDatePicker on the form. Plays a series of images Displays an image on the form A command button with a graphical face Dispays text in a grid A horizontal scroll bar Used to send and receive wireless HTTP requests Displays text that a user cannot change directly Displays a variable list of items Plays a movie A grid that allows user specified text, shapes, and graphics in each cell. Prompts for the selection of one item in a list Non-visual control that exposes scanner functionality for a variety of Symbol barcode scanner devices. Provides for serial port communication Displays a shape on the form Serves as an input for signatures A slider bar that reflects minimum and maximum data ranges Use AFSpriteField to control sprites and receive events during game progress. Use AFSpriteTemplate to design animations and behaviors for sprites which will be used with the AFSpriteField. Displays text on a form; accepts textual input from the user 5 AFTimePicker AFTimer AFTitleBarNS80 ** AFTone AFUpDown AFVScrollBar * AFWidget * AFWindowBkgNS80 ** Displays an AFTimePicker on the form Executes code at specific time intervals Provides a standard header for Nokia Series 9200 Communicator applications. Plays an audible tone Provides two arrow buttons that can be used to increase or decrease a value A vertical scroll bar Provides system programming in an Ingot Assists in creating Nokia Series 9200 Communicator applications that provide consistent window appearance and highlighting behavior. * Available in AppForge MobileVB™ only, and not in AppForge MobileVB Lite. ** For use on Nokia Series 9200 Communicator Only. 6 4.2 AFAlarm (MobileVB™ Only) AFAlarm Overview (MobileVB™ Only) AFAlarm is available in AppForge MobileVB™ only, and not in AppForge MobileVB Lite. The AFAlarm Ingot fires events at specified times. If your application is not currently running when the alarm goes off, it will also launch your application at that time. Before utilizing the AFAlarm Ingot, please be aware of the following constraints: • Only one AFAlarm Ingot is allowed in your application. • The Alarm event only fires when the form containing the Alarm Ingot is loaded. • Firing of the Alarm event is subject to timing of the specific device. Under Win32, the Alarm Ingot is checked every 30 seconds. Under Palm OS, when the device is asleep, alarms are checked approximately every 30 seconds. The developer should not assume that an Alarm will fire at the exact time specified in AlarmTime. Note for Palm OS Devices Palm OS® allows the user to turn off and lock the device using the Security application. If the devices is turned off and locked the AFAlarm Ingot will not properly launch your application. When the AFAlarm Ingot attempts to wake up the device, the Security asks for the password, and the intended application is never started. The AFAlarm Ingot provides the following properties, methods, and events: Properties AlarmExpired DisplayAlarm Index Tag Width AlarmTime Enabled Left Top Description Height SoundAlarm Visible Methods Move SetFocus Events 7 ZOrder Alarm Validate 4.3 GotFocus LostFocus AFButton AFButton Overview Use AFButton to register user clicks. When clicked, an AFButton appears pressed in. Set the Caption property to add a title to the face of the button. The AFButton Ingot provides the following properties, methods, and events: Properties Alignment Caption FontName ForeColor Left Tag Width Appearance Enabled FontSize Height TabIndex Top BackColor FontHandle FontStyle Index TabStop Visible Methods Move ZOrder Refresh SetFocus Events Click Validate 4.4 GotFocus LostFocus AFCheckBox AFCheckBox Overview Use an AFCheckBox to provide a true/false option to the user. Check boxes can be grouped together to prompt the user to select any number of items in a list. 8 When the AFCheckBox is clicked, its Value is equal to True and a check appears in its box. Clicking the AFCheckBox again sets the Value to False and clears the check. The value of an AFCheckBox can also be set during run time with the Value property. The Value property may also be used to determine the current state of the Ingot: afCheckBoxValueUnchecked, afCheckBoxValueChecked, or afCheckBoxValueGrayed. Use the Caption property to set the text next to the check box. AFCheckBox Ingots can be used in groups to display multiple choices from which the user can select one or more. Appropriate Use AFCheckBox and AFRadioButton Ingots function similarly, but are not interchangeable. Any number of AFCheckBox Ingots on a form can be selected at the same time, but only one AFRadioButton in a group can be selected at any given time. In addition, an AFCheckBox can be toggled by selecting it, whereas the only way to set a AFRadioButton to False is to select a different AFRadioButton. The AFCheckBox Ingot provides the following properties, methods, and events: Properties Alignment BackColor FontHandle FontStyle Index TabStop Value AllowGrayState Caption FontName ForeColor Left Tag Visible Appearance Enabled FontSize Height TabIndex Top Width Methods Move ZOrder Refresh SetFocus Events Click Validate GotFocus 9 LostFocus AFClientSocket (MobileVB™ Only) 4.5 AFClientSocket Overview (MobileVB™ Only) AFClientSocket is available in AppForge MobileVB™ only, and not in AppForge MobileVB Lite. The AFClientSocket Ingot provides several functions for performing socket-based communication using a wireless handheld device. The Ingot uses the network connection preferences specified by the handheld user to connect to the network. Usage The AFClientSocket Ingot supports two-way socket communication between a client and server. The AFClientSocket Ingot can only perform the functions of a client socket. As such, it can not listen on a port and must initiate the communication. • Use the ResolveHostName method to resolve a hostname into a dotted-quad formatted IP address. • Use the Connect method to create a socket and connect to a server. • Use the Close method to close the socket. • Use the SendString method to transmit non-Unicode strings. • Use the GetString method to retrieve and remove non-Unicode strings from the receive buffer. • Use the SendByte method to transmit bytes. • Use the GetByte method to retrieve and remove bytes from the receive buffer. • Use the SendInteger method to transmit integers. • Use the GetInteger method to retrieve and remove integers from the receive buffer. • Use the SendLong method to transmit longs. • Use the GetLong method to retrieve and remove longs from the receive buffer. The AFClientSocket Ingot provides the following properties, methods, and events: Properties Height Left RemoteHostIP Top Index LocalPort RemotePort Visible 10 LastError Protocol Tag Width Methods Close GetByte GetString SendByte SendString Connect GetInteger Move SendInteger SetFocus Disconnect GetLong ResolveHostName SendLong ZOrder Events DataWaiting LostFocus 4.6 Error Validate GotFocus AFComboBox AFComboBox Overview Use AFComboBox to read textual input and/or prompt the user to select an item from a menu. AFComboBox is a combination of two other Ingots, AFTextBox and AFListBox, and takes selected properties, methods, and events from these components. Use the Style property to select the style of the combo box (simple combo, dropdown combo, or dropdown list). With any of the three combo box styles, the user can select items from the list box. With the simple combo and dropdown combo styles, the user can be allowed to edit the contents of the text box. Different properties apply to different styles of the combo box. • Use the AddItem and RemoveItem methods to add or delete items from the list box. • Use the List, ListCount, and ListIndex properties to enable user access to combo box items. • Use the Locked property to control the user’s ability to edit text box contents. • If the Style property is selected as dropdown combo or dropdown list, the Height property of the Ingot cannot be changed. The height will be determined automatically by the FontSize it contains. The Height property can be adjusted when simple combo is selected for the Style property. • List item indexes used by the AFComboBox Ingot are zero-based. (0 is the first index, 1 is the second, 2 is the third, and so on). Typical Usage 11 1. Open a form. Double-click the AFComboBox Ingot icon in the toolbar to add a list box to the form. 2. Drag the combo box to the desired location on the form. 3. Resize the combo box to the desired height and width with the control handles. 4. Change the combo box’s default name (AFComboBox1) to a meaningful name for your application, e.g. "cboProduceList". 5. Within the form code, invoke the AddItem property to add a selection to the combo box. This code would likely be added to a form load or initialization subroutine/function. 6. Within the form code, call the list index property to determine the index of the item in the list that was selected. This code would likely be placed within the SelectItem event, or an AFButton’s Click event. Special Note In Visual Basic Hosted Mode, when an AFComboBox Ingot is clicked on to "drop down" the box, the ZOrder is changed so the AFComboBox is on top. When the box collapses, the initial Z-Order of the AFComboBox is not retained. This only occurs when operating in Visual Basic Hosted mode, and is NOT an issue when the application is running on a mobile device. The AFComboBox Ingot provides the following properties, methods, and events: Properties Alignment Enabled FontSize Height Left ListIndex ScrollBarAppearance SelText TabIndex Text Visible Appearance FontHandle FontStyle Index List Locked SelLength Sorted TabStop Top Width BackColor FontName ForeColor ItemData ListCount NewIndex SelStart Style Tag TopIndex Methods AddItem Refresh ZOrder Clear RemoveItem 12 Move SetFocus Events Change LostFocus 4.7 Click SelectItem GotFocus Validate AFCommandBtnAreaNS80 (Nokia Series 9200 Communicator Only) AFCommandBtnAreaNS80 Overview (Nokia Series 9200 Communicator Only) AFCommandBtnAreaNS80 is for use on a Nokia Series 9200 Commicator Only. The AFCommandBtnAreaNS80 Ingot position is always right and top aligned on the Form. NOTE: When the Form width is changed, the AFCommandBtnAreaNS80 Ingot position will not change automatically: It must either be dragged or its position properties must be edited before its position will update. The AFCommandBtnAreaNS80 Ingot provides the following properties, methods, and events: Properties Caption1 Caption2Enabled Caption4 Height TabIndex Top Caption1Enabled Caption3 Caption4Enabled Index TabStop Visible Caption2 Caption3Enabled DefaultCaption Left Tag Width Methods Move SetFocus ZOrder Click Validate GotFocus LostFocus Events 13 4.8 AFDatePicker AFDatePicker Overview The AFDatePicker Ingot enables you to provide a formatted date field that allows easy date selection. Note for Symbian OS developers: Because there is no touchscreen on the Nokia 9200 Communicator devices, you need to take advantage of the DatePicker’s support for keyboard navigation. By default, the AFDatePicker responds to the arrow keys as follows: • Up or Left = decrease value • Right or Down = increase value • With no modifier keys: arrows change the Day • With CTRL key held down: arrows change the Month • With CTRL+SHIFT keys held down: arrows change the Year The built-in Symbian date selection control responds to the arrow keys in this same way. You can also use theAFCommandBtnAreaNS80 Ingot (CommandBtnArea) to offer customized button input for the AFDatePicker Ingot. The AFDatePicker Ingot provides the following properties, methods, and events: Properties Appearance Day FontHandle FontStyle Index MinDate TabStop TitleFontName TitleForeColor Value Year BackColor DayOfWeek FontName ForeColor Left Month Tag TitleFontSize Top Visible Methods 14 BorderStyle Enabled FontSize Height MaxDate TabIndex TitleBackColor TitleFontStyle TrailingForeColor Width Move ZOrder Refresh SetFocus Events Change GotFocus 4.9 Click LostFocus DayClick Validate AFFilmstrip AFFilmstrip Overview Use AFFilmstrip to animate a series of graphics on the screen. NOTE: The AFMovie Ingot provides another way to add animation to a form using converted .AVI files. Typical Usage 1. Use a graphics editor to create two or more image files to be used as frame images for the filmstrip. The Ingot can display AppForge Graphics (.rgx) or JPEGs (.jpg). (Convert .bmp files to .rgx files using the AppForge Graphic Converter.) 2. Open a MobileVB™ form. From the Toolbar, double-click the AFFilmstrip Ingot icon to add it to the form. (The Ingot will appear invisible until its Frames property is set.) 3. Change the Name property from its default value to a custom name, e.g. "flmGears". 4. Click on the Frames property row, then click the browse button ("...") to open the Frames property window. Use the "Add" button to select and add the graphic files to show in the filmstrip. (The graphic files must be stored under the directory for the project.) Use the "Up" or "Down" arrows to change the display order of the files. 5. When all the frames are added, click "OK." The filmstrip will then display the first frame picture. Adjust the size of the Ingot as needed to fit the graphic. 6. The filmstrip will not play automatically. Call the Play method to start the animation from the first frame (e.g. "flmGears.Play"). The Interval property adjusts the delay between frames in milliseconds. Set the Interval to a smaller value to increase the animation speed. 7. By default, the AnimationStyle property is set to Loop. After the Play method is called, the filmstrip will play from first to last frame and repeat until the Stop method is called. 15 The AFFilmstrip Ingot provides the following properties, methods, and events: Properties AnimationStyle FrameCount Frames Interval TabStop Visible Enabled FrameFile Height Left Tag Width Frame FrameIndex Index TabIndex Top Methods AddFrame Play SetFocus ClearFrames Refresh Stop Move RemoveFrame ZOrder Events Click LostFocus 4.10 GotFocus Validate LastFrame AFGraphic AFGraphic Overview Use AFGraphic to display a graphic on the screen. AFGraphic can enhance the look and functionality of applications in a variety of ways: • Splash screen images • Icons • Customized form elements (e.g. 3D borders) • Interactive graphics 16 The AFGraphic Ingot provides the following properties, methods, and events: Properties BackColor Index TabIndex Top Enabled Left TabStop Visible Height Picture Tag Width Methods Cls DrawRectangle InvertArea Refresh ZOrder DrawCircle DrawText Move SetFocus Click MouseDown GotFocus MouseMove DrawLine Invert PaintPicture SetPixel Events LostFocus Validate 4.11 AFGraphicButton AFGraphicButton Overview Use the AFGraphicButton Ingot™ to register user clicks. The AFGraphicButton displays an image than can be programmed to change when the button is pressed, loses focus, or is disabled. The AFGraphicButton Ingot provides the following properties, methods, and events: Properties Alignment DownPicture Height NoFocusPicture Tag Width BackColor Enabled Index TabIndex Top 17 DisabledPicture FocusPicture Left TabStop Visible Methods Move ZOrder Refresh SetFocus Events Click Validate 4.12 GotFocus LostFocus AFGrid AFGrid Overview Use AFGrid to display text in a grid. The user can select one or more grid elements to provide input. • When programming with the AFGrid Ingot, it is usually necessary to perform customization during both design time and run time. For example, the ColWidth and RowHeight properties can only be set during run time. • Use the Row and Col properties to determine the currently selected grid item(s). • Use the AddItem and RemoveItem methods to add or delete a row from the grid. • Row and column indexes are zero-based, so the first item has an index of 0, the second has index 1, etc. Typical Usage 1. Open a form. Double-click the AFGrid Ingot icon in the toolbar to add a grid to the form. 2. Drag the grid to the desired location on the form. 3. Resize the grid to the desired height and width with the control handles. 4. Change the grid’s default name (AFGrid1) to a meaningful name for your application, e.g. "grdPayroll". 5. Set the number of columns for the grid to display using the Cols property. 6. Using the SelectionType property, set whether user clicks on the grid select single cells, entire rows, or nothing. 18 7. Within the form code, initialize the width of the columns using the ColWidth property. 8. Within the form code, invoke the AddItem property to add a row of data to the grid. This code would likely be added to a Form_Load subroutine. (This is also a good time to set the RowHeight property for each newly created row.) 9. Within the form code, call the Row and Col properties to determine which item in the grid was selected. This code would likely be placed within the grid’s SelectCell event, or within a button’s Click event. The AFGrid Ingot provides the following properties, methods, and events: Properties Appearance Col Cols DefaultRowHeight FontName ForeColor Index LeftCol RowHeight ScrollBars TabStop TextMatrix Visible BackColor ColAlignment ColWidth Enabled FontSize GridLines ItemData NewRow RowIsVisible SelectionType Tag Top Width BorderStyle ColIsVisible DefaultColWidth FontHandle FontStyle Height Left Row Rows TabIndex Text TopRow Methods AddItem Refresh ZOrder Clear RemoveItem Move SetFocus Events Click LostFocus Validate GotFocus SelectCell 19 LeftColChanged TopRowChanged 4.13 AFHScrollBar (MobileVB™ Only) AFHScrollBar Overview (MobileVB™ Only) AFHScrollBar is available in AppForge MobileVB™ only, and not in AppForge MobileVB Lite. Use AFHScrollBar to place a horizontal scroll bar on a form. Custom scroll bars can be used to manually change the placement of Ingots. This allows the programmer to create forms that are longer or wider than the device display, or to give scroll bars to Ingots that do not normally have them. Typical Usage The following steps describe how to create a horizontal scroll bar that extends the width of a form past its visible boundaries. 1. Open a form. Double-click the scroll bar Ingot icon in the toolbar to add one to the form. 2. Drag the scroll bar to the desired location on the form, and use the Appearance property to match the look of either Palm OS® or Pocket PC. 3. Resize the scroll bar to the desired height and width with the control handles, or change its Top, Left, Width and Height values in the properties window. 4. Change the list box’s default name to a meaningful name for your application, e.g. "hscbFormScrollBar". 5. Set the Min and Max properties to give the scroll bar a range of values to scroll through. 6. Within the scroll bar’s Change Event, read the new Value property and adjust other Ingots’ Top properties accordingly. (Note that Ingots are allowed to have negative Top and Left properties, which will place them at least partially off the form.) The AFHScrollBar Ingot provides the following properties, methods, and events: Properties Appearance Height Left SmallChange Tag Value BackColor Index Max TabIndex ThumbColor Visible 20 Enabled LargeChange Min TabStop Top Width Methods Move ZOrder Refresh SetFocus Events Change Validate GotFocus LostFocus 4.14 AFINetHTTP (MobileVB™ Only) AFINetHTTP Overview (MobileVB™ Only) AFINetHTTP is available in AppForge MobileVB™ only, and not in AppForge MobileVB Lite. The AFINetHTTP Ingot™ is a non-visual Ingot that provides several functions for connecting to the World Wide Web using a wireless handheld device. The Ingot uses the network connection preferences specified by the handheld user to connect to the Internet. Remarks To retrieve a URL that contains a question mark, set the AFINetHTTP Ingot’s URL property to match the portion left of the question mark, and the Document property to match the portion right of the question mark. Data retrieved by the Ingot is not formatted or parsed (e.g., retrieved HTML will retain its formatting tags). It is up to the programmer to format the data. You can add multiple AFINetHTTP Ingots to a form, and have up to four simultaneous HTTP connections. Typical Usage 1. In Visual Basic® , double-click on the AFINetHTTP Ingot to add it to the current form of an MobileVB™ project. 2. In the form’s code, set the Ingot’s URL and Document properties to match the URL to be retrieved from the World Wide Web. 3. Call the Ingot’s Execute method to search for the requested URL/Document. 21 4. Create code for the Ingot’s StatusChanged event. The event’s constant afINetHTTPStatusResponseReceived signals that the Ingot has found the requested host and document and is ready to receive data. 5. Check the ResponseCode property to ensure the target URL was found. 6. Use the Ingot’s GetChunk method to retrieve data from the host. Visual Basic is a registered trademark of Microsoft Corp. in the United States and/or other countries. Palm OS is a registered trademark of Palm, Inc. The AFINetHTTP Ingot provides the following properties, methods, and events: Properties Configuration Conversion Height RequestTimeout StillExecuting Top Width ConnectionAvailable DeviceID Index ResponseCode SystemError URL ContentType Document Left ResponseInfo Tag Visible Methods Cancel GetHeader URLEncodeString Execute Move ZOrder GetChunk SetFocus GotFocus StateChanged LostFocus Validate Events Error ReceivedData 4.15 AFLabel AFLabel Overview Use AFLabel to mark areas of a form, or label other controls. 22 You can write code that changes the text displayed by an AFLabel control in response to events during run time. For example, if your application takes a few seconds to commit a change, you can display a processing status message in an AFLabel. You can also use an AFLabel to identify a control, such as an AFTextBox Ingot, that doesn’t have its own Caption property. Typical Usage 1. Open a form. Double-click the AFLabel Ingot icon in the toolbar to add a label to the form. 2. Change the label’s default name (AFLabel1) to a meaningful name for your application, such as "lblFormTitle". 3. Drag the label to the desired location on the form or set the Top and Left properties. 4. Resize the label to the desired height and width with the control handles or by using the Height and Width properties. 5. Change the Caption property to the text that the label should display. 6. Set the font for the label by selecting the FontName property and selecting an option from the dialog that appears. 7. Set the ForeColor and BackColor properties to show the label with the desired colors. 8. To change the text in the label at runtime, set the Caption property to desired new text. The AFLabel Ingot provides the following properties, methods, and events: Properties Alignment BorderStyle FontHandle FontStyle Index TabStop Visible BackColor Caption FontName ForeColor Left Tag Width BackStyle Enabled FontSize Height TabIndex Top Methods Move ZOrder Refresh 23 SetFocus Events Change LostFocus 4.16 Click Validate GotFocus AFListBox AFListBox Overview Use AFListBox to display a list of varying size and content. The user can select one or more of the items in the list box to provide input. Typical Usage 1. Open a form. Double-click the AFListBox Ingot icon in the toolbar to add a list box to the form. 2. Drag the list box to the desired location on the form. 3. Resize the listbox to the desired height and width with the control handles. 4. Change the list box’s default name (AFListBox1) to a meaningful name for your application, e.g. "lstProduceList". 5. Within the form code, invoke the AddItem property to add a selection to the list. This code would likely be added to a Form_Load subroutine. 6. Within the form code, read the ListIndex property to determine the index of the item in the list that was selected. This code would likely be placed within the SelectItem event, or an AFButton’s Click event. The AFListBox Ingot provides the following properties, methods, and events: Properties Alignment Border FontName ForeColor ItemData ListCount NewIndex SelCount TabIndex Text Visible Appearance Enabled FontSize Height Left ListIndex ScrollBarAppearance Selected TabStop Top Width 24 BackColor FontHandle FontStyle Index List MultiSelect ScrollBars Sorted Tag TopIndex Methods AddItem Refresh ZOrder Clear RemoveItem Move SetFocus GotFocus Validate LostFocus Events Click SelectItem 4.17 AFMovie (MobileVB™ Only) AFMovie Overview (MobileVB™ Only) AFMovie is available in AppForge MobileVB™ only, and not in AppForge MobileVB Lite. Use AFMovie to play a movie on the screen. The AFMovie Ingot plays movies in the .RMV movie format. Use the AppForge Movie Converter to convert .AVI movie files to .RMV files. NOTE: The size of .RMV files is limited to 64 kb. Potential uses of AFMovie include rotating product views, how-to videos, introductory animations, and special effects. Sound is not supported by the AFMovie Ingot, and the converted .RMV files do not contain audio information. Future versions may support sound for platforms that support it. The playback speed (frame rate) of the AFMovie Ingot depends on the FramesPerSec property and the target hardware. Typical Usage To convert a movie file: 1. Use video editing software to create a suitable .AVI file for conversion to the .RMV format. 2. Use the AppForge Movie Converter to convert the .AVI file into an .RMV file. The .RMV file must be saved in the MobileVB™ project folder or sub-folders. To add the movie to an MobileVB project: 1. Open a MobileVB form. From the Toolbar, double-click the AFMovie Ingot icon to add it to the form. (The Ingot will appear invisible during design time.) Adjust its position and dimensions as needed. 25 2. Change the Name property from its default value to a custom name, e.g. "movDemo". 3. Click the Filenename property, then click the browse button ("...") to open the movie filename window. Click the "Browse..." button and select the converted .RMV file, then select "OK." (MobileVB™ includes a sample .RMV file in the "..\AppForge\VB Toolkit\samples\Resources\TargetImage" directory.) 4. To view the movie at runtime, use the Play method. In the following example, the movie is played when a button is clicked: ’Play the demo movie when the "Play" button is clicked Private Sub btnPlay_Click() movDemo.Play End Sub Note that movie files and other dependencies that are set at design time will automatically be bundled into the compiled project. However, any movie files that are only referenced in code must be manually added to the list of project dependencies. To view and edit the dependencies list, from the MobileVB menu select "MobileVB Settings," then click the "Dependencies" tab. The AFMovie Ingot provides the following properties, methods, and events: Properties CurrentFrame FramesPerSec Left TabStop TotalFrames Enabled Height LoopMovie Tag Visible Filename Index TabIndex Top Width Methods Move SetFocus Play Stop Refresh ZOrder Events End Validate GotFocus 26 LostFocus 4.18 AFOwnerDrawGrid (MobileVB™ Only) AFOwnerDrawGrid Overview (MobileVB™ Only) AFOwnerDrawGrid is available in AppForge MobileVB™ only, and not in AppForge MobileVB Lite. The AFOwnerDrawGrid Ingot is a grid that contains a separateICanvas for each cell. Using the available methods and properties of the ICanvas Class, text, shapes, and graphics can be painted into each grid cell. This makes it possible to create feature-rich grids with variable fonts, colors, and images. AFOwnerDrawGrid technically does not contain any data. It is simply told what to paint into each cell based on the code in thePaintCell event. Typically, the data would be stored in an array or a database, and the index of the array would be tied to the row number. For example, the text painted into a cell that is in row 5 may come from the data in MyArray(5). Before Using the AFOwnerDrawGrid Ingot Pay close attention to theVarColWidth property. Its default value is False. If you don’t want the column width all of the columns in the grid to change each timeColWidth property is modified, set VarColWidth to True. If you are planning to use any text in your grid, make sure to set theHasStrings property to True. When HasStrings is set to False theItemData , Text , andTextMatrix properties will not store any text. The AFOwnerDrawGrid Ingot provides the following properties, methods, and events: Properties Appearance Col ColWidth Enabled FontSize GridLines Index LeftCol Row Rows TabIndex Text TopRow Visible BackColor ColIsVisible DefaultColWidth FontHandle FontStyle HasStrings ItemData NewRow RowHeight ScrollBars TabStop TextMatrix VarColWidth Width Methods 27 BorderStyle Cols DefaultRowHeight FontName ForeColor Height Left OwnerDraw RowIsVisible SelectionType Tag Top VarRowHeight AddItem RefreshCell ZOrder Move RemoveItem Refresh SetFocus Events Click LostFocus SelectCell GotFocus MouseDown TopRowChanged LeftColChanged PaintCell Validate Classes The AFOwnerDrawGrid Ingot uses the following Classes: ICanvas IPalette IImage An overview of the Classes used in the AFOwnerDrawGrid can be found in the AppForge Classes Section on the following pages: Class Name ICanvas IImage IPalette 4.19 Page Number p. 55 p. 58 p. 59 AFRadioButton AFRadioButton Overview Use an AFRadioButton to provide the option of selecting exactly one item from a list of items. Radio buttons are always used in groups of two or more, and provide the user with a way to select only one item from a set of options. All AFRadioButtons with the same GroupID property value behave as a group. When one AFRadioButton is selected, all others in its group are deselected. When a AFRadioButton is selected, its Value property is set to True. The Value property can also be changed programmatically. Appropriate Use AFCheckBox and AFRadioButton Ingots function similarly, but are not interchangeable. Any number of AFCheckBox Ingots on a form can be selected at the same time, but only one AFRadioButton in a group 28 can be selected at any given time. In addition, an AFCheckBox can be toggled by selecting it, whereas the only way to set a AFRadioButton to False is to select a different AFRadioButton. Typical Usage 1. Open a form. Double-click the AFRadioButton Ingot icon in the toolbar to add a radio button to the form. 2. Drag the radio button to the desired location on the form. 3. Change the radio button’s default name (AFRadioButton1) to a meaningful name for your application, e.g. "rdoOptionOne". 4. Continue adding AFRadioButtons for all the selections desired. 5. Double-click the button to view its Click event procedure. Code that is added to this procedure will be run when the button is clicked. 6. Group together AFRadioButton Ingots by setting their GroupID properties to the same value (e.g. 1 for the first group of buttons, 2 for the second group, etc.). 7. To determine which radio button was selected in a group, check each button’s Value property. The AFRadioButton Ingot provides the following properties, methods, and events: Properties Alignment Caption FontName ForeColor Index TabStop Value Appearance Enabled FontSize GroupID Left Tag Visible BackColor FontHandle FontStyle Height TabIndex Top Width Methods Move ZOrder Refresh SetFocus Events Click Validate GotFocus 29 LostFocus 4.20 AFScanner (MobileVB™ Only) AFScanner Overview (MobileVB™ Only) AFScanner is available in AppForge MobileVB™ only, and not in AppForge MobileVB Lite. Description Use the AFScanner Ingot to support scanning and decoding of different types of barcodes from within your application. With AFScanner, your application can: • Activate and deactivate the scanner. • Set and get key scanner parameters, such as the hardware configuration and decoding options for various barcode symbologies. • Scan a barcode and handle the received data. The AFScanner Ingot is only available in AppForge MobileVB™ . Remarks The AFScanner Ingot currently supports the following barcode scanners: • Symbol Technologies® Model SPT1500 • Symbol Technologies® Model SPT1700 • Symbol Technologies® Model CSM-150 (SpringBoard Module) • Symbol Technologies® Model SPT1550 (requires Booster Plus™ for Symbol SPT1550) • Symbol Technologies® Model SPT1800 (requires Booster Plus™ for Symbol SPT1800) • Symbol Technologies® Model PPT2800 (requires Booster Plus™ for Symbol Pocket PC) • Symbol Technologies® Model PDT8100 (requires Booster Plus™ for Symbol Pocket PC) The AFScanner Ingot has no comparable Visual Basic® component. Essentially, it acts as a translator, giving you access to native Symbol SDK function calls in the form of AFScanner properties, events, and methods. AFScanner reports scanner errors back to the application through an event and a property (ErrorType), and retains pre-error copies of data. You can write your application either to respond to such reports, or to ignore them as appropriate. 30 Note: In MobileVB™ 3.0.0 or later, the AFScanner Ingot supports Pocket PC barcode scanner devices (listed above) as well as Palm OS devices. However, due to some differences in the underlying device drivers between the two platforms, not all properties, methods and events of the AFScanner Ingot will be supported on the Pocket PC platforms. These are as follows: • SetDefaultParams method • LEDState property • PointerMode property • AimDuration property • Angle property • ScanTimedOut Event Using these in cross platform application code will not harm the application, they simply will not have any effect on the actual scanner device Visual Basic is a registered trademark of Microsoft Corporation in the United States and other countries. Symbol is a registered trademark of Symbol Technologies, Inc. Recommended Usage Use the ScanReceived event to get scanned barcode data as a string, which you can then manipulate or store as you wish. Scans can be started through the DoScan method, or by simply using the Trigger buttons (not all devices have Trigger buttons). The Trigger buttons will start a scan automatically, the DoScan method only needs to be called if you are using a ’soft’ technique (like a VB button) to initiate a scan. Use the properties of the AFScanner Ingot to get and set scanner operating parameters, such as hardware configuration and decoding options. These properties are described in detail later in this section. About Subproperties AFScanner properties that control decoding and formatting options for specific barcode symbologies use subproperties to further specify their functions. The general form of a property-subproperty statement is: AFScanner1.Property.SubProperty = <Value> or, for an indexed subproperty, AFScanner1.Property.SubProperty(Index) = <Value> IMPORTANT: To bring up the property pages used for setting subproperties at design time, click on the ellipsis in the (Custom) entry in the VB properties window. 31 You can opt to set only design-time (static) parameters, or if called for by the application, you can also add the VB code needed for run-time (dynamic) support. In addition, many parameters are enumerations, in which case the available values will display for selection as you type. Subproperty Example Suppose that you want to configure your application to scan and decode Code39 barcodes between 4 and 10 characters in length. To set up design-time parameters in Visual Basic, you open the Code 39 property page and check the Code39 Enabled checkbox. Next, you set LengthType to "Length Within Range," set Length1 to "4," and set Length2 to "10." You can then add runtime support for modifying these settings by adding statements to your VB code: AFScanner1.Code39Params.EnabledTypes(Code39) _ = <Boolean Value> AFScanner1.Code39Params.Length1 = <Value> AFScanner1.Code39Params.Length2 = <Value> Note: You can also create references to the property objects that contain subproperties. Example: Dim MyCodabarParams As IAFScannerCodaBarParams ’declares an object of type IAFScannerCodabarParams Set MyCodaBarParams = AFScanner1.CodabarParams ’sets MyCodabarParams to the CodabarParams property ’object in AFScanner MyCodabarParams.Length1 = <value> Multiple Ingots The AFScanner Ingot, like any other VB control, will allow multiple instances of itself in an application. However, since the AFScanner Ingot is representative of a single piece of hardware, there are some things the developer must be conscious of when using multiple instances. • Only one instance of the Ingot can have control of the physical scanner hardware at any given time. This is controlled by the ’ScannerOpen’ property. • Many configuration parameters are stored by the physical scanner. Values for these parameters exist in each instance of an AFScanner ingot. The developer can choose whether to update the scanner hardware with the ingot’s parameters when it gets control, or to leave the scanner’s parameters in their current state. This is controlled by the ’AssertParamsOnOpen’ property. Properties, Events, and Methods 32 The AFScanner Ingot provides the following properties, methods, and events: Properties AimDuration AssertParamsOnOpen BiDirectionalRedundancy Code128Params Code93Params ErrorCode I2of5Params LEDOnDuration Left MSIPlesseyParams ScanEnabled ScannerOpen Tag TransmitCodeIDChar UPCEANParams Width Angle BeepOnDecode CodabarParams Code39Params D2of5Params Height Index LEDState LinearCodeTypeSecurityLevel PointerMode ScannedBarCodeType ScanTimeOut Top TriggerMode Visible Methods DoScan GetScanManagerVersion SetFocus GetDecoderVersion Move StopScan GetPortDriverVersion SetDefaultParams ZOrder Events GotFocus ScanReceived LostFocus ScanTimedOut Classes The AFScanner Ingot uses the following Classes: 33 ScanError Validate IAFScannerCodabarParams IAFScannerCode39Params IAFScannerD2of5Params IAFScannerI2of5Params IAFScannerUPCEANParams IAFScannerCode128Params IAFScannerExtCode39Params IAFScannerI2of5Params IAFScannerMSIPlesseyParams The following sections give an overview of the classes used in the AFScanner Details on the following Classes can be found in the see the on line help. IAFScannerExtCode39Params Overview The IAFScannerExtCode39Params provides the following properties: Properties CheckDigitVerification EnabledBarCodes Length2 Code32Prefix FullAscii LengthType Conversions Length1 TransmitCheckDigit IAFScannerCode39Params Overview The IAFScannerCode39Params provides the following properties: Properties CheckDigitVerification EnabledBarCodes LengthType Code32Prefix Length1 TransmitCheckDigit Conversions Length2 IAFScannerUPCEANParams Overview The IAFScannerUPCEANParams provides the following properties: Properties Conversions EANZeroExtend TransmitCheckDigit DecodeRedundancy EnabledBarCodes 34 DecodeSupplementals SecurityLevel IAFScannerCode128Params Overview The IAFScannerCode128Params provides the following property: Property EnabledBarCodes IAFScannerCodabarParams Overview The IAFScannerCodabarParams provides the following properties: Properties ClsiEditing Length2 EnabledBarCodes LengthType Length1 NotisEditing IAFScannerI2of5Params Overview The IAFScannerI2of5Params provides the following properties: Properties CheckDigitVerification Length1 TransmitCheckDigit Conversions Length2 EnabledBarCodes LengthType IAFScannerD2of5Params Overview The IAFScannerD2of5Params provides the following properties: Properties EnabledBarCodes LengthType Length1 35 Length2 IAFScannerCode93Params Overview The IAFScannerCode93Params provides the following properties: Properties EnabledBarCodes LengthType Length1 Length2 IAFScannerMSIPlesseyParams Overview The IAFScannerMSIPlesseyParams provides the following properties: Properties CheckDigitAlgorithm Length1 TransmitCheckDigit 4.21 CheckDigits Length2 EnabledBarCodes LengthType AFSerial AFSerial Overview Use the AFSerial Ingot™ to send and receive data through the device serial port. The operation of AFSerial is similar to the MSComm control in Visual Basic® , although AFSerial omits support for MSComm properties not generally supported in the handheld device environment. The AFSerial Ingot currently supports a single serial port on the target device, and COM1 through COM16 under Windows. Usage The AFSerial Ingot supports two-way serial communication using either polling or an event-driven method. You use the CommEvent property to poll for communication activity at appropriate points in your application. Event-driven communication activity is triggered by the arrival of data or when a communications error occurs. • Use the OnComm event to handle communication events and errors. • Use the CommEvent property to detect possible communication events and errors. 36 • Also use CommEvent when polling for communication events and errors. • Use the CommPort property to set and return the communications port number. • Use the Settings property to set and return the serial communication settings. • Use the PortOpen property to open and close a communications port and check port status. • Use the ReadInputB method to retrieve and remove bytes from the receive buffer. • Use the Output property to transmit a string. • Use the WriteOutputB method to transmit bytes. Example The following code sample demonstrates basic event-driven serial communications: ’Create a buffer for the input string Dim Instring As String Private Sub Form_Load() #if APPFORGE then ’On Palm use cradle port AFSerial1.CommPort = 32768 #else ’In Windows use the COM1 port AFSerial1.CommPort = 1 #end if ’9600 baud, no parity, 8 data, 1 stop AFSerial1.Settings = "9600,N,8,1" ’On Input, read the whole buffer AFSerial1.InputLen = 0 ’Open the serial port AFSerial1.PortOpen = True ’Fire OnComm as each character arrives AFSerial1.RThreshold = 1 End Sub Private Sub AFSerial1_OnComm() Select Case AFSerial1.CommEvent 37 Case afSerialEventReceive ’ Append all incoming data to Instring While AFSerial1.InBufferCount > 0 Instring = Instring & AFSerial1.Input Wend Case afSerialEventBreak ’ Break character detected Case afSerialEventFrame ’ framing error detected Case afSerialEventParity ’ parity error detected Case afSerialEventOverrun ’ receiver overrun, data has been lost End Select End Sub The AFSerial Ingot provides the following properties, methods, and events: Properties Break CTSHolding Height Index Left RThreshold Top CommEvent DSRHolding InBufferCount Input Output Settings Visible CommPort Handshaking InBufferSize InputLen PortOpen Tag Width Methods Move WriteOutputB ReadInputB ZOrder Events 38 SetFocus GotFocus Validate LostFocus OnComm 4.22 AFShape AFShape Overview Use AFShape to draw rectangles, squares, circles, ovals and more. The AFShape Ingot is the easiest and most efficient way to customize the look of a MobileVB™ application. Shapes use much less memory than an AFGraphic, or other Ingots that require external graphic files. Shapes can also be overlapped and blended with other Ingots to create new looks, or to emulate the look of the target platform. The AFShape Ingot provides the following properties, methods, and events: Properties BackColor BorderWidth FillStyle Left TabStop Visible BorderColor Enabled Height Shape Tag Width BorderStyle FillColor Index TabIndex Top Methods Move ZOrder Refresh SetFocus Events GotFocus LostFocus 39 Validate 4.23 AFSignatureCapture (MobileVB™ Only) AFSignatureCapture Overview (MobileVB™ Only) AFSignatureCapture is available in AppForge MobileVB™ only, and not in AppForge MobileVB Lite. Use the AFSignatureCapture Ingot to read and store signatures as input. Signatures can be stored and read as String data. Typical Usage 1. Open a form. Double-click the AFSignatureCapture Ingot icon in the toolbar to add a signature caputre box to the form. 2. Change the signature capture box’s default name (AFSignatureCapture1) to a meaningful name for your application, e.g. "sigUserAuthorization". 3. Drag the signature capture box to the desired location on the form, or set the Top and Left properties. 4. Resize the signature capture box to the desired height and width with the control handles, or by using the Height and Width properties. 5. Set the PenWidth property to the desired width of stroke lines made inside the signature capture box. 6. During run time, use the SignatureData property to read and set signature data. The AFSignatureCapture Ingot provides the following properties, methods, and events: Properties BackColor BorderStyle Height PenColor TabIndex Top BackPicture BorderWidth Index PenWidth TabStop Visible BorderColor Enabled Left SignatureData Tag Width Methods Clear SetFocus Move ZOrder 40 Refresh Events GotFocus LostFocus Validate 4.24 AFSlider (MobileVB™ Only) AFSlider Overview (MobileVB™ Only) AFSlider is available in AppForge MobileVB™ only, and not in AppForge MobileVB Lite. Use AFSlider for input or output based on magnitude. The slider bar has minimum and maximum integer values (Min and Max properties), and can visually represent any integer values in between. Users can change the value of the slider’s pointer (called the "thumb") by clicking and moving it directly, or by clicking on either side of the thumb (on the "track"). This moves the thumb a number of positions along the track, determined by the SmallChange and LargeChange properties. Programs can respond immediately to changes in the slider bar by using the SliderMoved event. Slider bars provide a way to input or output data on a pre-determined scale. For example, a program could connect a slider to the current frame being displayed in an AFFilmStrip. The Min and Max values would be 1 and the total number of frames respectively. By placing code in the slider’s SliderMoved event, the program could update the frame being displayed according to the current position of the thumb (Value property). Typical Usage 1. Open a form. Double-click the AFSlider Ingot icon in the toolbar to add a slider to the form. 2. Drag the slider to the desired location on the form. 3. Resize the slider to the desired height and width with the control handles. 4. Change the slider’s default name (AFSlider1) to a meaningful name for your application, e.g. "sldVolume". 5. Set the Min and Max properties to the desired minimum and maximum slider values. 6. To see valid positions for the slider thumb as tick marks, set the ShowTicks property to True. 7. Use the SliderMoved event to determine when the slider has been moved by the user, or set the Value property to show a value using the slider. The AFSlider Ingot provides the following properties, methods, and events: 41 Properties Appearance Index Max ShowTicks TabStop ThumbForeColor TrackBackColor Visible Enabled LargeChange Min SmallChange Tag TickFrequency TrackForeColor Width Height Left Orientation TabIndex ThumbBackColor Top Value Methods Move ZOrder Refresh SetFocus Events GotFocus Validate 4.25 LostFocus SliderMoved AFSpriteField AFSpriteField Overview The AFSpriteField Ingot has events for updating a game’s progress and painting: • Animate - This event is useful for changing a sprite’s location, animating a sprite, updating the player’s score, etc. • PrePainting - This event is used to paint the background, before the sprites have been drawn. This event has a parameter eraseBackground, which should be set to False if drawing will occur. If there is no PrePainting event, the background will be erased. • PostPainting - This event is used to paint after the sprites have been drawn. This can be used to draw the player’s score, lives left, and any other foreground painting. The AFSpriteField Ingot provides the following properties, methods, and events: 42 Properties BackgroundColor Left MapImageName MapTileData MapWidth SpriteState SpriteX TabStop Visible Height MapHeight MapOffsetX MapTileIndex Period SpriteUserData SpriteY Tag Width Index MapImage MapOffsetY MapTileSize SpriteFrame SpriteVisible TabIndex Top Methods CreateSprite Move SpriteAnimate Stop DestroySprite Refresh Start ZOrder InvalidateRegion SetFocus Step Events Animate HardKeyDown KeyPress PointerDown PostPainting Validate Collision HardKeyUp KeyUp PointerMove PrePainting GotFocus KeyDown LostFocus PointerUp SpriteClicked Classes The AFSpriteField Ingot uses the following Classes: ICanvas 4.26 AFSpriteTemplate AFSpriteTemplate Overview The AFSpriteTemplate is a non-visual Ingot that eases sprite design. 43 • TheTemplateName property is a string used to uniquely identify the sprite template. TemplateName is used as the first argument of the AFSpriteField methodCreateSprite. • TheImage property is a picture with all the animation frames. Each frame must be the same width. • A custom property page is used to control animations and collisions. To open a custom property page for an AFSpriteTemplate, click on the (Custom) property in the Properties pane of your AFSpriteTemplate Ingot. On the animation tab, set the Frame Width to the width in pixels of a frame. The State List is used to create separate animations that sprite can be set to. For example, different states can be when a character is walking, running, jumping, or climbing. For each state in the State List, there is the Frame List. The Frame List is the actual frames used in the animation sequence. To add frames, click the add button. To change a frame, highlight the frame to change in the Frame List, then click on the frame picture in the Frames. The AFSpriteField method SpriteAnimate is used to change the sprite to the next frame in the current Frame List. The AFSpriteFieldSpriteState property is used to change the sprite to a different state in the State List. • ThePlane property is used to determine the drawing order of sprites and to group sprites for collision detection. For drawing order, the lowest plane is drawn first and the largest plane is drawn last. In the property pages, on the collision tab, the "Collides With Planes" is a list of other planes that this sprite can collide with. This will limit the number of collision events that are generated from AFSpriteField. For example, the character can be on plane 0, the player’s weapon fire on plane 1, the enemy on plane 2, and the enemy’s weapon fire on plane 3. The character might be set to collide with plane 2 and 3, but not with plane 1. So the character can collide with the enemy or the enemy’s weapon fire, but not the player’s weapon fire. • TheMaskColor andMasked properties determine if and how the sprite will be rendered with transparency. If the Masked property is False, the sprite is rendered without transparency. If the Masked property is True, then the MaskColor is used as the transparent color for the sprite image. The AFSpriteTemplate Ingot provides the following properties, methods, and events: Properties Animations Height Left Plane Top Collisions Image MaskColor Tag Visible FrameWidth Index Masked TemplateName Width Methods Move SetFocus 44 ZOrder Events GotFocus LostFocus Validate Classes The AFSpriteTemplate Ingot uses the following Classes: IAnimationList ICollisionList The following sections give an overview of the classes used in the AFSpriteTemplate Details on the following Classes can be found in the see the on line help. IAnimationList Overview The IAnimationList provides the following properties and methods: Properties Frame NumFrames NumStates Methods AddFrame RemoveFrame AddState RemoveState Clear ICollisionList Overview The ICollisionList provides the following properties and methods: Properties NumPlanes Plane Methods AddPlane Clear 45 RemovePlane 4.27 AFTextBox AFTextBox Overview Use AFTextBox to display text, or read text as input. Typical Usage 1. Open a form. Double-click the AFTextBox Ingot icon in the toolbar to add a text box to the form. 2. Change the text box’s default name (AFTextBox1) to a meaningful name for your application, e.g. "txtUserDescription". 3. Drag the text box to the desired location on the form or set the Top and Left properties. 4. Resize the text box to the desired height and width with the control handles or by using the Height and Width properties. 5. Set the UnderlineStyle property to the type line that should be displayed under the text. 6. Set the MultiLine property to determine if the text box should accept multiple lines of text entry. 7. Enter the default text to be displayed into the Text property field. 8. Set the font for the text box by selecting the FontName property and selecting an option from the dialog that appears. 9. Set the ForeColor and BackColor properties to show the text box with the desired colors. 10. During run time, call the Text property to determine what text the user has entered into the text box. The AFTextBox Ingot provides the following properties, methods, and events: Properties Alignment BorderStyle FontHandle FontStyle Index MaxLength ScrollBars SelText Tag TopLine Visible Appearance DisplayableLines FontName ForeColor Left MultiLine SelLength TabIndex Text TotalLines Width 46 BackColor Enabled FontSize Height Locked PasswordChar SelStart TabStop Top UnderlineStyle Methods Move ZOrder Refresh SetFocus Events Change LostFocus Click Validate GotFocus 4.28 AFTimePicker AFTimePicker Overview The AFTimePicker Ingot enables you to provide a formatted time field that allows easy time selection. The AFTimePicker Ingot provides the following properties, methods, and events: Properties Appearance CustomFormat FontName ForeColor HourIncrement Minute SecondIncrement Tag Visible BackColor Enabled FontSize Height Index MinuteIncrement TabIndex Top Width BorderStyle FontHandle FontStyle Hour Left Second TabStop Value Methods Move ZOrder Refresh SetFocus Events Change LostFocus Click Validate 47 GotFocus 4.29 AFTimer AFTimer Overview Use AFTimer to execute code at specific time intervals. The timer is used for creating a programmatic delay, or causing an event to happen at regular intervals. A timer may be used to display a splash screen for a predefined period of time, or to cause a form element to refresh at a specified interval (such as a label showing percentage complete of an operation). Once the Enabled property is set to True, the timer will continue firing Timer events untill the Enabled property is set to False. Even though the timer icon appears on the form at design time, there is no visual representation of the timer on the form at runtime. Typical Usage 1. Open a form. Double-click the AFTimer Ingot icon in the toolbar to add a timer to the form. 2. Change the timer’s default name (AFTimer1) to a meaningful name for your application, e.g. "tmrSplashWait". 3. Set the Interval property to the number of milliseconds the timer should wait before firing its Timer event. 4. Double-click the timer to view its Timer event procedure. Code that is added to this procedure will be run when the Interval time has elapsed. 5. If the timer should start when the form is loaded, set the Enabled property to True during design time. Otherwise, set Enabled to False and add code that will set the Enabled property to true when it is needed during run time. The AFTimer Ingot provides the following properties, methods, and events: Properties Enabled Interval Top Height Left Visible Index Tag Width Methods Move SetFocus 48 ZOrder Events GotFocus Validate LostFocus Timer 4.30 AFTitleBarNS80 (Nokia Series 9200 Communicator Only) AFTitleBarNS80 Overview (Nokia Series 9200 Communicator Only) AFTitleBarNS80 is for use on a Nokia Series 9200 Commicator Only. The AFTitleBarNS80 Ingot provides the following properties, methods, and events: Properties AutoPosition Height TabIndex Top BackColor Index TabStop Visible Caption Left Tag Width Methods Move SetFocus ZOrder Events GotFocus LostFocus Validate 4.31 AFTone AFTone Overview Use AFTone to provide auditory feedback, or to play simple musical tones. The type of tone created is specified with the Pitch and Duration properties. The Pitch property documentation contains an enumeration for converting musical notes to pitches in hertz. The target platform must have a speaker to use the AFTone Ingot. 49 Program execution halts when the Play method is called, and resumes when the tone has finished playing. Typical Usage 1. Open a form. Double-click the AFTone Ingot icon in the toolbar to add a tone player to the form. 2. Drag the tone player to the desired location on the form. 3. Change the tone’s default name (AFTone1) to a meaningful name for your application, e.g. "toneAlert". 4. Set the Pitch property to the desired pitch. 5. Set the Duration property to the number of milliseconds the tone should play. 6. In the form code, call the Play method to play the tone during run time. The AFTone Ingot provides the following properties, methods, and events: Properties Duration Index Tag Width Enabled Left Top Height Pitch Visible Methods Move ZOrder Play SetFocus Events GotFocus LostFocus 50 Validate 4.32 AFUpDown AFUpDown Overview The AFUpDown Ingot provides two arrow buttons that can be used to increase or decrease a value, such as an AFScrollBar or AFGrid position. The Value property of the AFUpDown Ingot changes when the user clicks the buttons on the control. How the Value property changes is controlled by the Increment, Min, Max, and Wrap properties. • TheIncrement property sets/returns the amount that the Value property changes when the AFUpDown Ingot is clicked. • TheMin property sets/returns the minimum for the Value Property of the AFUpDown Ingot. • TheMax property sets/returns the maximum for the Value Property of the AFUpDown Ingot. • TheWrap property is a boolean value that determines whether the Value property of the AFUpDown Ingot wraps around to the beginning or end once it reaches the Max or Min value. For example, say you need to increment the Value property in multiples of 5, and its range needs to be between 0 and 100. Set the Increment, Min, and Max properties to 5, 0, and 100 respectively. If you don’t want the Value to wrap from 0 up to 100 when the Min is hit or from 100 to 0 when the Max is hit set the Wrap property to False. The AFUpDown Ingot provides the following properties, methods, and events: Properties Appearance ForeColor Index Min TabStop Value Wrap BackColor Height Left Orientation Tag Visible Enabled Increment Max TabIndex Top Width Methods Move SetFocus Events 51 ZOrder Change LostFocus MouseUp 4.33 DownClick MouseDown UpClick GotFocus MouseMove Validate AFVScrollBar (MobileVB™ Only) AFVScrollBar Overview (MobileVB™ Only) AFVScrollBar is available in AppForge MobileVB™ only, and not in AppForge MobileVB Lite. Use AFVScrollBar to place a vertical scroll bar on a form. Custom scroll bars can be used to manually change the placement of Ingots. This allows the programmer to create forms that are longer or wider than the device display, or to give scroll bars to Ingots that do not normally have them. Typical Usage The following steps describe how to create a vertical scroll bar that extends the height of a form past its visible boundaries. 1. Open a form. Double-click the scroll bar Ingot icon in the toolbar to add one to the form. 2. Drag the scroll bar to the desired location on the form, and use the Appearance property to match the look of either Palm OS® or Pocket PC. 3. Resize the scroll bar to the desired height and width with the control handles, or change its Top, Left, Width and Height values in the properties window. 4. Change the list box’s default name to a meaningful name for your application, e.g. "vscbFormScrollBar". 5. Set the Min and Max properties to give the scroll bar a range of values to scroll through. 6. Within the scroll bar’s Change Event, read the new Value property and adjust other Ingots’ Left properties accordingly. (Note that Ingots are allowed to have negative Top and Left properties, which will place them at least partially off the form.) The AFVScrollBar Ingot provides the following properties, methods, and events: Properties 52 Appearance Height Left SmallChange Tag Value BackColor Index Max TabIndex ThumbColor Visible Enabled LargeChange Min TabStop Top Width Methods Move ZOrder Refresh SetFocus Events Change Validate GotFocus LostFocus 4.34 AFWidget (MobileVB™ Only) AFWidget Overview (MobileVB™ Only) AFWidget is available in AppForge MobileVB™ only, and not in AppForge MobileVB Lite. The AFWidget Ingot enables a programmer to construct a custom Ingot. It allows the use of theIWindow , ICanvas , andIImage Classes to create user defined fonts, colors, and images on the AFWidget. The AFWidget Ingot provides the following properties, methods, and events: Properties Height TabIndex Top Window Index TabStop Visible Left Tag Width Methods Move SetFocus 53 ZOrder Events BoundsChanging CapturedMouseLeave ContainsRect KeyDown LostFocus MouseUp Validate CanClose Closing EnabledStateChanged KeyPress MouseDown Painting VisibilityChanged CapturedMouseEnter ContainsPoint GotFocus KeyUp MouseMove TouchesRect Classes The AFWidget Ingot uses the following Classes: ICanvas IFontManager IMenu IShell IFontFoundry IFrame IScrollBar ITimer IFontList IMenu IShell IWindow An overview of the Classes used in the AFWidget can be found in the AppForge Classes Section on the following pages: Class Name ICanvas IFontFoundry IFontList IFontManager IFrame IImage IMenu IPalette IScrollBar IShell ITimer IWindow 4.35 Page Number p. 55 p. 56 p. 102 p. 57 p. 57 p. 58 p. 58 p. 59 p. 59 p. 59 p. 60 p. 60 AFWindowBkgNS80 (Nokia Series 9200 Communicator Only) AFWindowBkgNS80 Overview (Nokia Series 9200 Communicator Only) AFWindowBkgNS80 is for use on a Nokia Series 9200 Commicator Only. 54 The AFWindowBkgNS80 Ingot provides the following properties, methods, and events: Properties BackColor Height Left Tag Width Caption1 Highlighted TabIndex Top Caption2 Index TabStop Visible Methods Move SetFocus ZOrder Events GotFocus 5 LostFocus Validate AppForge Classes AppForge Class Overview AppForge provides a set of Classes that are available through several Ingots. They are listed in the following table and described in the following sections. ICanvas IFontManager IMenu IShell IFontFoundry IFrame IPalette ITimer IFontList IImage IScrollBar IWindow ICanvas Overview This interface represents a drawable surface supporting several drawing methods. Canvases can be obtained from a variety of sources including windows and images. To draw on a visible object, you must first request its ICanvas interface. Each drawing primitive in the interface, with the exception of "Erase", adjusts any geometric arguments by adding the values of the XOffset and YOffset properties. (Erase will clear the entire canvas to the pen color regardless of offset.) 55 The ICanvas provides the following properties and methods: Properties BrushColor Height PenColor Pixel SurfaceGreenMask Top YOffset BrushStyle Left PenPattern SurfaceBlueMask SurfacePitch Width CurrentFont Palette PenWidth SurfaceDepth SurfaceRedMask XOffset DrawEllipse DrawLine DrawText DrawTriangle GetClipRect InvertRectangle SetClipRect DrawHorizontalLine DrawRectangle DrawTextRange DrawVerticalLine GetSurface ReleaseSurface Methods Blit DrawImage DrawRoundRectangle DrawTextWrapped Erase IntersectClipRect Reset IFontFoundry Overview A "foundry" reflects the rendering engine for a particular font. Types of foundries include "native" indicating that the font is rendered by facilities native to the underlying operating system, and CMF in which case the font is rendered within the Piedmont framework. The IFontFoundry provides the following methods: Methods DrawText GetFontName GetStringBounds FontSupportsRange GetFontSize SetFontSize GetFontFamily GetFontStyle IFontList Overview While the IFontList class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they 56 may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The IFontList class provides the following methods: Methods EnumFirstFont EnumNextFont IFontManager Overview Fonts are referenced by a font handle (Long type) that can be obtained from GetFont. The IFontManager provides the following methods: Methods FontSupportsRange GetFontList GetFontStyle GetWrappedStringBounds GetFont GetFontName GetFoundryFromHandle SetFontSize GetFontFamily GetFontSize GetStringBounds IFrame Overview A Frame is a top-level window object that is rendered in a platform-specific manner, often including a border, caption bar, and menu. Frames contain a primary client window. The IFrame provides the following properties and methods: Properties Canvas Shell Title Enabled SuppressPaint Visible Menu SystemWindow Window Methods GetBounds SetBounds GetClientBounds 57 Paint IImage Overview An IImage encapsulates the state of a rectangular region of pixels with a particular bit depth per pixel. Images can present an ICanvas interface to allow drawing to the underlying raster through the set of the canvas’s basic drawing primitives. When loading a new image, make sure to free the previously loaded image. This optimizes memory memory usage. The code should look something like this: Set img = Nothing Set img = shell.LoadImage("MyImage.bmp") The IImage provides the following properties and methods: Properties Height TransparentColor Masked Width Palette Methods GetCanvas MakeCompatible Optimize Classes The IImage uses the following Classes: ICanvas IMenu Overview The IMenu provides the following properties and methods: Properties MenuItemEnabled MenuItemName Methods 58 MenuItemShortcut CreateMenuItem DestroyMenuItem FireMenu IPalette Overview IPalette represents the colors associated with an indexed-color image or canvas. A palette provides a mapping from an integer index into an RGB value encoded as a long. The first (highest-order) byte of the long is reserved for future use. The second, third and fourth bytes represent red, green and blue respectively. Each byte represents an color intensity ranging from 0 to 255. The IPalette provides the following properties and method: Properties NumEntries PaletteEntry Method GetNearestPaletteIndex IScrollBar Overview The scroll bar is a component of Window, but controls TargetWindow (without belonging to it). The virtual offset of a window determines how far it is scrolled. The IScrollBar provides the following properties: Properties Appearance Enabled Min PreferredWidth TargetWindow BackColor LargeChange OutlineColor ShaftColor ThumbColor IShell Overview The IShell provides the following properties and methods: 59 Direction Max Position SmallChange Window Properties CaretColor CaretWindow ScreenBlueMask ScreenHeight ScreenWidth CaretHeight FontManager ScreenDepth ScreenPalette CaretImage LogicalPalette ScreenGreenMask ScreenRedMask Methods CreateCompatibleImage CreateTimer EnumNextDisplayMode GetFrameCanvas GetTempCanvas LoadOptimizedImage ShowFrame UpdateTempCanvas CreateFrame DestroyFrame GetCaretPosition GetOffscreenCanvas GetTimeMS SetCaretPosition TranslateColor CreateImage EnumFirstDisplayMode GetCurrentFrame GetScreenCanvas LoadImage SetDisplayMode UpdateFrame ITimer Overview The ITimer provides the following properties and methods: Properties Period Running Methods Start Stop IWindow Overview Piedmont windows are rectangular regions of a device that are capable of displaying graphics (via their associated canvas) and initiating several events reflecting various state changes and user interactions. Windows may contain other child windows, and can be contained within a parent window or frame. Each window defines its own coordinate system relative to that of its parent. The origin of the local system is the upper-left corner of the window’s drawable area. 60 The IWindow provides the following properties and methods: Properties Children Frame HorizontalScrollEnabled Left SuppressPaint VerticalScrollEnabled Depth Height InternalHeight Parent Top Visible Enabled HorizontalScrollBar InternalWidth Sibling VerticalScrollBar Width Methods AddChildWindow CapturePointer GetBounds GrabFocus Paint RefreshArea RemoveChildWindow CanDrawDirect CreateChildWindow GetVirtualOffset Invalidate PaintDirect ReleaseCaret SetBounds 61 CanScrollDirect DestroyChildWindow GrabCaret InvalidateArea Refresh ReleasePointer SetVirtualOffset 6 AppForge Libraries 6.1 AppForge Libraries Overview AppForge provides several libraries for use in Visual Basic® . The following table provides a description of each. Library AppForge PDB Library AppForge Numeric Library AppForge System Library AppForge Palm OS® Extended Functions Library AppForge Palm OS Extensibility Library * AppForge PIM Library AppForge Database Library AppForge SQLCE Administration Library AFCore Library AFTelephony Library Description Provides a set of methods to manipulate a Palm OS® Database (.PDB). Provides two methods for generating pseudo-random numbers. Provides several system related methods. Provides several useful functions that allow you to get or change many Palm OS® settings. Provides methods to switch control over to another PRC. Allows access to data in Pocket Outlook Provides access to databases on handheld devices within the AppForge framework. Provides support for SQL Server CE running on Windows CE or Pocket PC devices. Provides support for SQL Server CE running on Windows CE or Pocket PC devices. Provides access to AppForge Core Services including AFClipboard, AFSysInfo, and filesystem. Also allows control of Graphics, Windows, Menus, Text, Audio, Serial Communications and other services. An overview of the AppForge Numeric Library, AppForge System Library, AppForge Palm OS Extensibility Library, AppForge Palm OS Extended Functions Library, AppForge PIM Library, AFCore Library, and AFTelephony Library follow. For full details on a specific Library, see the on line help. Information on the AppForge PDB Library can be found in the AppForge PDB Library Overview on page286 . Information on the AFDatabase Library can be found in the AppForge PDB Library Overview on page288 . Information on the AppForge SQLCE Administration Library can be found in the AppForge PDB Library Overview on page290 . * The AppForge Palm OS Extensibility Library is only available in AppForge MobileVB and not in AppForge MobileVB Lite. Visual Basic is a registered trademark of Microsoft Corporation in the United States and/or other 62 countries. Palm OS is a registered trademark of Palm, Inc. 63 6.2 AppForge Numeric Library AppForge Numeric Library Overview Description The AppForge Numeric library provides two methods for generating pseudo-random numbers. Typical Usage 1. A seed is a number that starts a random number generator. Within the application code, call SeedRandomLong with a Long value to seed the random number generator. (Typically SeedRandomLong is used once per application session.) To vary the seed used, use TimerMS as the SeedRandomLong paramter. 2. To get a randomly generated Long value, call RandomLong with an upper bound for the value to return,e.g. RandomLong(10) returns numbers in the range 0 to 9. Example Const UPPER_RANGE = 10 ’TimerMS returns a Long value based on the ’current time, so it works well as a seed ’for the random number generator. Private Sub Form_Load() Call SeedRandomLong(TimerMS) End Sub ’When a button named btnNewRandomNum is clicked, ’display a random number between 1 and 10 in a ’label called lblRandomValue. Private Sub btnNewRandomNum_Click() lblRandomValue.Caption = RandomLong(UPPER_RANGE) + 1 End Sub AppForge Numeric Library Methods RandomLong SeedRandomLong 64 6.3 AppForge System Library AppForge System Library Overview Description The AppForge System library provides several system related methods. These include methods for determining device key presses, determining the user name on the device, and getting a time in milliseconds. AppForge System Library Methods GetDeviceUserName TimerMS 6.4 RegisterKeyCode ReleaseKeyCode AppForge Palm OS Extensibility Library (MobileVB™ , Palm OS Only) AppForge Palm OS Extensibility Library Overview (MobileVB™ , Palm OS Only) The AppForge Palm OS Extensibility Library provides the following class: AppForge Palm OS Extensibility Library Class afPalmOS afPalmOS Overview The afPalmOS class provides the following methods: Methods CallApp 6.5 LaunchApp AppForge Palm OS Extended Functions Library (Palm OS Only) AppForge Palm OS Extended Functions Library Overview (Palm OS Only) The AppForge Palm OS Extended Functions Library provides the following class: 65 AppForge Palm OS Extended Functions Library Class afExtLib afExtLib Overview The afExtLib class provides the following methods: Methods ClipboardGetString EnqueueKey GetApplicationPreferences GetApplicationPreferencesVersion GetFirstDatabaseName GetHeapLargestFree GetNextDatabaseName GetSystemPreference GraffitiSetShiftState GraffitiShiftIndicatorInitialize GraffitiShiftIndicatorSetLocation RuntimeVersion SelectTime SetApplicationPreferences StringWidth 6.6 ClipboardSetString FontHeight GetApplicationPreferencesSize GetBatteryRemaining GetHeapFree GetHeapSize GetROMSerialNumber GraffitiGetShiftState GraffitiShiftIndicatorEnable GraffitiShiftIndicatorIsEnabled KeepAwake SelectDay SendDatabase SetSystemPreference AppForge PIM Library AppForge PIM Library Overview The AppForge PIM library provides access to all of the native PIM data on a Pocket PC or Symbian OS device. Developer’s can use the PIM library to create custom solutions such as CRM, time management, etc. that directly interface to a user’s PIM data on the device. The AppForge PIM Library does not support access to Microsoft® Outlook® Express. The AppForge PIM Library provides the following classes: AppForge PIM Library Classes 66 AddressCollection AddressItem EventRecipient IField IToDo MemoCollection MemoItem Recurrence SchedulerFind ToDoCollection ToDoItem AddressFilter AddressSort EventRecipients IMemos LinkCollection MemoFilter MemoSort SchedulerCollection SchedulerItem ToDoFilter ToDoSort AddressFind Categories IAddressBook IScheduler LinkItem MemoFind ObjectManager SchedulerFilter SchedulerSort ToDoFind AddressCollection Overview The AddressCollection class provides the following properties and methods: Properties Filter Sort Find Item Methods Add GetItemIndex Count Remove Delete Save AddressFilter Overview The AddressFilter class provides the following methods: Methods AddCriteriaAsDate Execute AddCriteriaAsString AddressFind Overview The AddressFind class provides the following methods: 67 ClearCriteria Methods AddCriteriaAsDate Execute AddCriteriaAsString ClearCriteria AddressItem Overview The AddressItem class provides the following properties and methods: Properties Anniversary AssistantTelephoneNumber Body BusinessAddressCity BusinessAddressPostalCode BusinessAddressStreet BusinessTelephoneNumber Children Department Email2Address FieldCount FirstName HomeAddressCity HomeAddressPostalCode HomeAddressStreet HomeTelephoneNumber JobTitle LinkCollection MobileTelephoneNumber OtherAddressCity OtherAddressPostalCode OtherAddressStreet RadioTelephoneNumber Suffix WebPage AssistantName Birthday Business2TelephoneNumber BusinessAddressCountry BusinessAddressState BusinessFaxNumber Categories CompanyName Email1Address Email3Address FileAs Home2TelephoneNumber HomeAddressCountry HomeAddressState HomeFaxNumber ItemID LastName MiddleName OfficeLocation OtherAddressCountry OtherAddressState PagerNumber Spouse Title Methods Delete Save 68 Field AddressSort Overview The AddressSort class provides the following methods: Methods AddCriteria ClearCriteria Execute Categories Overview The Categories class provides the following property and methods: Property Item Methods Add Count Delete EventRecipient Overview The EventRecipient class provides the following properties: Properties EmailAddress Name EventRecipients Overview The EventRecipients class provides the following property and methods: Property Item 69 Methods Add Count Delete IAddressBook Overview The IAddressBook class provides the following methods: Methods GetCollection GetItem IField Overview The IField class provides the following properties: Properties Name Value ValueType IMemos Overview The IMemos class provides the following methods: Methods GetCollection GetItem IScheduler Overview The IScheduler class provides the following methods: Methods GetCollection 70 GetItem IToDo Overview The IToDo class provides the following methods: Methods GetCollection GetItem LinkCollection Overview The LinkCollection class provides the following property and methods: Property Item Methods AddAddressLink AddToDoLink GetSortField AddMemoLink Count GetSortOrder AddSchedulerLink Delete SetSort LinkItem Overview The LinkItem class provides the following properties: Properties DateCreated Type ID Subject MemoCollection Overview The MemoCollection class provides the following properties and methods: Properties 71 Filter Sort Find Item Methods Add GetItemIndex Count Remove Delete Save MemoFilter Overview The MemoFilter class provides the following methods: Methods AddCriteriaAsDate ClearCriteria AddCriteriaAsLong Execute AddCriteriaAsString MemoFind Overview The MemoFind class provides the following methods: Methods AddCriteriaAsDate ClearCriteria AddCriteriaAsLong Execute AddCriteriaAsString MemoItem Overview The MemoItem class provides the following properties and methods: Properties Body FieldCount LinkCollection Categories ItemID Size 72 CreationTime LastModified Subject Methods Delete Field Save MemoSort Overview The MemoSort class provides the following methods: Methods AddCriteria ClearCriteria Execute ObjectManager Overview The ObjectManager class provides the following methods: Methods AddressBook ToDo Memos Scheduler Recurrence Overview The Recurrence class provides the following properties: Properties Duration NoEndDate StartTime EndDate Occurrences Type EndTime StartDate SchedulerCollection Overview The SchedulerCollection class provides the following properties and methods: Properties 73 Filter Sort Find Item Methods Add GetItemIndex Count Remove Delete Save SchedulerFilter Overview The SchedulerFilter class provides the following methods: Methods AddCriteriaAsBoolean AddCriteriaAsString AddCriteriaAsDate ClearCriteria AddCriteriaAsLong Execute SchedulerFind Overview The SchedulerFind class provides the following methods: Methods AddCriteriaAsBoolean AddCriteriaAsString AddCriteriaAsDate ClearCriteria AddCriteriaAsLong Execute SchedulerItem Overview The SchedulerItem class provides the following properties and methods: Properties AllDayEvent Categories FieldCount LinkCollection Recipients ReminderSet StartDate Body Duration IsRecurring Location Recurrence ReminderSoundFile Subject 74 BusyStatus EndDate ItemID MeetingStatus ReminderMinutesBeforeStart Sensitivity Methods Delete Field Save SchedulerSort Overview The SchedulerSort class provides the following methods: Methods AddCriteria ClearCriteria Execute ToDoCollection Overview The ToDoCollection class provides the following properties and methods: Properties Filter Sort Find Item Methods Add GetItemIndex Count Remove Delete Save ToDoFilter Overview The ToDoFilter class provides the following methods: Methods AddCriteriaAsBoolean AddCriteriaAsString AddCriteriaAsDate ClearCriteria 75 AddCriteriaAsLong Execute ToDoFind Overview The ToDoFind class provides the following methods: Methods AddCriteriaAsBoolean AddCriteriaAsString AddCriteriaAsDate ClearCriteria AddCriteriaAsLong Execute ToDoItem Overview The ToDoItem class provides the following properties and methods: Properties Body DateCompleted Importance LinkCollection ReminderSoundFile StartDate Categories DueDate IsRecurring Recurrence ReminderTime Subject Complete FieldCount ItemID ReminderSet Sensitivity TeamTask Methods Delete Field Save ToDoSort Overview The ToDoSort class provides the following methods: Methods AddCriteria ClearCriteria 76 Execute 6.7 AFCore Library AFCore Library Overview While the AFCore Library provides visibility to a powerful set of low level services, all of its classes are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support the use of all AFCore Library classes at present. The AFCore Library provides the following classes: AFCore Library Classes AFClipboard CAudioBuffer CBmpLoader CCanvas CDirectory CFileBinaryWritable CFileTextReadable CFileTextUnicodeWritable CFontList CFrame CImage CLocale CMemoryMappedFile CMessageBox CNativeFoundry CPDBManager CPngLoader CRgxLoader CSerialManager CShell CSocketAddress CSocketServer CSystem CTimer CTone CWrappedString IEventManager2 IFontScanner IPopupKeyboardEvents IScrollEvents ISocketAddress_InetDatagram 77 AFSysInfo CAudioManager CBufferStream CCmfFoundry CFileBinaryReadable CFileManager CFileTextUnicodeReadable CFileTextWritable CFontManager CGridBase CInputBox CLocalizationManager CMenu CNativeFormatter CPalette CPersistenceManager CPopupKeyboard CScrollBar CSerialPort CSocket CSocketManager CSymbianLauncher CTextEdit CTimerManager CWindow IAudioBufferEvents IFontList IGridBaseEvents3 IScrollEvents ISerialEvents ISocketEvents ISocketServerEvents ITextEditEvents ITimerEvents ITypedStream ISystemEvents ITimerEvents IToneEvents IWindowEvents AFClipboard Overview AFClipboard is used to copy and paste text in an MobileVB™ Application. When running an MobileVB application, AFClipboard must be used instead of the Clipboard object normally used in Visual Basic® . The AFClipboard class provides the following methods: Methods Clear GetText GetData SetData GetFormat SetText AFSysInfo Overview The AFSysInfo class provides the following properties: Properties BatteryLifePercent BoosterMinor BoosterVersion DeviceVersion HeapSize StorageFree WorkAreaLeft BoosterBuild BoosterPlatform DeviceType HeapFree ROMSerialNumber StorageSize WorkAreaTop BoosterMajor BoosterRevision DeviceUserName HeapLargestFree ScrollBarSize WorkAreaHeight WorkAreaWidth CAudioBuffer Overview While the CAudioBuffer class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CAudioBuffer class provides the following property, methods, and events: 78 Property Volume Methods Start Stop Events Done NeedMoreData CAudioManager Overview While the CAudioManager class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CAudioManager class provides the following property and methods: Property Volume Methods CreateAudioBuffer SystemAlarm SystemError CreateTone SystemBeep PlaySoundFromFile SystemClick CBmpLoader Overview While the CBmpLoader class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. 79 The CBmpLoader class provides the following method: Method LoadImageMapped CBufferStream Overview While the CBufferStream class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CBufferStream class provides the following properties and methods: Properties AtEnd CanSeek Realized CanRead CanWrite Size CanResize Position Methods ReadBinary WriteBinary Resize Seek CCanvas Overview While the CCanvas class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CCanvas class provides the following properties and methods: Properties 80 BrushColor Height PenColor Pixel SurfaceGreenMask Top YOffset BrushStyle Left PenPattern SurfaceBlueMask SurfacePitch Width CurrentFont Palette PenWidth SurfaceDepth SurfaceRedMask XOffset DrawEllipse DrawLine DrawText DrawTriangle GetClipRect InvertRectangle SetClipRect DrawHorizontalLine DrawRectangle DrawTextRange DrawVerticalLine GetSurface ReleaseSurface Methods Blit DrawImage DrawRoundRectangle DrawTextWrapped Erase IntersectClipRect Reset CCmfFoundry Overview While the CCmfFoundry class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CCmfFoundry class provides the following methods: Methods DrawText GetFontFamily GetFontStyle FontSupportsRange GetFontName GetStringBounds GetFont GetFontSize SetFontSize CDirectory Overview The CDirectory class provides the following properties and methods: Properties 81 Archive ReadOnly Hidden System Modified Methods CreateSubdirectory EnumFirstDirectory EnumNextFile EnumEndDirectory EnumFirstFile EnumResetDirectory EnumEndFile EnumNextDirectory EnumResetFile CFileBinaryReadable Overview The CFileBinaryReadable class provides the following properties and methods: Properties Archive Position System Hidden ReadOnly Modified Size Methods PeekChar ReadAsDouble ReadAsSingle SetSize ReadAsByte ReadAsInteger ReadBuffer ReadAsCurrency ReadAsLong Seek CFileBinaryWritable Overview The CFileBinaryWritable class provides the following properties and methods: Properties Archive Position System Hidden ReadOnly 82 Modified Size Methods PeekChar ReadAsDouble ReadAsSingle SetSize WriteAsDouble WriteAsSingle ReadAsByte ReadAsInteger ReadBuffer WriteAsByte WriteAsInteger WriteBuffer ReadAsCurrency ReadAsLong Seek WriteAsCurrency WriteAsLong CFileManager Overview The CFileManager class provides the following methods: Methods CopyDirectory DeleteFile EnumFirstFile EnumNextVolume MoveFile OpenAsTextUnicode OpenReadOnlyAsBinary CopyFile EnumEndFile EnumFirstVolume EnumResetVolume OpenAsBinary OpenDirectory OpenReadOnlyAsText DeleteDirectory EnumEndVolume EnumNextFile MoveDirectory OpenAsText OpenMapped OpenReadOnlyAsTextUnicode CFileTextReadable Overview The CFileTextReadable class provides the following properties and methods: Properties Archive Position System Hidden ReadOnly Modified Size Methods Peek ReadToEnd Read Seek 83 ReadLine SetSize CFileTextUnicodeReadable Overview The CFileTextUnicodeReadable class provides the following properties and methods: Properties Archive Position System Hidden ReadOnly Modified Size Methods Peek ReadToEnd Read Seek ReadLine SetSize CFileTextUnicodeWritable Overview The CFileTextUnicodeWritable class provides the following properties and methods: Properties Archive Position System Hidden ReadOnly Modified Size Methods Peek ReadToEnd Write Read Seek WriteLine ReadLine SetSize CFileTextWritable Overview The CFileTextWritable class provides the following properties and methods: Properties 84 Archive Position System Hidden ReadOnly Modified Size Methods Peek ReadToEnd Write Read Seek WriteLine ReadLine SetSize CFontList Overview While the CFontList class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CFontList class provides the following methods: Methods EnumFirstFont EnumNextFont CFontManager Overview While the CFontManager class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CFontManager class provides the following methods: Methods FitString GetFontFamily GetFontSize GetStringBounds FontSupportsRange GetFontList GetFontStyle GetWrappedStringBounds 85 GetFont GetFontName GetFoundryFromHandle SetFontSize CFrame Overview While the CFrame class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CFrame class provides the following properties and methods: Properties Canvas Shell Title Enabled SuppressPaint Visible Menu SystemWindow Window Methods GetBounds SetBounds GetClientBounds Paint CGridBase Overview While the CGridBase class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CGridBase class provides the following properties, methods, and events: Properties 86 Appearance Col Cols DefaultRowHeight FontName ForeColor LeftCol OwnerDraw RowIsVisible SelCount Sorted TopRow BackColor ColAlignment ColWidth Enabled FontSize GridLines MultiSelect Row Rows SelectedRow Text BorderStyle ColIsVisible DefaultColWidth FontHandle FontStyle ItemData NewRow RowHeight ScrollBars SelectionType TextMatrix Methods AddItem GetScrollNeeded GetWindow OnModeChanged RemoveItem Clear GetStringBounds InitWindow Refresh ScrollBarPtrDown GetFontHandle GetTrueColors OnHostDeviceChanged RefreshCell SetFlags Events GridBaseClick GridBaseSelectCell PaintCell GridBaseKeyCRLF LeftColChanged TopRowChanged GridBaseKeySelectCell MouseDown CImage Overview While the CImage class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CImage class provides the following properties and methods: Properties Height TransparentColor Masked Width 87 Palette Methods GetCanvas MakeCompatible Optimize CInputBox Overview While the CInputBox class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CInputBox class provides the following method: Method ShowInputBox CLocale Overview While the CLocale class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CLocale class provides the following methods: Methods GetCountryName GetCurrencySymbol GetFirstDayOfWeek GetLongDateFormat GetMonthName GetThousandsSeparator GetWeekdayName GetCurrencyDecimalPlaces GetDecimalSeparator GetInternationalCurrencySymbol GetMeasurementSystem GetShortDateFormat GetTimeFormat CLocalizationManager Overview While the CLocalizationManager class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible 88 that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CLocalizationManager class provides the following methods: Methods GetCurrentLocale GetLocale GetNumLocales CMemoryMappedFile Overview The CMemoryMappedFile class provides the following properties: Properties Ptr Size CMenu Overview While the CMenu class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CMenu class provides the following properties and methods: Properties MenuItemChecked MenuItemShortcut MenuItemEnabled MenuItemVisible MenuItemName Methods CreateMenuItem DestroyMenuItem FireMenu CMessageBox Overview While the CMessageBox class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that 89 they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CMessageBox class provides the following method: Method ShowMessageBox CNativeFormatter Overview While the CNativeFormatter class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CNativeFormatter class provides the following properties: Properties BasicStream TypedStream CNativeFoundry Overview While the CNativeFoundry class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CNativeFoundry class provides the following methods: Methods DrawText GetFontFamily GetFontStyle FontSupportsRange GetFontName GetStringBounds GetFont GetFontSize SetFontSize CPalette Overview While the CPalette class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they 90 may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CPalette class provides the following properties and method: Properties NumEntries PaletteEntry Method GetNearestPaletteIndex CPDBManager Overview While the CPDBManager class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CPDBManager class provides the following methods: Methods Bof CancelRecordEdit CreateDatabase CreateRecord CreateTable DeleteDatabase DeleteRecordEx Eof FindRecordByFieldAsByte FindRecordByFieldAsDate FindRecordByFieldAsInteger FindRecordByFieldAsSingle FindRecordByID GetDatabaseAttributes GetFieldAsByte GetFieldAsDate GetFieldAsInteger BulkRead Close CreateDBUniqueNumber CreateRecordBySchema CurrentIndex DeleteRecord EditRecord FindRecordByFieldAsBoolean FindRecordByFieldAsCurrency FindRecordByFieldAsDouble FindRecordByFieldAsLong FindRecordByFieldAsString GetCategoryName GetFieldAsBoolean GetFieldAsCurrency GetFieldAsDouble GetFieldAsLong 91 GetFieldAsSingle GetFieldByOffsetAsBoolean GetFieldByOffsetAsCurrency GetFieldByOffsetAsDouble GetFieldByOffsetAsLong GetFieldByOffsetAsString GetNumFields GotoIndex MoveLast MovePrev Open RecordAttributes RecordCategoryID RecordUniqueID ResizeRecord SetDatabaseAttributes SetNumFields SetRecordCategoryID SetSortFields WriteFieldAsBoolean WriteFieldAsCurrency WriteFieldAsDouble WriteFieldAsLong WriteFieldAsString WriteFieldByOffsetAsByte WriteFieldByOffsetAsDate WriteFieldByOffsetAsInteger WriteFieldByOffsetAsSingle WriteRecord GetFieldAsString GetFieldByOffsetAsByte GetFieldByOffsetAsDate GetFieldByOffsetAsInteger GetFieldByOffsetAsSingle GetLastError GetSortFields MoveFirst MoveNext NumRecords ReadRecord RecordAttributesEx RecordSize RemoveAllRecords SetCategoryName SetFieldType SetRecordAttributes SetSort UpdateRecord WriteFieldAsByte WriteFieldAsDate WriteFieldAsInteger WriteFieldAsSingle WriteFieldByOffsetAsBoolean WriteFieldByOffsetAsCurrency WriteFieldByOffsetAsDouble WriteFieldByOffsetAsLong WriteFieldByOffsetAsString CPersistenceManager Overview While the CPersistenceManager class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CPersistenceManager class provides the following method: Method CreateStreamFromBuffer 92 CPngLoader Overview While the CPngLoader class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CPngLoader class provides the following method: Method LoadImageMapped CPopupKeyboard Overview While the CPopupKeyboard class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CPopupKeyboard class provides the following properties and event: Properties Height x Visible y Width Event StateChanged CRgxLoader Overview While the CRgxLoader class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CRgxLoader class provides the following method: 93 Method LoadImageMapped CScrollBar Overview While the CScrollBar class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CScrollBar class provides the following properties and event: Properties Appearance Enabled Min PreferredWidth TargetWindow BackColor LargeChange OutlineColor ShaftColor ThumbColor Direction Max Position SmallChange Window Event PositionChanged CSerialManager Overview While the CSerialManager class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CSerialManager class provides the following method: Method OpenPort 94 CSerialPort Overview While the CSerialPort class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CSerialPort class provides the following methods and events: Methods ClearInputBuffer GetCTSHolding GetInputLen Read SetSettings ClearOutputBuffer GetDSRHolding GetOutputLen SetBreak Write GetBreak GetInputBufferSize GetSettings SetInputBufferSize Events PortError PortReadable CShell Overview While the CShell class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CShell class provides the following properties and methods: Properties CaretColor CaretWindow ScreenBlueMask ScreenHeight ScreenWidth CaretHeight FontManager ScreenDepth ScreenPalette Methods 95 CaretImage LogicalPalette ScreenGreenMask ScreenRedMask CreateCompatibleImage CreateTimer EnumNextDisplayMode GetFrameCanvas GetTempCanvas LoadOptimizedImage ShowFrame UpdateTempCanvas CreateFrame DestroyFrame GetCaretPosition GetOffscreenCanvas GetTimeMS SetCaretPosition TranslateColor CreateImage EnumFirstDisplayMode GetCurrentFrame GetScreenCanvas LoadImage SetDisplayMode UpdateFrame CSocket Overview While the CSocket class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CSocket class provides the following methods and events: Methods Close Shutdown Read Write ReadFrom WriteTo Events SocketClosed SocketWriteable SocketError SocketReadable CSocketAddress Overview While the CSocketAddress class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CSocketAddress class provides the following properties: Properties LocalPort RemoteAddress 96 RemotePort CSocketManager Overview While the CSocketManager class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CSocketManager class provides the following methods: Methods Connect GetAddressByHostName HostToNetShort CreateSocketAddress GetHostNameByAddress NetToHostLong CreateSocketServer HostToNetLong NetToHostShort CSocketServer Overview While the CSocketServer class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CSocketServer class provides the following method and events: Method IncludePort Events CanAcceptConnection NewConnection SocketError CSymbianLauncher Overview While the CSymbianLauncher class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CSymbianLauncher class provides the following method: 97 Method CreateApplication CSystem Overview While the CSystem class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CSystem class provides the following methods and events: Methods MaximizeApplication MinimizeApplication Events AppMaximized AppMinimized CTextEdit Overview While the CTextEdit class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CTextEdit class provides the following properties, method, and events: Properties 98 AlignmentHorizontal BackColor CaretColor Enabled ForeColorSelected MaxLength ScrollBars SelText TotalLines UnderlineColorSelected AlignmentVertical BackColorDisabled CurrentFont ForeColor Locked MultiLine SelLength Text UnderlineColor UnderlineStyle Appearance BackColorSelected DisplayableLines ForeColorDisabled MarginSize PasswordChar SelStart TopLine UnderlineColorDisabled Window Method Refresh Events Click TextChanged CTimer Overview While the CTimer class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CTimer class provides the following properties, methods, and event: Properties Period Running Methods Start Stop Event 99 Trigger CTimerManager Overview While the CTimerManager class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CTimerManager class provides the following property and method: Property TimerCount Method CreateTimer CTone Overview While the CTone class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CTone class provides the following properties, methods, and event: Properties Duration Frequency Methods Start Stop Event 100 Volume Done CWindow Overview While the CWindow class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CWindow class provides the following properties and methods: Properties Children Frame HorizontalScrollEnabled Left SuppressPaint VerticalScrollEnabled Depth Height InternalHeight Parent Top Visible Enabled HorizontalScrollBar InternalWidth Sibling VerticalScrollBar Width Methods AddChildWindow CapturePointer GetBounds GrabFocus Paint RefreshArea RemoveChildWindow CanDrawDirect CreateChildWindow GetVirtualOffset Invalidate PaintDirect ReleaseCaret SetBounds CanScrollDirect DestroyChildWindow GrabCaret InvalidateArea Refresh ReleasePointer SetVirtualOffset CWrappedString Overview While the CWrappedString class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The CWrappedString class provides the following properties and methods: Properties 101 CurrentFont VisibleLineCount TotalLineCount VisibleLineHeight TotalLineHeight WrappedString Methods Draw SetBounds GetBounds GetLineInformation IEventManager2 Overview While the IEventManager2 class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The IEventManager2 class provides the following methods: Methods EnqueKey Loop Flush Terminate Iterate Terminated IFontList Overview While the IFontList class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The IFontList class provides the following methods: Methods EnumFirstFont EnumNextFont IFontScanner Overview While the IFontScanner class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that 102 they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The IFontScanner class provides the following method: Method RescanFonts IScrollEvents Overview While the IScrollEvents class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The IScrollEvents class provides the following method: Method PositionChanged ISocketAddress_InetDatagram Overview While the ISocketAddress_InetDatagram class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The ISocketAddress_InetDatagram class provides the following properties: Properties LocalPort RemoteAddress RemotePort ITypedStream Overview While the ITypedStream class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. 103 The ITypedStream class provides the following methods: Methods ReadBoolean ReadDateTime ReadLong WriteBoolean WriteDateTime WriteLong ReadByte ReadDouble ReadSingle WriteByte WriteDouble WriteSingle ReadCurrency ReadInteger ReadString WriteCurrency WriteInteger WriteString IWindowEvents Overview While the IWindowEvents class provides visibility to a powerful set of low level services, these are not yet an officially supported part of the AppForge MobileVB™ Programming Interface. It is possible that they may provide utility in some advanced cases, but we cannot sanction or formally support their use at present. The IWindowEvents class provides the following methods: Methods BoundsChanging CapturedPointerEnter ContainsPoint FocusChanged KeyUp PointerMove VisibilityChanged 6.8 CanClose CapturedPointerLeave ContainsRect KeyDown Painting PointerUp AppForge Telephony Library AppForge Telephony Library Overview The AppForge Telephony Library provides the following classes: AppForge Telephony Library Classes 104 CanLoseFocus Closing EnabledStateChanged KeyPress PointerDown TouchesRect CSMSManager CTelAddress CTelCallCollection CTelPhoneDeviceCollection ITelCallEvents ITelPhoneDeviceEvents CSMSMessage CTelAddressCollection CTelephonyRoot ISMSEvents ITelephony_Nokia_S80 CSMSMessageCollection CTelCall CTelPhoneDevice ITelAddressEvents ITelephonyEvents CSMSManager Overview The CSMSManager class provides the following methods and events: Methods CreateMessage GetMessages Events MessageDeleted MessageReceived MessageFailed MessageSent MessageMoved CSMSMessage Overview The CSMSMessage class provides the following properties and methods: Properties Body Subject Folder Timestamp PhoneNumber Methods Delete Save Send CSMSMessageCollection Overview The CSMSMessageCollection class provides the following methods: 105 Methods Count Item CTelAddress Overview The CTelAddress class provides the following properties, methods, and event: Properties Calls Name Capabilities State Close Open CreateCall HookState Methods DestroyCall Event IncomingCall CTelAddressCollection Overview The CTelAddressCollection class provides the following methods: Methods Count Item CTelCall Overview The CTelCall class provides the following properties, methods, and events: Properties 106 Capabilities State DialableAddress Name Methods Answer Drop Close Open Dial Events Connected Connecting Disconnected CTelCallCollection Overview The CTelCallCollection class provides the following methods: Methods Count Item CTelephonyRoot Overview The CTelephonyRoot class provides the following properties and methods: Properties DeviceType PhoneDevices Methods Initialize UnloadPhoneDevice LoadPhoneDevice 107 Shutdown CTelPhoneDevice Overview The CTelPhoneDevice class provides the following properties and methods: Properties Addresses State Capabilities Name Methods Close Open CTelPhoneDeviceCollection Overview The CTelPhoneDeviceCollection class provides the following methods: Methods Count Item ISMSEvents Overview The ISMSEvents class provides the following methods: Methods MessageDeleted MessageReceived MessageFailed MessageSent ITelAddressEvents Overview The ITelAddressEvents class provides the following method: Method IncomingCall 108 MessageMoved ITelCallEvents Overview The ITelCallEvents class provides the following methods: Methods Connected Connecting Disconnected ITelephony_Nokia_S80 Overview The ITelephony_Nokia_S80 class provides the following properties and methods: Properties DeviceType PhoneDevices PhonePowerOn Methods Initialize UnloadPhoneDevice LoadPhoneDevice 109 Shutdown 7 AppForge MobileVB™ Data Synchronization 7.1 Overview One requirement common to a large majority of mobile applications is the ability to effectively transfer information between a device and a backing data store residing on either a desktop system or on a server. This problem is typically referred to as data synchronization, and, in its general case, can be extremely complex. Several companies have developed entire product lines that assist developers in creating customizable synchronization solutions that accommodate arbitrary data formats, and a variety of synchronization policies. AppForge MobileVB supports a number of different alternatives for data storage in mobile applications. Each platform on which MobileVB applications are enabled has one or more native database formats. In addition to supporting these native formats, AppForge offers an implementation of the Palm OS Database format (and supporting library) on all platforms. For details on the data storage options provided with MobileVB, see theAppForge Data Storage document. Data Storage PDB (Palm Database) SQL Server-CE Pocket Access Symbian OS Details PDB files constitute the native data format for Palm OS applications. While the PDB file format, in general, supports relatively unstructured data, theAppForge PDB Library supplied in the MobileVB environment makes it easy to impose a schema on the data within a PDB. This allows some ability to generalize a synchronization solution based on this data format since fields within a PDB can be easily associated with fields in a table that is part of an ODBC data source. For devices running Palm OS, data synchronization is typically accomplished through the hot sync manager. This process relies on the existence of a database-specific conduit that provides individual records to a controlling synchronization process. TheAppForge Universal Conduit Guide details the use of the Universal Conduit provided with MobileVB. SQL Server-CE provides a tight coupling between a server-side SQL Server database and a client application. Microsoft provides two synchronization technologies when working with SQL Server-CE: replication, and remote data access (RDA). See theUsing the Database Model with SQL Server CE section of the AppForge Data Storage documentation for details. Pocket Access, through the Microsoft ActiveSync software, provides data synchronization with a backend ODBC data source. See theUsing the Database Model with Pocket Access section of the AppForge Data Storage documentation for details. Symbian OS provides a native relational database that can be accessed through the AppForge Database model. Symbian does not, however, provide a means of synchronizing these databases with any data store on a server. For further details see theUsing the Database Model with Symbian OS Databases section of the AppForge Data Storage documentation for details. 110 7.2 AppForge Universal Conduit Guide Overview The AppForge Universal Conduit (UC) is an extension of HotSync Manager™ that allows for data synchronization between Palm® Databases (PDBs) and Open Database Connectivity (ODBC) databases on the PC. ODBC is a standard protocol for database servers that provides a common interface for applications to gain access to a database. The Universal Conduit can be used with most popular databases for which an ODBC driver exists, including Microsoft® Access™ , SQL Server™ , and Oracle® . PDBs are different from most other databases in that each PDB stores only one table, and constraint checking is not performed (e.g., PDBs do not have primary keys). It is the developer’s responsibility to maintain appropriate database constraints within his or her Palm OS® application. The AppForge Universal Conduit is only available in MobileVB™ for use with Palm OS® . What is a conduit? A Palm "conduit" is a standard Windows® application that runs on a host desktop computer (or a network server) and can read and write Palm databases (PDB files) on a connected Palm device. How do conduits work? When a handheld user installs a conduit on a desktop computer, the HotSync Manager™ adds that program to its list of local conduits that want to participate in the next HotSync session. When the Palm user initiates a HotSync, the HotSync Manager first establishes a communications link between the host computer and the connected handheld device. Then, it launches each conduit in turn. After each conduit has exchanged data with the handheld, the HotSync Manager closes the communications link, and the HotSync session ends. What can conduits do? Because they are standard desktop applications, conduits have access to the same features and functions that any standalone application does. Although it is common for conduits to present little or no user interface, and to be primarily concerned with shuttling data back and forth between the host computer and the device, these are not strict requirements. Typically, a conduit’s primary job is to "synchronize" two data sources - a PDB database on the Palm device, and a parallel database or file on the host computer. Data on the device is accessed via the Palm® API functions, and the host’s data is accessed via a provided driver or subsystem (ODBC, ADO, etc.), or through the native file I/O features of the programming language. 111 How is the AppForge Universal Conduit different from other conduits? The AppForge Universal Conduit is a single program that can synchronize multiple databases (belonging to multiple applications) during a HotSync™ session. Normally in Palm OS® , each application would require its own conduit. Instead, the AppForge Universal Conduit is a single DLL that can synchronize all your databases for all your MobileVB™ programs. You set up the Universal Conduit by creating a Universal Conduit Descriptor (UCD) for each database that will be synchronized. A UCD is an entry that describes how an application should synchronize with a host database. Before Starting • Palm OS does not allow two conduits with the same creator ID to be synchronized in the same HotSync session. Windows 95, Windows 98, Windows 2000, Windows NT, Access, SQL Server and Visual Basic are trademarks or registered trademarks of Microsoft Corporation in the United States and/or other countries. HotSync, HotSync Manager and Palm OS are trademarks or registered trademarks of Palm, Inc. Installation on the Developer’s System Use the AppForge Universal Conduit Configuration tool (UCConfig.exe) to create a Universal Conduit Descriptor for your application. The Universal Conduit is compatible with Palm® Databases (PDBs) created by the AppForge Database Converter, as well as databases created using the AppForge PDB library. When a UCD is enabled on your system, you can test its functionality with your application. Setting Up an ODBC Data Source The UC does not have direct support for any native database file types. Instead, it accesses databases through an ODBC interface. Some initial setup in Windows® is required before creating a conduit, as each database must have a unique Data Source Name (DSN). 1. Find "ODBC Data Sources" in your Windows control panel. Click Start -> Settings -> Control Panel -> ODBC Data Sources. (In Windows 2000® , ODBC Data Sources is located inside the Administrative Tools folder in the Control Panel.) 2. Under the "User DSN" tab, click "Add..." to add a new data source Pick a driver based on the type of database you are using and continue. 112 3a. Pick Select to use an existing database. An existing database could be a Microsoft Access database (.MDB file) that was converted to the initial Palm® Database. If you create a new database, you must then open the database to create a schema that matches the PDB you will be using. or: 3b. Pick Create to create a new database. After creating the database, open it to create a table schema that matches the PDB you will be using. 4. Give your database a unique Data Source Name (DSN). The DSN identifies the database connection to the Universal Conduit. Creating a Universal Conduit Descriptor Once a DSN has been established for your database, run the AppForge Universal Conduit Configuration program. When you installed MobileVB™ , UCConfig.exe should have been installed in the "Universal Conduit" subfolder. (The default path is C:\Program Files\AppForge\Universal Conduit\UCConfig.exe.) Note: This program is not for intended to be used by end users, as it can damage HotSync Manager settings if used improperly. AppForge Universal Conduit Wizard Click New to start the AppForge Universal Conduit Wizard and enter the following information: 1. Universal Conduit Descriptor Name Enter a name to identify your Universal Conduit Descriptor. This name will also display on the PC during each HotSync™ operation. 2. Palm Creator ID The creator ID of the Palm® application using the PDB. Visit www.palm.com to register a unique ID. See the AppForge MobileVB™ User’s Guide for more information. 3. ODBC Data Source Name This is the DSN for the data source, from the ODBC Data Sources control panel applet. 4. Tables to Synchronize Select the tables from the specified DSN that you wish to synchronize during a HotSync operation. The name of each PDB must match the name of the corresponding table set for the DSN. 5. Sync Type Select how the PC database and handheld database should interact. 113 Do nothing Two-way Palm replaces PC PC replaces Palm Palm appends to PC PC appends to Palm The databases do not synchronize. The databases are synchronized with each other, so that changes made in one database are recorded in the other. If the same record has been modified or added in both databases, the new information from the PDB takes precedence and overwrites the information from the PC database. All information from the PDB completely overwrites the information in the PC database. All information from the PC database completely overwrites the information in the PDB. Records that exist only on the Palm are copied to the PC. No records are copied from the PC to the Palm. Records that exist only on the PC are copied to the Palm. The PC database remains unchanged. Table 5: Sync Type Fields 6. Sync Keys For each table you choose, select sync keys from the Key Fields box. If the host table has a primary key that uniquely identifies each record, you must select that as the sync key. Palm databases do not perform constraint checking. This could lead to unwanted conflicts in the primary key fields or other fields. When the UC performs database synchronization, an insertion into the PC database may fail due to primary key violations. (You can customize the behavior of the Universal Conduit when a conflict occurs by clicking Configure -> Advanced Settings once setup is complete.) 7. Automated File Creation (optional) For each table selected earlier, you have the option of creating a new Palm Database that contains the records for the selected tables. You can also create MobileVB™ code modules for each table, making database access easier during programming. Activating a Conduit When you are finished creating a new UCD, activate it by checking the box next to its name. The next time a HotSync™ is performed, all checked UCDs will perform their specified database synchronizations. Configuring a Universal Conduit Descriptor Enable a Universal Conduit Descriptor by checking the box next to its name. The next time a HotSync™ operation is performed, each enabled UCD will synchronize its related tables. Basic Settings 114 To view or change the basic settings for a UCD, select it and click "Configure". You can change the ODBC Data Source, the tables to be synchronized, sync keys, and the sync type for each table. Creator ID The creator ID of the Palm® application using the PDB. ODBC Data Source Name (DSN) This is the DSN for the data source, from the ODBC Data Sources control panel. DSN Tables Select the tables from the specified DSN that you wish to synchronize during each HotSync™ . The names of the Palm Databases you wish to synchronize must match the table names set for the DSN. If the expected tables are not displayed, select "ODBC Data Sources" from the Windows® Control Panel and assign the correct database to the DSN. (See "Setting Up an ODBC Data Source" in the "Installation on the Developer’s System" section for more information.) Table sync type Select how the PC database and handheld database should interact. Do nothing Two-way Palm replaces PC PC replaces Palm Palm appends to PC PC appends to Palm The databases do not synchronize. The databases are synchronized with each other, so that changes made in one database are recorded in the other. If the same record has been modified or added in both databases, the new information from the PDB takes precedence and overwrites the information from the PC database. All information from the PDB completely overwrites the information in the PC database. All information from the PC database completely overwrites the information in the PDB. Records that exist only on the Palm are copied to the PC. No records are copied from the PC to the Palm. Records that exist only on the PC are copied to the Palm. The PC database remains unchanged. Table 6: Sync Type Fields Advanced Settings Click the Advanced Settings tab to change preferences regarding sync tables and host tables. Discard Archived Records, Discard Conflict Records The Discard Archived Records option causes PDB records that are deleted and marked "archive" to be removed, rather than saved in a corresponding sync table on the PC. 115 The Discard Conflict Records option causes PDB records that cannot be inserted into the host table to be removed, rather than saved in a corresponding sync table on the PC. Before Action Use the Before Action box to specify a command line to execute before database synchronization takes place for this UCD. After Action Use the After Action box to specify a command line to execute once the Universal Conduit has completed synchronization for this UCD. Log File Specify a text file to record the Universal Conduit’s actions for this UCD. If the file does not exist, it will be created. If the file exists, it will be appended with new information during the next synchronization. Sync Table To save archived or conflicting records, the PC database must contain a sync table with the following name: <host-table-name>_hh It must contain all the fields from the original table, plus three additional fields: Field Name afsyncDate afsyncRecordId afsyncDisposition Description Contains the date and time of the HotSync that resulted in the conflict Contains the record identification from the PDB Contains 1 when a conflict occurred and 2 when a record was archived. Data Type date/time 32-bit integer byte Table 7: Sync Table Fields If you anticipate not being able to include a PC database, or do not wish to include a host or sync table, you can specify an SQL command to create the host or sync table (see below). Recreate Missing Tables 116 The AppForge Universal Conduit allows you to write your own SQL commands to create host tables or sync tables within a database. SQL Command to Re-create Host Tables If you wish to specify the schema of the host table as an SQL statement, enter the SQL command here. Use this feature if you expect the end user’s PC database will not be set up with the correct schema for the host table. (Alternatively, you could distribute a PC database file with the correct schema already defined.) The host table must have the same schema as the corresponding handheld database. SQL Command to Re-create Sync Tables If you wish to specify the schema of the sync table as an SQL statement, enter the SQL command here. Use this feature if you expect the end user’s PC database will not be set up with the correct schema for the sync table. (Alternatively, you could distribute a PC database file with the sync table, as defined below, already created.) The Universal Conduit must be able to write to this table to record conflicts and archived data. A frequent use for this option is to force the sync table (suffixed with "_hh") to be created only on demand. This is useful because, in practice, the sync table only needs to be created if a conflict or archive record is encountered. The sync table must be named <host-table-name>_hh. The last three fields in the sync table must be afsyncDate, afsyncRecordId, and afSyncDisposition, as described above in the Sync Table section. Installation on the End User’s System The Universal Conduit Configuration application included with the Universal Conduit package is a great tool for developers, as it allows for easy configuration and reconfiguration for testing purposes. However, it is not appropriate to give this application to an end user. To make the installation process as easy as possible for the end user, you may wish to create a custom setup package that copies the application’s files and configures the Universal Conduit and UCDs for the application. Preliminary Installation Steps The following are typical steps required to configure an application using a custom installer: Check Target System Requirements Validate that the target system meets the suggested requirements of the Universal Conduit: 117 - ODBC 3.5 or later (for best Unicode support) - HotSync Manager 3.0 Install the Universal Conduit Runtime (UCRunSetup.exe) Universal Conduit Runtime Support is a redistributable setup application, called UCRunSetup.exe, that can be included with an application’s installer. This program must be installed before UCConfigCmd.exe can be used to configure Universal Conduit entries. Many installer creation utilities allow you to perform a "sub-install". You can use such a facility to launch UCRunSetup.exe during your installation process. Create an ODBC Data Source Name (DSN) Some installer creation utilities allow you to specify DSNs to be created during installation. If your installer creation utility does not provide this mechanism, you will need to find a way to create a DSN on the target machine for your specific ODBC driver. Consult your Database Management System for more information. Configuring a Universal Conduit Descriptor for End Users There are three basic options for installing a UCD on the end user’s system. Option 1: Deploy UCConfigCmd.exe temporarily onto the end user’s system. It is recommended that you use UCConfigCmd.exe to create UCDs if you create an installer to deploy your own Universal Conduit-based applications. This command-line tool allows for easy configuration from .bat files, scripts, and almost any install program, all without having to write any code. See the Reference section for command-line specifics. Option 2: Deploy UCConfig.dll temporarily onto the end user’s system. UCConfig.DLL contains code to help you configure your UCD. The easiest way to interface with the DLL is to write a Visual Basic application containing modUCConfig.bas. This module can be found in the Universal Conduit’s installation directory, and contains a well-documented API for UCConfig.DLL. (It is possible to use this API from C/C++, but this is generally not recommended, as it was designed for use with Visual Basic.) Option 3: You can write custom code to directly modify the proper registry entries. This is generally not recommended. Visit the AppForge Developer Sector at www.appforge.com for registry information. 118 Using UCConfigCmd.exe The Universal Conduit comes with a command-line program called UCConfigCmd.exe that allows you to easily create a UCD on the end user’s system. Here are the command-line options for UCConfigCmd: /HELP Syntax UCConfigCmd /HELP [<topic>] Details <topic> The command for which you want help. This can be one of the following: UCD Commands: ADD, DEL, ENABLE, DISABLE, LIST Table Commands: ADDTABLE, DELTABLE, CLEARTABLES, LISTTABLES /ADD Syntax UCConfigCmd /ADD <Conduit> /DSN:<DSN> /CREATOR:<Creator> [/LOGFILE:<LogFile>] [/INIFILE:<ConfigFile>] [/DISABLE] [/BEFOREAPP:<App to be run before sync>] [/AFTERAPP:<App to be run after sync>] [/OPENPARAMS:<Open Params>] Details Adds a new Universal Conduit Descriptor (UCD) <Conduit> The name of the UCD to add, as it should appear in the HotSync Manager /DSN:<DSN> The name of the ODBC Data Source Name that defines the connection to the host database /CREATOR:<Creator> The Creator ID of the MobileVB™ application this UCD should synchronize; this can either be a four-character ASCII Creator ID or a 32-bit number expressed in hexadecimal of the form 0xDDDDDDDD, where D is a hexadecimal digit /LOGFILE:<LogFile> The path (including the filename) of a log file to which to which the Universal Conduit can append a record of its action for this UCD; a log file can be very helpful in understanding how each synchronization type can be used 119 /INIFILE:<ConfigFile> (Advanced) Overrides the default location of the driver configuration file used by the Universal Conduit; the driver configuration file defines mappings of driver-specific data type descriptions onto normalized AppForge types. /DISABLE Marks this UCD as disabled, preventing it from participating in synchronization /BEFOREAPP:<App to be run before sync> The path (inclding the filename) of an application to be run before adding the UCD. /AFTERAPP:<App to be run after sync> The path (inclding the filename) of an application to be run after adding the UCD. /OPENPARAMS:<Open Params> Extra "uid=MyUser;pwd=MyPass;" parameters for SQL connect statement, ie: /DEL Syntax UCConfigCmd /DEL <Conduit> Details Deletes an existing Universal Conduit Descriptor (UCD) <Conduit> The name of the UCD to be deleted, as it appears in the HotSync Manager /ENABLE Syntax UCConfigCmd /ENABLE <Conduit> Details Enables an existing Universal Conduit Descriptor (UCD), allowing it to participate in synchronization <Conduit> The name of the UCD to enable as it appears in the HotSync Manager /DISABLE Syntax UCConfigCmd /DISABLE <Conduit> Details Disables an existing Universal Conduit Descriptor (UCD), preventing it from participating in synchronization 120 <Conduit> The name of the UCD to disable, as it appears in the HotSync Manager /LIST Syntax UCConfigCmd /LIST Details Lists all Universal Conduit Descriptors (UCDs) that have been created /ADDTABLE Syntax UCConfigCmd /ADDTABLE <Conduit> <Table> /SYNCTYPE:<0-5> /KEYFIELDS:<KeyFields> [/DISCARD_ARCHIVES] [/DISCARD_CONFLICTS] [/CREATEHOSTTABLESQL:<SQL>] [/DISCARD_ARCHIVES] [/DISCARD_CONFLICTS] [/CREATEHOSTTABLESQL:<SQL>] [/CREATESYNCTABLESQL:<SQL>] Details Adds an additional table to be synchronized for an existing Universal Conduit Descriptor (UCD) <Conduit> The name of the UCD to which the table will be added, as it appears in the HotSync Manager <Table> The name of the table, as it appears within the ODBC database /SYNCTYPE:<0-5> The method of synchronization to use for this table. The values are: 0 = Do Nothing (do not synchronize this table); 1 = Two-way synchronization; 2 = PC appends to Handheld; 3 = Handheld appends to PC; 4 = PC replaces Handheld; 5 = Handheld replaces PC. /KEYFIELDS:<KeyFields> The fields used to define the sync key. If the host table has a primary key, you must use it as the sync key. The format is: <zero-based-field-index>:<field-name> [,<zero-based-field-index>:<field-name> ...] For example, you might define a sync key as follows: ... /KEYFIELDS:"0:Phone, 3:LastName, 4:FirstName" ... to define a sync key composed of fields 0, 3, and 4, named "Phone", "LastName", and "FirstName". [/DISCARD_ARCHIVES] Indicates that archived records should be ignored and not inserted into a sync table; by default, archived records are saved in a sync table [/DISCARD_CONFLICTS] Indicates that conflict records should be ignored and not inserted into a sync table [/CREATEHOSTTABLESQL:<SQL>] Used to define an SQL command that will recreate the host table if it does not exist; see the Universal Conduit help for more information on this feature 121 [/CREATESYNCTABLESQL:<SQL>] Used to define an SQL command that will recreate the sync table if it does not exist; see the Universal Conduit help for more information on this feature /DELTABLE Syntax UCConfigCmd /DELTABLE <Conduit> <Table> Details Deletes a table from an existing Universal Conduit Descriptor, removing it from synchronization <Conduit> The name of the UCD from which the table will be removed, as it appears in the HotSync Manager <Table> The name of the table, as it appears within the ODBC database /CLEARTABLES Syntax UCConfigCmd /CLEARTABLES <Conduit> Details Removes all tables from an existing Universal Conduit Descriptor (UCD) <Conduit> The name of the UCD from which all tables will be removed, as it appears in the HotSync Manager /LISTTABLES Syntax UCConfigCmd /LISTTABLES <Conduit> Details Lists all the table associated with a Universal Conduit Descriptors (UCD) <Conduit> The name of the UCD, as it appears in the HotSync Manager, whose tables will be listed /HSRESTART Syntax UCConfigCmd /HSRESTART Details 122 Restarts the HotSync Manager. Understanding Key Fields If you experience problems such as duplicate records, records being unintentionally overwritten, or slow syncs, picking appropriate key fields may help eliminate the problem. Key fields are a set of fields that match the host table’s primary key – that is, they uniquely identify each record. Each record must have a different set of values in its key fields. Although a single field may contain duplicates, the set of values in all these fields must be unique for each record. This is how a record is uniquely recognized, and how the UC knows when two records, one on the Palm and one on the PC, are the same record. Some databases contain natural key fields. A list of books might have an ISDN field, or a list of people a social security number field. Key field conflicts are not checked in Palm® Databases, but they often are checked in PC databases. For example, if a Palm® user creates two entries in a PDB with identical primary keys, no error message is generated. However, during the next HotSync™ an error would occur if the UC tried to enter both records into a PC database. To resolve possible conflicts without losing data, the UC attempts to insert the problematic record into a sync table in the host database. This sync table contains any records that could not be inserted into the database during the HotSync™ operation. Things to remember when selecting a sync key - If your database contains a primary key, you must select it as your sync key. - The sync key should not contain fields that can be set to null. - Names of fields within the sync key – all fields, in fact – must not contain spaces, nor may they be given names that conflict with keywords defined for the host DBMS in use. For example, naming a field "Patient ID" would be illegal because field names may not contain spaces. Another example of a bad field name is "Integer", because this would conflict with data types names in many DBMSs. - The sync key should not contain fields of type Single or Boolean. Although doing so is allowed, floating-point types can difficult to check for equality, while Boolean types may sort differently across difference DBMSs. - Do not depend on case sensitivity in a string to uniquely identify a record, as case is ignored during sync key comparison. 123 Glossary afsyncDate afsyncDate is a field within every sync table that stores the date and time at which an archive or conflict record was added. This field must be the third-to-last column in a sync table. It must be able to store a date and time, and should map to a Visual Basic Date type. Note that the name of the data type for this field is DBMS-specific, although it is often "datetime" or "date." afsyncRecordId afsyncRecordId is a field within every sync table that stores the Palm Record Id for each archive or conflict record that was added. This field must be the second-to-last column in a sync table. It must be able to store a 32-bit value, and should map to a Visual Basic Long type. Note that the name of the data type for this field is DBMS-specific, although it is often "int" or "integer." afsyncDisposition afsyncDisposition is a field within every sync table that stores the disposition for each archive or conflict record that was added. A value of 1 in this field means that the record is a conflict record. A value of 2 in this field means that the record is an archive record. This field must be the last column in a sync table. It must be able to store an 8-bit value, and should map to a Visual Basic Byte type. Note that the name of the data type for this field is DBMS-specific, although it is often "tinyint" or "byte." Archive record A record that has been deleted from a Palm Database (PDB) and has been marked Archived. Archive records are inserted into the sync table, if one is defined, with a record disposition of 2. See the documentation for PDBDeleteRecordEx in the AppForge MobileVB User’s Guide for a description of different forms of record deletion (one of which is archival). Conflict record 124 A conflict record is a record that could not be inserted in a host table due to a primary key violation or other integrity constraint violation. Conflict records are inserted into the sync table, if one is defined, with a record disposition of 1. Data Source Name (DSN) The name of a database connection, as specified within the Windows Control Panel. DSNs provide a single name for the multiple parameters needed to establish a database connection with an ODBC database. Each UCD has an associated DSN. Database Management System (DBMS) A database engine that runs on a desktop computer or server and is optimized for manipulating large quantities of data. Each company that provides a database engine is referred to as a DBMS vendor. Disposition Indicates why a record was added to the sync table. Host table A table defined within an ODBC database that participates in the synchronization process. For example, a Palm Database called Recipes.pdb would synchronize with a host table called Recipes, which is a table that is accessible by opening an ODBC data source. Normalized schema A host table for which each field type has been normalized. For example, if the table has fields of type "tinyint, bit", then normalized schema might be "ftByte, ftBoolean." Normalized types One of the simple Visual Basic types supported by MobileVB™ : Byte, Integer, Long, String, Single, or Date. Each DBMS defines its own set of data types that can be used to define field types within database tables. Since some types are vendor-specific, the Universal Conduit can use a mapping file (called UCTypes.ini by default), to map DBMS types onto the set of Visual Basic types defines above. For example, Microsoft SQL Server stores 8-bit quantities using a data type called "tinyint." There is an entry in UCTypes.ini for SQL Server that specifies that tinyint maps to ftByte (the "ft" is used to indicate that it is a normalized type name). 125 Note that modifying the mapping file is an advanced topic. Visit the AppForge Knowledge Base for more information. ODBC Open Database Connectivity is a common database API introduced by Microsoft. Many database vendors provide ODBC-compatible drivers. The AppForge Universal Conduit works with many ODBC-compatible databases. Palm Creator ID A four-character code that uniquely each Palm application. Creator IDs should be registered on the Palm OS web site (http://www.palmos.com). Sync key A sync key is associated with a table, and defines the set of fields that determine identity of a record. The sync key is used to compare records between a Palm database and a corresponding host table. The table below shows an example of a sync key of type ID: Palm Record A - ID Field 1 2 3 10 Palm Record A NAME Field Samuel James John Freddy Host Record B - ID Field 1 2 4 8 Host Record B NAME Field Samuel David Jenny Sarah Sync comparison A=B A=B A<B A>B Table 8: Sync Key Glossary Entry Sync table A table defined within an ODBC database that stores archive or conflict records encountered during synchronization. For example, if an archived record is encountered while synchronizing a Palm Database called Recipes.pdb, the Universal Conduit would attempt to insert the archived record in the sync table, called Recipes_hh. Note that the name of a sync table is always the name of its corresponding host table with the suffix "_hh". Universal Conduit Descriptor (UCD) 126 An entry that indicates how a particular application should synchronize. A UCD defines the name that should be displayed during synchronization, the tables that should be synchronized, and many other properties. UCDs appear as normal conduits within the HotSync Manager display, although they are actually all managed by the Universal Conduit. 127 8 AppForge Fuser Technology 8.1 Introduction To Fusers MobileVB™ applications can draw from a wide variety of controls (Ingots) and libraries supplied with the native product. There are times, however, when a program may need to access some system level API or other external library that is not exposed directly to Visual Basic® . Fusers provide a fairly simple solution for applications with this requirement. By providing a "standard way of being non-standard", fusers allow information to be passed in and out of a MobileVB™ program to an external software module. The precise form of a fuser varies from system to system. In Microsoft-based systems (Win32, Windows CE, Pocket PC) for example, fusers are implemented as standard .dll files that would typically be written in C/C++. Similarly, under Symbian OS, fusers are standard polymorphic .dlls. On Palm, fusers take the form of a separate .prc application with a set of custom launch codes. 8.2 Fuser Architecture At a high level, a fuser is a collection of functions f(i) all possessing identical signatures and all residing in a common dynamically loadable module. The expected signature for any of the functions f is void f( void* ); Each fuser function f(i) is addressable by a name n(i )(specified as a character string) that is unique within the containing module. A Visual Basic program accesses the services of a particular fuser by first creating amodule object that represents the containing fuser. This module object provides a mapping from a unique name n(i) to afunction object that is usable from Visual Basic. Ultimately, thefunction object provides a proxy to transfer control to the underlying function f(i). The Visual Basic program, by way of thefunction object can pass in a pointer to an arbitrary data structure from the Visual Basic address space (via theVarPtr directive) that appears as the incoming"void*" argument to the target function. This data structure needs to provide slots for the receiving C++ code to extract any input arguments, and return any outgoing arguments. Because the layout of the data structure (typically via a user defined type) is completely determined by the Visual Basic compiler, it is critical that the receiving code in the fuser interprets this layout correctly. The following figure illustrates the corresponding memory layout of Visual Basic and C++ structures. 128 Figure 1: Corresponding memory layout in Visual Basic and C++ 8.3 Creating a Fuser The MobileVB™ install contains a set of headers and libraries that assist in creating a fuser. These are located in the "Fuser SDK" directory under each specific platform. For example, the headers and linkable libraries for ARM-based platforms can be found in "...\AppForge\Platforms\WinCE\ARM\FuserSDK" Pocket PC and Windows CE Fusers on Pocket PC or Windows CE systems are implemented as standard .dll files that expose a set of public functions via a .def file. As noted in theFuser Architecture section, each function should expect to receive as an argument a void pointer that can then be cast to a structure that reflects the layout of the referenced Visual Basic data structure. The names exported in the .def file become the names used when retrieving a function object from the module. 129 Symbian OS Under the Symbian OS, fusers are implemented as polymorphic .dll files. Because functions within a .dll are referenced by ordinal number, the Symbian fuser logic expects the fuser author to provide a translation function that maps a given function name into the corresponding ordinal number. This translation function is expected to be the present at ordinal one within the fuser .dll.. The source code below (excerpted from the sample fuser implementation for Symbian OS) illustrates a simple mapping from an incoming function name to an ordinal number. The fuser defines four entrypoints, "fnSquare", "fnDouble", "fnReverse", and "fnBumpDate" that correspond to ordinal numbers 2 through 5 respectively. (as defined in the corresponding .def file for the .dll.) EXPORT_C TInt32 af01_nameLookup(const TUint16* funcName) { TPtrC16 desFuncName(funcName); TInt funcLookup = -1; // Initialize to invalid lookup if (desFuncName.Compare(_L("fnSquare")) == 0) funcLookup = 2; else if (desFuncName.Compare(_L("fnDouble")) == 0) funcLookup = 3; else if (desFuncName.Compare(_L("fnReverse")) == 0) funcLookup = 4; else if (desFuncName.Compare(_L("fnBumpDate")) == 0) funcLookup = 5; return funcLookup; } Palm OS Fusers under Palm OS are actually separate Palm applications. They do not necessarily need to be marked as type "APPL" since they won’t in general be launched other than by a MobileVB™ program. Each fuser function is implemented as a separate custom launch code in this Palm application. Note: Palm OS defines a special constant,sysAppLaunchCmdCustomBase that denotes the first available custom launch code. A mapping defined in the reserved launch code0xFFFF provides the unique name of each function. The implementation of this launch code should retrieve a requested function namen from thecmdPBP argument that the application is invoked with. If the given name is associated with a supported function, the launch code of that function is returned. Specifically, on entry to PilotMain in the fuser, thecmdPBP argument points to a structure of typetAppForgeNameLookup that contains two elements: a name and a launch code. A typical sequence used in mapping a name to a function for Palm OS follows. 130 UInt32 PilotMain( UInt16 cmd, MemPtr cmdPBP, UInt16 launchFlags) { switch (cmd) { case sysAppLaunchCmdCustomBase + 0: fnSquare((int*)cmdPBP); break; case sysAppLaunchCmdCustomBase + 1: fnDouble((int*)cmdPBP); break; case sysAppLaunchCmdCustomBase + 2: fnReverse((void**)cmdPBP); break; case sysAppLaunchCmdAppForgeNameLookup: tAppForgeNameLookup *pLook = (tAppForgeNameLookup*)cmdPBP; Char *pFunc = (Char*)MemHandleLock(pLook->mhFuncName); if(pFunc == 0) break; if(StrCaselessCompare(pFunc, "fnSquare") == 0) pLook->launchCmd = sysAppLaunchCmdCustomBase + 0; else if(StrCaselessCompare(pFunc, "fnDouble") == 0) pLook->launchCmd = sysAppLaunchCmdCustomBase + 1; else if(StrCaselessCompare(pFunc, "fnReverse") == 0) pLook->launchCmd = sysAppLaunchCmdCustomBase + 2; MemHandleUnlock(pLook->mhFuncName); break; default: break; } Special Data Types There are two standard Visual Basic data types that require special handling when being manipulated from C++: Date, and String. When either of these types is passed into a fuser, the receiving code must use some special functions (provided in the "fuser glue" library) to convert the incoming argument to a native system equivalent. Similarly, when returning a Date or String back to Visual Basic from a fuser, corresponding routines are available to create a new instance of the element. Note: It is not safe to directly modify input variables of either of these types. Proper practice is to treat the input date or time as read-only and return any modification in a separate instance. 131 The conversion functions are summarized in the following table. From Visual Basic String C++ Visual Basic Date C++ 8.4 To C++ Palm OS AFStringToMemHandle Pocket PC / Windows CE AFStringToWideCharPtr Visual Basic String C++ MemHandleToAFString WideCharPtrToAFString AFDateToDateTime AFDateToDateTime Visual Basic Date DateTimeToAFDate DateTimeToAFDate Calling A Fuser Viusal Basic programs access fusers by setting a reference to the "AppForge Fuser Functions." This provides two new objects,AFFuserModule , andAFFuserFunction . TheFuserModule object has a single property,ModuleName , that can be set to the name of the .dll or .prc containing the fuser. Specific functions from that module can then be retrieved by theGetFunction method and assigned to variables of typeAFFuserFunction . Typically, fuser functions will need to pass in and possibly receive back some data. This can, in general, be accomplished by defining auser defined type in Visual Basic that lays out all the relevant parameters. TheExecute method of the Function object takes a pointer to an instance of the UDT as an argument, ultimately allowing the implementing C++ code to gain access to the memory of this instance. For example, a fuser that takes an integer and returns a string reflecting the English spelling of the number might be invoked as follows. Public Type SomeType n as integer s as string End type Dim st as SomeType Dim m as new AFFuserModule ’Setting the ModuleName property below ’implicitly finds "MyGreatFuser.dll" or "MyGreatFuser.prc" ’depending on the underlying OS. m.ModuleName = "MyGreatFuser" f = m.GetFunction("EnglishName") st.n = 2 132 f.Execute(VarPtr(st)) MsgBox st.s 8.5 Building and Running the Fuser Samples AppForge MobileVB includes a simple example of a fuser that can be built under each supported platform. There is also a corresponding Visual Basic project group containing implementations for each platform that make use of the functions exposed by the fuser. All Fuser sample files are located in the VB Toolkit\Samples\Fuser folder of a typical install of AppForge MobileVB. Palm OS Building the sample fuser for the Palm OS platform requires the Metrowerks™ CodeWarrior™ compiler. The sample project includes a .mcp file that defines all the necessary compiler settings to build the fuser. (note that it may be necessary to adjust access paths, etc. to reflect a particular installation.) A successful build creates the file "SampleFuser.prc" which can be downloaded to a Palm OS device via HotSync. Pocket PC The Microsoft Embedded Visual C++ compiler is used to build the sample fuser in the Pocket PC environment. An example workspace (.vcw) is included with the source for this project. When deploying the fuser to the device, it is important to align the location of the .dll with the path at which the Visual Basic application expects to find it. In the sample Visual Basic project for fusers, the statement that sets the location of the module to load resides in common code, and hence simply sets the fuser location to the relative path, "SampleFuser". Under Pocket PC, this means that the fuser .dll should be found in the same directory as the Visual Basic application. Symbian OS Creating a fuser for the Symbian environment is slightly more complex than the other two environments due to the fact that it is necessary to use different tools to build a .dll file that works with the emulator versus a .dll that runs on an actual device. The emulator runs under Win32, and executes libraries that target the standard PC instruction set. Consequently, it is possible to use the Visual C++ environment to build and test fusers that are intended to run within the emulator. By contrast, the Nokia Communicator series relies on the ARM processor. Code for this processor is built with the "gcc" compiler. 133 The MobileVB installation includes the requisite files for each of these two environments: a Visual C++ project and workspace (.dsp and .dsw respectively) can be used to build the fuser for use with the Nokia emulator, and a standard Symbian .mmp can be used to create the ARM version of the fuser.* As noted in the Pocket PC directions above, the location of the fuser file on the device or emulator should be coordinated with the location of the module specified within the Visual Basic code. In the case of the sample Visual Basic project, this means that the fuser .dll should reside in the same directory as the Visual Basic project on the device. * Note - due to the nature of the Symbian build scripts, it is not possible to reference file paths containing spaces, e.g., "Program Files". Since the standard installation of the AppForge environment does include this name, it was necessary to go to some lengths to reference required header files. Specifically, the included .mmp will search a directory "\tmp" to find headers. This can be set to any other directory that doesn’t contain spaces. The "fuser" header files (under "C:\Program Files\AppForge\Platforms\SymbianOS\ARMI\FuserSDK") should be copied to that directory for access by "gcc." 134 8.6 AppForge Fuser Functions Library AppForge Fuser Functions Library Overview The AppForge Fuser Functions Library provides the following classes: AppForge Fuser Functions Library Classes AFFuserFunction AFFuserModule AFFuserFunction Overview The AFFuserFunction class provides the following method: Method Execute AFFuserModule Overview The AFFuserModule class provides the following property and method: Property ModuleName Method GetFunction 135 9 AppForge MobileVB™ Support for Visual Basic 9.1 Overview MobileVB™ supports a large subset of the Visual Basic® programming language. For example, most of the common Visual Basic runtime functions are available and work the same as their PC counterparts. Where differences in language support do exist, they generally stem from limitations of mobile computing devices and represent conscious engineering decisions made in the design of MobileVB. For up-to-date articles about specifics of Visual Basic support, including techniques for optimizing your mobile software using MobileVB™ , visit the Developer Sector at http://www.appforge.com. MobileVB™ is Specifically Designed for Mobile Devices MobileVB™ is specifically designed to meet the special programming challenges of mobile devices. Speed, efficiency and reliability are critical when writing software for these devices. In particular, be aware of the following aspects of programming mobile devices: • Limited RAM. Reading and writing to RAM requires energy, reducing battery life. As a general rule, it is advisable to reduce RAM usage wherever possible. Programming styles that are less RAM-intensive translate well to mobile software development. • Slower execution. To minimize per-unit costs and maximize the life of small batteries, lowerspeed processors are often used. Because of this, certain CPU-intensive features may not be available. • In-the-field updates are difficult. Hence, mobile applications should be as reliable as possible. Preventable errors, such as those related to type-safety, should be identified at compile-time rather than after deployment to a mobile device. Visual Basic is a registered trademark of Microsoft Corporation in the United States and/or other countries. Palm OS is a registered trademark of Palm, Inc. 9.2 Data Type Support Numeric Types The following supported numeric types are the most efficient variable types and do not have any memory overhead beyond the bits required to store their value: 136 Type Byte Integer Long Single Double Currency Size (bytes) 1 2 4 4 8 8 Range Unsigned numbers in the range 0..255. Signed numbers in the range (-32768) ... 32767. Signed numbers in the range (-2,147,483,648) ... 2,147,483,647. Single-precision IEEE floating-point numbers. Double-precision IEEE floating-point numbers. Fixed-point numbers in the range -922,337,203,685,477.5808 ... 922,337,203,685,477.5807. Table 9: Numeric Types Supported Note that the Decimal numeric type is unsupported. String Types String types are optimized in MobileVB™ for both size and speed. Variable-length strings (String) are more common. They dynamically change size depending on the character data. Fixed-length strings (String * N) are subject to programming limitations, but can be beneficial when small or temporary strings are required. Although string length is typically limited by available device memory, no string within MobileVB™ may exceed 65,000 characters. 137 Type String Size (bytes) 4 + (1 or 2 bytes per character in the string) Notes • No fixed maximum length; limited by device memory • Allocated from the dynamic heap, for both global and local variables • Dynamically grows and shrinks to accommodate the character data • If any character requires unicode, the entire string is stored in unicode format String * N, where N is a literal number and the maximum number of characters allowed N*2 • No fixed maximum length; limited by device memory (for globals) or stack size (for locals) • Allocated in-place rather than from the heap, either globally or on the stack • Avoid using large fixed-length strings as local variables to conserve stack space • As a rule, fixed-strings are an efficient way to create small, temporary string buffers • Truncates characters it contains to ensure that no more than N characters are used • Does not get updated if passed ByRef to a subroutine • All characters are stored in unicode format, using 2 bytes for each character Table 10: String Types Array Types MobileVB™ allows the use of static and dynamic arrays of every supported type, including user-defined types. The following list details array support and restrictions in MobileVB: • Statically or dynamically dimensioned arrays are supported, and they can appear at the Form, Module, Sub, and Function scopes. 138 • User-defined types may contain statically or dynamically dimensioned arrays as members. • Arrays may contain elements of any MobileVB-supported data type, including user-defined types. • Bounds-checking is not provided for static arrays while running on an embedded device. (Of course, bounds-checking can be done as normal running within the Visual Basic® IDE.) • Arrays cannot be passed to a user-defined function, as doing so loses dimension information. An efficient workaround that achieves the same effect is to create a user-defined type whose only member is an array, then pass the user-defined type ByRef to a function. • Functions cannot return arrays. User-defined Types MobileVB™ provides full support for Visual Basic user-defined types. • Members of a user-defined type can be any supported MobileVB data type, including arrays and other user-defined types. • User-defined types may be passed ByRef to subroutines. Passing user-defined types ByVal is not supported. Enumerated Types MobileVB™ supports Enumerated types. Variant Type MobileVB™ does not support the Variant data type because it is a poor choice for use in embedded applications. However, MobileVB emulates the use of Variants in many common VB functions. Boolean Type MobileVB™ supports the Boolean type. Date Type MobileVB supports the Date type. 139 Note: Date separators are not available on all platforms, specifically Palm OS, and therefore MobileVB™ cannot take advantage of regional settings for Date separators. Thus, MobileVB allows ’.’ ’/’ and ’,’ as Date separators, regardless of regional settings. For example, IsDate returns TRUE within MobileVB because ’12.13.2000" is interpreted as a Date Value (ie., "12/13/2000"), while returning FALSE within the Visual Basic IDE because it is interpreted as a time value. Visual Basic is a registered trademark of Microsoft Corporation in the United States and/or other countries. Palm OS is a registered trademark of Palm, Inc. 9.3 User-defined Classes and Objects The MobileVB™ Compiler supports user-defined classes and provides full support for using Ingot types as variables and parameters. For example, Sub DisableSomeButton(someButton As AFButton) someButton.Enabled = False End Sub Note that all object references in MobileVB are early-bound and strongly-typed. One implication is that while the Object type is supported, properties and methods cannot be called directly using object variables. MobileVB™ supports the Control type. Only extender properties and methods can be called using the Control type (ie Top, Left, Height, Width, Move, and SetFocus). The WithEvents and New keywords are supported. 9.4 Scoping and Visibility Rules The MobileVB™ Compiler mirrors Visual Basic® scoping and visibility rules. The Public and Private visibility keywords are respected for subroutines, variables, user-defined types, and enumerations. MobileVB follows the default Visual Basic visibility rules for declarations that have no explicit visibility. The Static keyword is not supported. 9.5 Controls Collection MobileVB™ provides limited support for the Controls collection. MobileVB supports the Count and Item properties of the Controls collection. The Add method is not supported. Controls must be accessed through the Item property. For example: Me.Controls.Item(3) . The syntax Me.Controls(3) is not supported. 140 Only extender properties and methods can be called using the Controls collection (ie Top, Left, Height, Width, Move, and SetFocus). Note that these properties are not accessible for non-visual Ingots. The following example uses the Controls collection to display the positions of all controls on a form. It includes error-handling to handle non-visual Ingots. Sub ListControls() On Error Resume Next Dim Counter As Long For Counter = 0 To Me.Controls.Count - 1 MsgBox "Control " & Counter & " position: " _ & Me.Controls.Item(Counter).Left & ", " _ & Me.Controls.Item(Counter).Top Next Counter End Sub The Name property is not supported through the Controls collection. 9.6 Flow-of-control Structures Standard control structures are supported, including: • If..Then..[ElseIf..]Else..End If • Select..Case..[Case Else..]End Select • For..Next • Do Until..Loop, Do While..Loop, Do..Loop Until, Do..Loop While • While..Wend The following control structure is not currently supported: • For Each..Next End Statement MobileVB™ supports the use of the End statement. The End statement stops execution immediately. It may be placed anywhere in a procedure to end code execution. Calling the End statement closes all files opened in the program, and frees all memory used in the program. The End statement is used in the following subroutine to close a program. 141 Private Sub cmdClose_Click() Dim intCloseYesNo As Integer ’Prompt the user to make sure they want to close the program intCloseYesNo = MsgBox("Are you sure you want to close this program?" _ , vbYesNo) ’If the user selected Yes use End Statement to ’close the program If intCloseYesNo = vbYes Then End End If End Sub MobileVB™ Conditional Compilation Conditional compilation is used to execute parts of your code depending on specific conditions. MobileVB™ provides the conditional compilation constant: APPFORGE. It allows you to execute different code when running on a device or on a PC. For example if you are opening a Palm Database (.PDB), the path argument is different when running on a Palm OS® device than on a PC. The following code snippet shows how to use the APPFORGE conditional compilation constant to specify the proper path and open a Palm Database: Dim strPDBPath As String ’Use conditional compilation to determine if ’program is running on Palm on a PC #If APPFORGE Then ’Palm Path strPDBPath = "DatabaseName" #Else ’Path for PC strPDBPath = App.Path & "\DatabaseName" #End If ’open the database glngCatg = PDBOpen(Byfilename, strPDBPath, 0, 0, 0, 0, 0) If..Then Exception This exception only applies to code of the form: 142 If <test> Then <Instruction 1> : <Instruction 2> For example: If m > 59 Then m = m - 60: h = h + 1 When <test> is false, <Instruction 1> and <Instruction 2> should be skipped. However when running in Palm OS, <Instruction 2> is not skipped. 9.7 Debugging and Error Handling Using Err.Raise MobileVB™ supports the Err.Raise method, which can be used to display an error message box during run time. To use Err.Raise, specify an error number (required), along with optional source and description strings. All three values will be displayed to the user in a message box, along with the message "Please contact the author of this application". The application ends automatically when the user clicks "OK". Err.Raise Number as Long, Source as String, _ Description as String Entering empty strings ("") for the Source or Description field will cause that field to be omitted from the error message. Err.Raise 4, "Sub txtBox_Click()", "Invalid Name" The above code results in the following message box: Figure 2: Err.Raise Display. 143 Error Handling (On Error) MobileVB™ allows you to enable error handling blocks (On Error Goto LABEL) and disable error handling blocks (On Error Goto 0). Within an error handling block, the program can be put into a known good state and control can be returned to a specified point. MobileVB also supports "On Error Resume Next", which attempts to continue program execution despite an error, and "Resume LABEL", which jumps to a label during an error handling block. NOTE: MobileVB™ handles some error cases differently from Visual Basic. Under Visual Basic, if a second error is encountered while handling the first one (before a "Resume" command), the application will terminate. Conversely, MobileVB resets the error state the moment an error is caught using "On Error". Subsequent errors will transfer execution back to the last active error label. The following is an example of how to use error handling to implement a "best effort" algorithm (try three times before giving up): ’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’ ’ RiskyFunction is a function that fails intermittently. ’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’ Sub RiskyFunction() ’ Assume this function fails intermittently... End Sub ’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’ ’ Tries three times to successfully call ’ RiskyFunction. ’ Returns True on success, False on failure. ’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’ Function RobustFunction() As Boolean Const MAX_ATTEMPTS As Long = 3 Dim attempts As Long attempts = 0 On Error GoTo MyErrorCatchPoint ’ Register error handler TrySomethingRisky: Call RiskyFunction RobustFunction = True GoTo ExitPoint MyErrorCatchPoint: ’ This is the error handler If attempts < MAX_ATTEMPTS Then 144 attempts = attempts + 1 Resume TrySomethingRisky Else ’ Give up RobustFunction = False End If ExitPoint: ’ Exits the function using whatever was ’ last assigned to RobustFunction End Function 9.8 MsgBox The MobileVB™ MsgBox function does not support the Title parameter. Title is determined by the severity of the message box displayed, and is set to either "Error", "Warning", "Information", or "Confirm". If a severity level is not specified via the "buttons" parameter, the message box defaults to Information, unlike MSVB, which defaults to no icon. The MobileVB MsgBox does not support Helpfile or Context. The MobileVB MsgBox does not support the following constants: • vbApplicationModal • vbSystemModal • vbMsgBoxSetForeground • vbMsgBoxHelpButton • vbMsgBoxRight • vbMsgBoxRtlReading • vbDefaultButton1, vbDefaultButton2, vbDefaultButton3, vbDefaultButton4 9.9 InputBox MobileVB supports the InputBox function. For details see theInputBox section of the Supported Visual Basic Functions. 145 9.10 ReDim Statement MobileVB™ supports the ReDim statement. This statement sizes or resizes a dynamic array. The dynamic array must have already been formally declared with empty parentheses. The syntax for the ReDim statement is as follows: ReDim [Preserve] variablename(subscripts) As VariableType The optional Preserve statement allows you to preserve the data already stored in the array, but with a couple of restrictions: Only the upper bound of the last array dimension can be changed, and the array type cannot be changed. The following snippet of code provides an example of how a valid use of the ReDim statement. For additional details, see the Visual Basic documentation. ’Declare the array Dim strArray() As String ’Size the array as a two dimensional array ReDim strArray(1 To 1, 1 To 2) ’Assign values to the variable strArray(1, 1) = "String 1" strArray(1, 2) = "String 2" ’Increase the upper bound for the last array dimension ReDim Preserve strArray(1 To 1, 1 To 4) ’Assign additional values to the variable strArray(1, 3) = "String 3" strArray(1, 4) = "String 4" 9.11 VarPtr Function This function is available in MobileVB™ . It is used to get the address of a variable. It takes the variable name as an argument and returns the address of that variable as a long. It is used extensivley in theAppForge PDB Library . Additionally, it is used in theAppForge Palm OS Extended Functions Library , AppForge Palm OS Extensibility Library , AppForge Database Library , AFClientSocket Ingot , andAFSerial Ingot. The syntax for the VarPtr Function is as follows: VarPtr(variable) as Long 146 Special Note:The VarPtr function is not documented in the Visual Basic® documentation and is not Supported by MicroSoft Technical Support. 9.12 Customizing Toolbars Do not attempt to customize the toolbar in Visual Basic® . Dragging an AppForge Ingot to another toolbar causes the following behavior under Windows® 2000 and 98: 1. Clicking on the moved Ingot in the toolbar does nothing. 2. An error is generated from "modMenuManagement" when closing VB. 9.13 Event Handling MobileVB™ supports the immediate handling of multiple events. When an event is triggered, its code always executes without delay; an event no longer has to wait for the currently executing routine to finish. 9.14 Reserved Words The following identifiers are keywords used by MobileVB™ in Visual Basic® . You should avoid using them as names of Ingots, variables, subroutines, etc. #Const #Else Alias Attribute Boolean Byte Class Date Dim Each Empty End Function End Select End With Eqv False Global Implements In #If #End If And BeginProperty ByVal Call Const Decimal Double ElseIf EndProperty End If End Sub End On Error For GoTo Imp Is 147 #ElseIf AddressOf As Begin ByRef Case Currency Declare Do Else End Enum End Property End Type Enum Exit Function If Integer Let Lib Long Next Not On Option Compare Or Property Get Public Resume Single Sub True Variant While Xor Like Loop New Null Optional Option Explicit Preserve Let Property Set RaiseEvent Set Step Then Type Version WithEvents Long Mod Nothing Object Option Base Option Private Private Property Property ReDim Select String To Until Wend With Table 11: Reserved Words 148 9.15 MobileVB Form MobileVB Form Overview The MobileVB™ Form provides the same basic functionality as a standard Visual Basic® Form. Load and Unload Statements In addtion to the properties, events, and methods listed below, the MobileVB form supports Load and Unload statements. The Load statement loads the specified form into memory, and the Unload statement unloads it. In code, the syntax for these statements is as follows: Load MobileVBForm or: Unload MobileVBForm Note that under MobileVB™ , forms are automatically loaded when they are shown, using either the Show method or by setting the form’s Visible property to True. The reverse is not true: hiding a form does not unload it. Overlapping Forms Overlapping forms are supported on the Pocket PC platform, but not in Palm OS® . To ensure crosscompatibility between platforms, do not have more than one form visible at a time. Use the Hide method on a visible form before calling Show on another. Typical Usage 1. Use the Show method to display a form. Before showing a new form, the old form should be hidden first. (Otherwise, an "overlapping" form error may occur in Palm OS.) 2. Use the Hide method when the form no longer needs to be displayed. If no forms are shown, the screen will be blank. Hiding an application that has only one form and no modules will also exit the application. 3. To run code when a form is loading, place the code within the Form_Load Event. This is a good place to put code for opening a database to be used in the form’s code. 4. To run code any time a form becomes active, place the code within the Form_Activate Event. This is a good place to include code to prepare Ingots on the form with a default value. 5. To run code any time a form is no longer active, place the code within the Form_Deactivate Event. This is a good place to include code which saves the value associated with an Ingot. 149 6. To run code any time a form is unloaded, place the code within the Form_Unload Event. This is a good place to put code for closing a database that was used on this form. The MobileVB Form provides the following properties, methods, and events: Properties BackColor Controls Height ScaleHeight ScaleWidth Top WindowState BorderStyle Enabled KeyPreview ScaleLeft StartUpPosition Visible Caption ForeColor Left ScaleTop Tag Width Methods Hide Show Move Refresh Events Activate Initialize KeyUp Resize 9.16 Click KeyDown Load Terminate Deactivate KeyPress QueryUnload Unload MobileVB Screen MobileVB Screen Overview The MobileVB™ Screen allows the manipulation of MobileVB Forms and AppForge Ingots. Additionally, general screen size information is made available via the MobileVB Screen. The MobileVB™ screen provides the same basic functionality as the standard Visual Basic® Screen object, but does not support the MouseIcon and MousePointer Properties. The MobileVB Screen provides the following properties: 150 Properties ActiveControl Fonts TwipsPerPixelY ActiveForm Height Width FontCount TwipsPerPixelX 9.17 Supported Visual Basic Functions Overview The table below lists all Visual Basic® functions and subroutines supported by MobileVB: AscW CBool CDate ChrW Cos Date DateSerial DDB Err FormatCurrency FormatPercent Hex InStr IPmt IsNumeric Left Log Minute MonthName NPer PMT QBColor Replace Rnd SaveSetting Sgn SLN Str StrReverse Time TimeValue Atn CByte CDbl CInt CSng DateAdd DateValue DeleteSetting Exp FormatDateTime FV Hour InStrRev IRR LBound Len LTrim MIRR MsgBox NPV PPMT Randomize RGB Round Second Shell Space StrComp SYD Timer Trim 151 Beep CCur Chr CLng CStr DateDiff Day DoEvents Fix FormatNumber GetSetting InputBox Int IsDate LCase Load Mid Month Now Oct PV Rate Right RTrim SendKeys Sin Sqr String Tan TimeSerial UBound UCase WeekdayName 9.18 Unload Year Weekday Unsupported Visual Basic Functions Overview This section lists functions, subroutines, and enums that are supported in Visual Basic® , but are not supported in AppForge. Add method CallByName function Choose function CurDir function CVDate function EOF function FileAttr function FileLen function Format$ function GetAttr function HelpFile property IsArray function IsMissing function Join function Loc function MkDir method Reset method Seek function StrConv function Val function VbCalendar enum VbIMEStatus enum AppActivate method ChDir method Count function CurDir$ function CVErr function Error function FileCopy method Filter function FreeFile function GetObject function IMEStatus function IsEmpty function IsNull function Kill method LOF function Partition function RightB$ function SetAttr method Switch function VarType function VbCallType enum VbStrConv enum Calendar property ChDrive method CreateObject function CVar function Dir function Error$ function FileDateTime function Format function GetAllStrings function HelpContext property InStrB function IsError function Item function LastDllError property MidB$ function Remove method RmDir method Split function TypeName function VbAppWinStyle enum VbFileAttribute enum VbVarType enum Table 13: Functions and Subroutines not Supported in Visual Basic Visual Basic is a registered trademark of Microsoft Corporation in the United States and / or other countries. 152 10 10.1 AppForge MobileVB™ Tutorial Overview AppForge MobileVB™ is an extension of Microsoft® Visual Basic® that makes writing applications for mobile devices easier than ever. Visual Basic is a powerful programming language that’s easy to learn. You create the user interface by "drawing" controls, such as text boxes and command buttons, on a form. Next, you set properties for the controls to specify values such as caption, color, and size. Finally, you write code to bring the application to life. MobileVB works the same way, and includes many of the same functions and methods as Visual Basic. This tutorial will take you through the steps of designing and writing code for a sample application using MobileVB™ . You’ll learn basic Ingot™ manipulation at design time and run time, programming for events, and database usage techniques. If you’ve never used Visual Basic® before, we recommend reading the documentation for beginning programmers in the Microsoft® MSDN Library® at http://msdn.microsoft.com/library before attempting this tutorial. Be sure to check out the section "MobileVB™ Support for Visual Basic" for details on functions, structures and methods supported by MobileVB. TVToday Tutorial Application The TVToday tutorial application provides TV program information for multiple channels in four categories for an entire day. The user can view all the programs that correspond to a given category within any one-hour range. TVToday also supplies detailed information about any TV program and a preview of the program, if available. The TVToday application uses a range of AppForge Ingots™ . Some Ingots are similar to Visual Basic controls, while others are unique to MobileVB. Requirements The TVToday Tutorial requires MobileVB™ , which can be installed on any PC running Windows 95, Windows 98, Windows NT 4.0, Windows 2000, or Windows XP. If you are running Windows 95, you must install Windows 95 Service Pack 1. If you are running Windows NT 4.0, you must install Windows NT 4.0 Service Pack 4 or higher. The Palm™ HotSync Manager® is required for uploading MobileVB applications to a Palm OS® device, and Microsoft® ActiveSync® is required to deploy an application to a Pocket PC device. However, you 153 can still debug and run MobileVB™ applications within the Visual Basic environment without a handheld device. NOTE: Palm OS® version 3.1 or later is required to run MobileVB apps on a Palm OS handheld device. File Locations Once MobileVB™ has been fully installed, all of the essential files reside in the AppForge directory. The following table lists all of the files required by this tutorial. Folder Location ...AppForge\VB Toolkit\doc\VBTutorial\Database ...AppForge\VB Toolkit\doc\VBTutorial\Graphics ...AppForge\Fonts Table 14: File Locations 154 Files Category.PDB Program.PDB TVT_ARBD.RGX TVT_ARBH.RGX TVT_ARBK.RGX TVT_ARFD.RGX TVT_ARFH.RGX TVT_ARFW.RGX TVT_ARRT.RGX TVT_CGBH.RGX TVT_CGBK.RGX TVT_LOGO.RGX TVT_PGBH.RGX TVT_PGBK.RGX TVT_TVBH.RGX TVT_TVBK.RGX Mov_00.RGX Mov_01.RGX Mov_02.RGX Mov_03.RGX Mov_04.RGX Mov_05.RGX Mov_06.RGX Mov_07.RGX Mov_08.RGX Mov_09.RGX Mov_10.RGX Mov_11.RGX Palm_05.CMF Palm_05B.CMF Palm_07.CMF As an aid in completing this tutorial, different versions of TVToday are provided with the install. Each version represents a development stage of the tutorial. They are broken down by lesson in the ...AppForge\VB Toolkit\doc\VBTutorial folder of your MobileVB™ install. Each folder contains the TVToday application, as it should appear following the completion of a lesson. Lesson Overview This tutorial is broken down into 11 lessons. Each lesson provides step-by-step instructions that introduce important techniques and MobileVB™ features. Lesson Lesson 1 Description Creating a MobileVB™ Project Lesson 2 Adding Database Connectivity Lesson 3 Creating the Category Form Lesson 4 Adding Connectivity to the Program Database Lesson 5 Displaying Programs By The Hour Lesson 6 Providing Control Over Program Timeframe Lesson 7 What is Covered Creating a MobileVB Project Adding AppForge Ingots™ Saving and Running the Project Adding the Category Database Keeping Track of Database Fields Creating and Calling a Subroutine Saving and Running the Project Adding a New Form Copying Ingots from One Form to Another Adding New Ingots Creating Navigation Between Forms Saving and Running the Project Adding Ingots To Access and Present Program Data Keeping Track Of Database Fields Loading Database Information Creating and Calling a Subroutine Saving and Running The Project Adding Time-Based Code Determining The Top Of The Hour Creating and Calling a Subroutine Saving and Running The Project Adding Ingots To Control The Timeframe Displaying and Retaining The Current Timeframe Allowing Users To Control The Timeframe Saving and Running The Project Adding A New Form To Copy Ingots From One Form To Another Adding New Ingots To The Program Form Creating A Program Form 155 Lesson 8 Displaying Program Information Lesson 9 Creating A Preview Form Lesson 10 Displaying Program Previews Lesson 11 Uploading The MobileVB™ Project Creating Navigation Between Forms Creating Navigation From Program Form To Main Form Saving and Running The Project Adding Display Ingots To The Program Form Formatting a Time Range Creating and Calling a Subroutine Loading Database Information Saving and Running The Project Creating the Preview Form Copying Ingots to the Preview Form Adding New Ingots To The Preview Form Enabling and Disabling an AFButton Creating Navigation Between Forms Saving and Running The Project Adding the AFFilmstrip Ingot Setting the Frames Property Playing and Stopping the Preview Saving and Running The Project Setting the Dependencies Uploading the Project Viewing Messages In The Compiler Table 15: Lesson Overview Visual Basic and ActiveSync are registered trademarks of Microsoft Corporation in the United States and/or other countries. Palm OS and HotSync are registered trademarks, and Palm is a trademark of Palm, Inc. 10.2 Lesson 1: Creating a MobileVB™ Project Begin creating the TVToday application by choosing New Project from the File menu, then selecting MobileVB™ Project in the New Project dialog box. Choose "Palm OS" in the Design Target Selection window. 156 Figure 3: New Project Dialog Figure 4: Design Target Selection 157 This will automatically create a blank MobileVB form. Figure 5: Blank MobileVB(tm) Form You can change the names of projects and forms by clicking on them in the Project window, selecting Properties Window from the View menu, and changing the Name value. Change the Name of the Project from MobileVBProject1 to TVToday, change the name of Form1 to frmTVTMain, and clear the Caption property. Next Select the MobileVB Settings... option from the MobileVB Menu. 158 Figure 6: MobileVB(tm) Menu with MobileVB Settings Selected This brings up the MobileVB Settings window. 159 Figure 7: MobileVB(tm) Settings Window Click on the Palm OS Settings tab. Make sure that the HotSync Name is set to the correct user. Change the CreatorID to AFTV (all capital letters). AFTV has already been registered with Palm, so click OK to continue. 160 Figure 8: Palm OS Settings Now save the project by taking the following steps. 1. Select Save Project from the File menu. 2. Save the following files with the corresponding file names (If the project and form names were set correctly, the file names should automatically default to the correct save names): File Form Project File Name frmTVTMain.frm TVToday.vbp Table 16: Lesson 1 - Save Setttings Adding Ingots to the Form To create the look of the user interface for the TVToday Application, AppForge Ingots™ are added to the form. This first lesson of the tutorial uses the following Ingots: 161 Button Name Description AFShape Rectangles or circles on your form. AFButton Text button that can receive user events to begin, interrupt, or end a process. AFGraphic Displays a graphic in the application. Valid graphic formats are .bmp, .rgx, .jpg, or .png*. AFListBox Presents the user with a selectable list of text items. AFLabel Functions as a text field that is not directly editable by the user. Table 17: Lesson 1 - Ingot Table *AppForge MobileVB 3.1 or later is required to utilize a .png file. See theBooster and PNG Files Section of the AppForge Booster And Additional Files documentation for details. First, add two AFShape Ingots to frmTVTMain. The AppForge Shape Ingot is similar to Visual Basic’s own Shape control. To create the first shape, select the AFShape Ingot in the Visual Basic toolbox and draw it anywhere on frmTVTMain by clicking and dragging. In the Properties windows, set properties for the shape according to the following table. Keep all other properties at their defaults. Ingot AFShape Property Setting Name BorderStyle FillColor FillStyle Height Left Top Width shpRect1 0 - Transparent &H00AAAAAA& 0 - Solid 85 0 75 38 Table 18: Lesson 1 - shpRect1 Properties Next, draw a second AFShape on the form. In the Properties windows, set properties for the second shape according to the following table. Keep all other properties at their defaults. 162 Ingot AFShape Property Setting Name BorderStyle FillColor FillStyle Height Left Top Width shpRect2 0 - Transparent &H00AAAAAA& 0 - Solid 20 38 140 35 Table 19: Lesson 1 - shpRect2 Properties If all of the settings are entered properly, frmTVTMain should look like the following figure. Figure 9: frmTVTMain with AFShape Adding the TVToday Logo The TVToday main form also features the TVT logo. To display this on frmTVTMain, add an AFGraphic Ingot to it. Begin by selecting the AFGraphic Ingot in the Visual Basic toolbox and drawing it on frmTVTMain. In the Properties windows, set properties for the new AFGraphic according to the following table. Keep all other properties at their defaults. Please Note: The source file for an AFGraphic must reside within the same folder or a subfolder of the directory containing the project. When setting the Picture property of an AFGraphic or AFGraphicButton, a button labeled "..." appears. Click on this button to browse to the desired graphic. All graphics for the TVToday Application are stored in the ...AppForge\VB Toolkit\doc\VBTutorial\Graphics folder of your install of MobileVB™ . Once the appropriate graphic has been selected, MobileVB allows you to copy the selected graphic into the folder containing the TVToday project. 163 As an alternative to using the browser window provided by MobileVB™ , the graphic files for the project may be manually copied from the ...AppForge\VB Toolkit\doc\VBTutorial\Graphics folder to the folder in which you have saved the TVToday project. The Picture property may then be typed in manually. If the graphics are copied into a sub-folder within the TVToday project’s folder, a relative path must be used for the Picture property. For example, if the graphic TVT_LOGO.RGX is copied into a folder named Graphics in the TVToday project’s folder, the Picture property should be set to Graphics\TVT_LOGO.RGX. Ingot AFGraphic Property Setting Name Height Left Picture Top Width gphLogo 75 0 TVT_LOGO.RGX 0 75 Table 20: Lesson 1 - gphLogo Properties The form should now look like the following figure. Figure 10: frmTVTMain with TVTLogo Adding the AFButton, AFGraphic, and AFLabel Ingots To complete the visual user interface of frmTVTMain, we need to add AFButton, AFGraphic, AFListBox, and AFLabel Ingots. Each Ingot is similar to a corresponding Visual Basic control. Use the toolbox to draw an AFButton, AFGraphic, AFListBox, and AFLabel on frmTVTMain. In the Properties windows, set properties for the each Ingot according to the following tables. Keep all other properties at their defaults. 164 Ingot Property Setting AFButton Name Appearance BackColor Caption FontName FontSize FontStyle Height Left Top Width btnShowMe 1 - 3D 1 &H00AAAAAA& show me AFPalm 12 1 (Bold) 20 74 140 71 AFGraphic Name Height Left Picture Top Width gphArrowRight 20 146 TVT_ARRT.RGX 140 14 AFListBox Name FontName FontSize FontStyle Height Left Top Width lstCatg AFPalm 12 0 111 75 28 84 AFLabel Name BackColor Caption FontName FontSize FontStyle Height Left Top Width lblCatg &H00FFFFFF& Category: AFPalm 12 1 (bold) 18 75 8 73 Table 21: Lesson 1 - btnShowMe, gphArrowRight Properties 165 If all of the settings are entered properly, frmTVTMain should look like the following figure. Figure 11: frmTVTMain with AFButton, AFGraphic, AFListBox, and AFLabel Ingots Adding and Programming Sub Main For all MobileVB™ applications, a Sub procedure in Main is required. Sub Main is the first procedure that is run when the application is started. We need to create a code module to contain Sub Main. Begin by selecting Add Module from the Project Menu. Figure 12: Add Module This should bring up the Add Module Dialog box. Click on the Open button to add a new module to your project. Set the name property of the newly created module to mdlTVTMain. 166 Figure 13: Add Module Dialog Box The Sub Main procedure should reside within mdlTVTMain. mdlTVTMain: Paste the following code into Sub Main() ’show form frmTVTMain.Show End Sub This code shows frmTVTMain. In order to make TVToday start at Sub Main, it must be set as the startup object. This is done by selecting TVToday Properties... from the Project Menu. This brings up the TVToday Project Properties window. Set the Startup Object property in the upper right hand corner to Sub Main. Now TVToday will execute the code in Sub Main before any other code in the program. Click OK to return to the project. 167 Figure 14: Selecting TVToday Properties... from the Project Menu Figure 15: Setting the Startup Object for TVToday 168 Saving the Project Before running the application for the first time, save the project. To save the project 1. Select Save Project from the File menu. 2. Save the following files with the corresponding default file names: File Standard Module Form Project File Name mdlTVTMain.bas frmTVTMain.frm TVToday.VBP Table 22: Lesson 1 - Save Setttings Running the Project To run the application, choose Start from the Run menu, or click the Start button on the toolbar. The TVToday Main form should appear. To exit, choose Stop from the Run menu, or click the Stop button on the toolbar. 10.3 Lesson 2: Adding Database Connectivity and Creating an Error Form When the users enter the main form of the TVToday application, we want them to see a list of the available categories for today’s TV programs. This list of available categories will come from a Palm Database (.PDB) and be displayed in an Appforge ListBox on frmTVTMain. Figure 16: Main screen of the TVToday Application 169 To create the user interface for the Error form, we need to add AppForge Ingots to it. This lesson uses the following Ingots: Button Ingot Description AFShape Rectangles or circles on your form. AFButton Text button that can receive user events to begin, interrupt, or end a process. AFGraphic Displays a graphic in the application. Valid graphic formats are .bmp, .rgx, .jpg, or .png*. AFLabel Functions as a text field that is not directly editable by the user. AFTextBox Displays text on the form, or provides a text input box for the user. Table 23: Lesson 2 - Ingot List *AppForge MobileVB 3.1 or later is required to utilize a .png file. See theBooster and PNG Files Section of the AppForge Booster And Additional Files documentation for details. Copying the Category Database to the Project Folder The category database for TVToday is installed as part of the typical installation of MobileVB™ . In order to simplify access to the category database, copy it into the same folder as the TVToday application. The filename for the category database is Category.PDB, and it is installed in the ...\AppForge\VB Toolkit\doc\VBTutorial\Database folder of your MobileVB install directory. Keeping Track of Database Fields To retrieve information from the database, the application code needs to target specific database records and specific fields. Each field is identified by an integer value. The TVToday application uses constants to keep track of each database field. Add the following code into the Declarations section of mdlTVTMain: ’category database fields Global Const LNG_CATG_CATGID As Long = 0 Global Const LNG_CATG_CATGNAME As Long = 1 170 Declaring the Category Database MobileVB™ uses a Long type value to represent a Palm database. Since the category database is used throughout the TVToday program, we want to declare a public variable to represent it throughout our project. To do this, add the following code into the Declarations section of mdlTVTMain: ’category database Public glngCatg As Long Opening the Database Next, the category database must be opened. The added code also checks to see whether the database was successfully opened. If the PDBOpen call was successful, frmTVTMain is shown. Code to load the categories as well as handle an unsuccessful PDBOpen call will be added in this lesson. Edit the Sub Main procedure of mdlTVTMain so it matches the following code: Sub Main() Dim strCatgPath As String ’Use conditional compilation to determine if ’program is running on Palm or Windows #If APPFORGE Then ’Palm Path strCatgPath = "Category" #Else ’Windows Path strCatgPath = App.Path & "\Category" #End If ’open the database glngCatg = PDBOpen(Byfilename, strCatgPath, _ 0, 0, 0, 0, 0) ’Check to see if database was successfully opened If glngCatg = 0 Then ’Database was not successfully opened ’Run the Load Error subroutine and ’show frmTVTError frmTVTError.LoadError frmTVTError.Show Else ’show form frmTVTMain.Show 171 End If End Sub There are two important points to note about the path argument of the PDBOpen method: 1. The path argument for the PDBOpen method is different when running on a device and running in Windows® . Conditional compilation is used to ensure the proper path is assigned for each. 2. The database name is case-sensitive. Make sure that the name is typed in the correct case. Loading the Categories To load each category in the main form’s AFListBox, a new Sub procedure called LoadCategories should be added to frmTVTMain. LoadCategories clears the AFListBox and loads each category from the database, record by record. Paste the following code into the frmTVTMain code window: Public Sub LoadCategories() ’load the categories listed in database into the ’listbox, tagging each listbox item with it’s ’corresponding UniqueID in the database Dim strCatgName As String ’clear the listbox lstCatg.Clear ’sort the database by category name PDBSetSortFields glngCatg, LNG_CATG_CATGNAME ’start with the first record PDBMoveFirst glngCatg ’while not on the last record of the database While Not (PDBEOF(glngCatg) = True) ’get the record’s category name PDBGetField glngCatg, LNG_CATG_CATGNAME, _ strCatgName ’add the value as the next item in the listbox 172 lstCatg.AddItem strCatgName, -1 ’select the item just added to the listbox lstCatg.ListIndex = (lstCatg.ListCount - 1) ’set the list itemdata property as the unique ID ’of the record lstCatg.ItemData(lstCatg.ListIndex) = _ PDBRecordUniqueID(glngCatg) ’go on to the next record in the database PDBMoveNext glngCatg Wend ’select the first item in the listbox lstCatg.ListIndex = 0 End Sub Note that as each record’s category name is added as an AFListBox item, the code also tags the item with the record’s unique ID. The unique ID is a long value that uniquely identifies a specific database record. We will use it later to find all the TV programs corresponding to a category. Calling LoadCategories Now the LoadCategories subroutine must be called so that the ListBox is filled before frmTVTMain is shown. Edit the end of Sub Main in the mdlTVTMain module so it matches the following (the bolded code indicates the newly added lines): Else ’load the categories from the database into ’the Main form’s listbox frmTVTMain.LoadCategories ’show form frmTVTMain.Show End If End Sub 173 Adding and Enabling the Error Form Earlier in this lesson, code was inserted into Sub Main to verify the successful opening of the Categories database. In this section we will add a new form and code used to notify the user that the database failed to open. Adding a New Form to the MobileVB™ Project 1. Select Add Form from the Project menu. This will bring up the Add Form dialog box. 2. Select Form from the Add Form dialog box. 3. Click the Open button. Figure 17: Add Form Dialog Box In the Properties window, set the new form’s Name property to frmTVTError and clear the Caption property. Some of the Ingots we need for frmTVTError are nearly identical to those used on frmTVTMain. To save time, copy the matching Ingots from frmTVTMain to frmTVTError. The six matching Ingots are named gphLogo, shpRect1, shpRect2, btnShowMe, gphArrowRight, and lblCatg. Follow the following steps to copy these Ingots: To copy Ingots from one form to another: 174 1. Open the main form, frmTVTMain. You can double-click on the form’s name in the Project Explorer window to show it. 2. Click on the Edit menu and choose Select All to select all Ingots. 3. Copy the components by selecting Copy from the Edit menu, or by clicking the Copy button on the toolbar. 4. Open the Ingots’ destination form, frmTVTError. 5. Paste the components by selecting Paste from the Edit menu, or by clicking the Paste button on the toolbar. Once the Ingots are copied to the Error form, two of the Ingot name properties should be changed. On frmTVTError change the names as follows: Ingot Previous Name New Name btnShowMe btnExit lblCatg lblError Table 24: Lesson 2 - Copied Ingot Name Changes Now make the following properties changes: Ingot Name Property Setting btnExit Caption exit lblError Caption Error: Table 25: Lesson 2: Copied Ingot Changes Adding the Error Message TextBox The final Ingot placed on frmTVTError is an AFTextBox to display the error message. First, click on frmTVTError and delete the lstCatg list box. Then, use the toolbox to draw an AFTextBox on frmTVTError. In the Properties window, set properties for the Ingot according to the following tables. Leave all other settings at their defaults. 175 Ingot Name Property Setting AFTextBox Name Alignment BackColor BorderStyle FontName FontSize FontStyle Height Left Multiline Text Top UnderlineStyle Width txtErrorMsg 0 - Left Justify &H00FFFFFF& 1 - Single AFPalm 12 0 113 72 True Error Message 24 0 - None 88 Table 26: Lesson 2 - AFTextBox Property Settings frmTVTError should now look like the following figure. Figure 18: Error Screen of the TVToday Application Adding Code to the Form The final step in enabling the Error form is adding the code associated with it. First the LoadError Subroutine should be added. Click on frmTVTError, select Code from the View menu, and paste the following code in the window: Public Sub LoadError() Dim strDbName As String ’Identify the missing database 176 If glngCatg = 0 Then strDbName = "Category.PDB" End If ’Set the text for the Error Message text box txtErrorMsg.Text = strDbName & _ " not found. Please HotSync " & strDbName _ & " and run TVToday again." End Sub The above code identifies the missing database and displays the error message. LoadError is called before frmTVTError is shown. Remember that If the user gets to this error form, it probably means the category database has not been loaded on the Palm OS® device. Therefore, the only option left to the user is to exit the program and load the database onto the device. To enable the user to exit the program from frmTVTError, double click on btnExit, and add the following code: Private Sub btnExit_Click() ’Ends the program End End Sub This completes the implementation of the Error Form. Saving the Project Save the changes made to the project by selecting Save Project from the File menu. Save the following file with the corresponding file name: File Form File Name frmTVTError.frm Table 27: Lesson 3 - Save Names Running the Project Next, run the application by choosing Start from the Run menu, or by clicking the Start button on the toolbar. The main form will appear with a list of categories within the AFListBox. To test the Error form functionality, temporarily remove Category.PDB from its current location and run TVToday again. The frmTVTError form should appear instead of frmTVTMain. (Don’t forget to return Category.PDB after testing the Error form’s functionality.) 177 10.4 Lesson 3: Creating a Category Form In this lesson, a new form is added to display TV programs within a chosen category. Once users have selected a category on the Main form, they can click the Show Me button to view the corresponding program on a second form. The Category Form looks like the following figure. Figure 19: Category Screen of the TVToday Application Lesson 3 of the tutorial uses the following Ingots: Button Ingot Description AFShape Creates rectangles or circles on your forms. AFButton Text button that can receive user events to begin, interrupt, or end a process. AFGraphic Displays a graphic in the application. Valid graphic formats are .bmp, .rgx, .jpg, or .png*. AFLabel Functions as a text field that is not directly editable by the user. AFGraphicButton Works like the standard button, but instead of a caption, it can specify different graphics for the up and down click positions. Table 28: Lesson 3 - Ingot List *AppForge MobileVB 3.1 or later is required to utilize a .png file. See theBooster and PNG Files Section of the AppForge Booster And Additional Files documentation for details. 178 Adding a New Form Before laying out the user interface for the Category form, a new form needs to be added to the project. 1. Select Add Form from the Project menu. This will bring up the Add Form dialog box. 2. Select Form from the Add Form dialog box. 3. Click the Open button. In the Properties window, set the form’s name property to frmTVTCatg and clear the Caption property. Figure 20: Add Form Dialog Box Copying Ingots to the Category Form Three of the Ingots we will use on the Category form are identical to Ingots on the Main form. To save time, copy the matching Ingots from the Main form to the Category form. The three matching Ingots are shpRect2, btnShowMe, and gphArrowRight. To copy Ingots from one form to another: 1. Open the main form, frmTVTMain. You can double-click on the form’s name in the Project Explorer window to show it. 179 2. Select the first component to copy by clicking on it in the form. 3. Select each additional component to copy by holding down the Shift key and clicking on each component you want. 4. Copy the components by selecting Copy from the Edit menu, or by clicking the Copy button on the toolbar. 5. Open the Ingots’ destination form, frmTVTError. 6. Paste the components by selecting Paste from the Edit menu, or by clicking the Paste button on the toolbar. When the AFShape, AFButton, and AFGraphic Ingots are pasted onto the Category form, they will be placed at the top of the form. Update each Ingot’s properties to the following values: Ingot Name Property Setting shpRect2 Left Top Width 0 140 73 btnShowMe Left Top 74 140 gphArrowRight Left Top 146 140 Table 29: Lesson 3: Top Property Values Adding Ingots to the Category Form Use the toolbox to draw an AFLabel, an AFGraphicButton, and two AFShape Ingots on frmTVTCatg. In the Properties window, set properties for each Ingot according to the following table. Use the default setting for all other properties. Ingot AFGraphicButton Property Setting Name DownPicture FocusPicture Height Left NoFocusPicture grbTVBack TVT_TVBH.RGX TVT_TVBK.RGX 27 0 TVT_TVBK.RGX 180 Top Width 0 40 AFShape (1) Name BorderStyle FillColor FillStyle Height Left Top Width shpRect3 0 - Transparent &H00AAAAAA& 0 - Solid 6 40 5 120 AFShape (2) Name BorderStyle FillColor FillStyle Height Left Top Width shpRect4 0 - Transparent &H00AAAAAA& 0 - Solid 6 40 21 120 AFLabel Name BackColor Caption FontName FontSize FontStyle Height Left Top Width lblTVToday &H00AAAAAA& TVToday AFPalm 12 1 (Bold) 12 40 11 120 Table 30: Lesson 3 - New Ingot Properties The form should now look like the following figure. 181 Figure 21: frmTVTCatg with AFLabel, AFShapes, and AFGraphicButton Creating Navigation between Forms When users click the Show Me button on the Main form, the Category form should replace the Main form. Double-click the Show Me button on the Main form to view the button’s Click event in the Code window. Paste the following code into frmTVTMain’s form module: Private Sub btnShowMe_Click() ’hide this form and show the category form frmTVTMain.Hide frmTVTCatg.Show End Sub To complete the navigation between forms, we need to add code to frmTVTCatg. When users click on the AFGraphicButton at the top of the Category form, the Main form should replace the Category form. Double-click the AFGraphicButton on the Category form to view grbTVBack’s Click event in the Code window. Paste the following code into frmTVTCatg’s form module: Private Sub grbTVBack_Click() ’hide this form and show the main form frmTVTCatg.Hide frmTVTMain.Show End Sub Saving the Project Save the changes made to the project by selecting Save Project from the File menu. Save the following file with the corresponding file name: 182 File Form File Name frmTVTCatg.frm Table 31: Lesson 3 - Save Names Running the Project Run the application by choosing Start from the Run menu, or by clicking the Start button on the toolbar. The main form will appear with a list of categories within the AFListBox. Click on the Show Me button to navigate to the Category form. Once on the Category form, click on the AFGraphicButton at the top left to return to the Main form. 10.5 Lesson 4: Adding Connectivity to the Program Database When users choose a category and navigate to the Category form, they should see a list of television programs corresponding to the chosen category. Figure 22: Category Screen of the TVToday Application The data for these television programs will come from the Program database, Program.PDB. Copying the Program Database to the Project Folder The program database is installed as part of the typical install of MobileVB™ . In order to simplify access to the program database, copy it into the same folder as the TVToday application. The filename for the program database is Program.PDB, and it is installed in the ...\VB Toolkit\doc\VBTutorial\Database folder of your MobileVB install directory. 183 Adding Ingots to the Category Form To present the program information, the following Ingots will be added during Lesson 4: Button Ingot Description AFShape Used to create rectangles or circles on your forms. AFGrid Used to display text or graphics in a grid. It also allows the user to select rows or cells in the grid. The grid can contain a title, fixed rows and columns, and has flexible options for colors, alignment, and borders. AFLabel Functions as a text field that is not directly editable by the user. Table 32: Lesson 4 - Ingots Added Use the toolbox to draw an AFShape, AFGrid, and AFLabel on frmTVTCatg. In the Properties window, set properties for the each Ingot according to the following table. Use the default setting for all other properties. Ingot Property Setting AFShape Name BackColor BorderStyle FillColor Height Left Top Width shpLine1 &H00AAAAAA& 0 - Transparent &H00AAAAAA& 2 0 45 160 AFGrid Name FontName FontSize FontStyle GridLines Height Left SelectionType Top Width grdProg AFPalm (12 Regular) 12 0 1 - Horizontal 70 0 2 - Row 70 160 184 AFLabel Name BackColor Caption FontName FontSize FontStyle Height Left Top Width lblCatgName &H00FFFFFF& category name AFPalm (12 Regular) 12 0 12 40 31 120 Table 33: Lesson 4 - Ingot Properties The Category Form should now look like this: Figure 23: frmTVTCatg with Shape, Grid, and Label Declaring the Program Database MobileVB™ uses a Long type value to represent a Palm database. Since the program database is accessed throughout the TVToday program, we need to declare a public variable to represent it. To do this, add the following code to the Declarations section of mdlTVTMain: Public glngProg As Long Keeping Track of Program Database Fields To retrieve information from the Program database, the application code targets specific database records and specific fields within the records. Each field is identified by an integer value. 185 The TVToday application uses global constants to keep track of each database field. Paste the following code into the Declarations section of mdlTVTMain: ’program database fields Global Const LNG_PROG_PROGRAM As Long = 0 Global Const LNG_PROG_CHANNEL As Long = 1 Global Const LNG_PROG_STARTTIME As Long = 2 Global Const LNG_PROG_ENDTIME As Long = 3 Global Const LNG_PROG_CATGID As Long = 4 Global Const LNG_PROG_DESC As Long = 5 Global Const LNG_PROG_PREVIEW As Long = 6 Loading the Programs To load each corresponding television program into the Category form’s grid, a new Sub procedure called LoadPrograms is added to frmTVTCatg. The Sub procedure filters the Program database by category, sorts the Program database by channel, clears and formats the grid, and loads each television program from the database record by record. Sub LoadPrograms accepts a single argument: the bookmark of the chosen category in the category database. It uses the bookmark to retrieve the chosen category’s name and ID (an integer unique to the category). The category name is placed in the user interface. The category ID is used to identify which records in the Program database correspond to the chosen category. Paste the following code into the code window for frmTVTCatg: Public Sub LoadPrograms(ByRef lngCatgBookmark _ As Long) ’loads programs into grid that are in the ’selected category Dim Dim Dim Dim Dim Dim intRows As Integer lngCatgID As Long lngCurrCatgID As Long strCatgName As String strChannel As String strProgram As String ’get the selected record’s category name and ID PDBFindRecordbyID glngCatg, lngCatgBookmark PDBGetField glngCatg, LNG_CATG_CATGID, lngCatgID PDBGetField glngCatg, LNG_CATG_CATGNAME, _ strCatgName lblCatgName.Caption = strCatgName 186 ’Get the total number of rows in the grid intRows = grdProg.Rows ’hide the grid so it will draw faster grdProg.Visible = False ’remove any existing rows from the grid While Not (grdProg.Rows = 0) grdProg.RemoveItem (0) grdProg.Refresh intRows = grdProg.Rows Wend ’format the grid’s column widths grdProg.ColWidth(0) = 40 grdProg.ColWidth(1) = 115 ’target the left column, so that as cell tag ’properties are set below, they are set for the ’left cell in each row grdProg.Col = 0 ’start with the first record PDBMoveFirst glngProg ’while not on the last record of the database While Not PDBEOF(glngProg) ’get the current program’s category id PDBGetField glngProg, LNG_PROG_CATGID, _ lngCurrCatgID ’if the current program’s category id matches ’the category being loaded put it in ’the program grid If lngCurrCatgID = lngCatgID Then ’get the record’s channel and program name PDBGetField glngProg, LNG_PROG_CHANNEL, _ strChannel PDBGetField glngProg, LNG_PROG_PROGRAM, _ strProgram ’add as a new program in the grid grdProg.AddItem strChannel & Chr(9) _ & strProgram, -1 187 ’select the row just added to the grid grdProg.Row = (grdProg.Rows - 1) ’set the cell’s tag as the current ’record’s bookmark grdProg.ItemData(grdProg.Row, grdProg.Col) _ = PDBRecordUniqueID(glngProg) ’set the cell’s current font grdProg.FontStyle = 1 End If ’move to the next record in the database PDBMoveNext glngProg Wend ’If no rows are in the grid, add a row indicating ’there are no listings for this time slot and ’disable the show me button. ’Otherwise enable the show me button If grdProg.Rows = 0 Then grdProg.AddItem "No" & Chr(9) & "Listings" btnShowMe.Enabled = False btnShowMe.ForeColor = afButtonLightGray Else btnShowMe.Enabled = True btnShowMe.ForeColor = afButtonBlack End If ’select the first grid item grdProg.Row = 0 ’show the grid grdProg.Visible = True grdProg.Refresh End Sub Note that as each program is added as a new row to the grid, the new row’s left column is tagged with the program’s record unique ID. This tag will be used later to retrieve more information on the program. 188 Calling Sub LoadPrograms The corresponding television programs should be loaded into the grid before the user sees the Category form. Therefore, the Sub procedure LoadPrograms should be called from the Show Me button’s Click event on the Main form. In addition, the database must be opened and a schema must be defined for the database prior to calling LoadPrograms. If the database is not opened the LoadProgram Sub procedure will generate errors. The schema provides a means to define and label the fields in the database. Edit the Show Me button’s Click event procedure in frmTVTMain so it matches the following (the bold code indicates the newly added lines): Private Sub btnShowMe_Click() ’load the programs into the category form’s grid ’that correspond to the selected category Call frmTVTCatg.LoadPrograms(CLng( _ lstCatg.ItemData(lstCatg.ListIndex))) ’hide this form and show the category form frmTVTMain.Hide frmTVTCatg.Show End Sub Opening the Program Database Prior to calling LoadCategories, the Program database must be opened. Otherwise, the database will remain closed and the LoadCategories Sub procedure will generate errors. Additionally, a successful open of the database should be verified. This is done by adding the program database to the existing check of the category database that already exists in Sub Main. Edit the Sub Main in the standard module mdlTVTMain so it matches the following (the bold code indicates the newly added or edited lines): Sub Main() Dim strCatgPath As String Dim strProgPath As String ’Use conditional compilation to determine if ’program is running on Palm or Windows #If APPFORGE Then ’Palm Path strCatgPath = "Category" strProgPath = "Program" #Else 189 ’Windows Path strCatgPath = App.Path & "\Category" strProgPath = App.Path & "\Program" #End If ’open the databases glngCatg = PDBOpen(Byfilename,strCatgPath, 0, _ 0, 0, 0, 0) glngProg = PDBOpen(Byfilename, strProgPath, 0, _ 0, 0, 0, 0) ’Check to see if the databases were ’successfully opened ’If not bring up the error form ’If so continue by setting the schema ’and loading the categories If glngCatg = 0 Or glngProg = 0 Then ’Database was not successfully opened ’Run the Load Error subroutine ’and show frmTVTError frmTVTError.LoadError frmTVTError.Show Else ’load the categories from the database into ’the Main form’s listbox frmTVTMain.LoadCategories ’show form frmTVTMain.Show End If End Sub There are two important points to note about the path argument of the PDBOpen method: 1. The path argument for the PDBOpen method is different when running in Palm OS and running in Windows. Conditional compilation is used to ensure the proper path is assigned for each. 2. When running on a Palm device, the database name is case-sensitive. Make sure that the name is typed in the correct case. 190 Editing the LoadError Subroutine TVToday now accesses two databases. Therefore, the error message shown when a database is not successfully opened must identify which database has a problem. The error message is assembled in the LoadError subroutine of frmTVTError. Edit it so that it matches the following (the bold code indicates the newly added or edited lines): Public Sub LoadError() Dim strDbName As String ’Identify the missing database If glngCatg = 0 Then strDbName = "Category.PDB" If glngProg = 0 Then strDbName = strDbName & " and Program.PDB" End If ElseIf glngProg = 0 Then strDbName = "Program.PDB" End If ’Set the text for the Error Message text box txtErrorMsg.Text = strDbName & _ " not found. Please HotSync " & strDbName & _ " and run TVToday again." End Sub Running the Project Save the changes made to the project by selecting Save Project from the File menu. Run the application by choosing Start from the Run menu, or by clicking the Start button on the toolbar. The main form will appear with a list of categories within the AFListBox. Click on the Show Me button to navigate to the Category form. A list of matching television programs should be displayed on the grid. 10.6 Lesson 5: Displaying Programs by the Hour The TVToday application should only display television programs in the Category form that air within a one-hour timeframe. Currently, the Sub procedure LoadPrograms loads all the television programs into 191 the grid, regardless of the program’s start or end time. To create this functionality, additional code is added to the Sub procedure LoadPrograms, so that the display will look like the following figure. Figure 24: Category Screen of the TVToday Application Adding Time-Based Code To make the grid only display a one-hour timeframe of programs, we need to add code that filters the data to the Sub procedure LoadPrograms. If a program meets any of the following criteria, the program’s data is inserted into the grid: • The start time for the program is on or within the current hour. • The end time for the program is within or at the end the current hour. • If the start time for the program is before the current hour and the end time for the program is after the current hour. The following figure illustrates the "filtering" logic. 192 Figure 25: Illustration Time-Based Filter Logic The beginning of the one-hour timeframe will be determined by a second procedure argument that should be added to the Sub LoadPrograms. Edit the LoadPrograms Sub procedure in frmTVTCatg so it matches the following (the bold code indicates the newly added lines): Public Sub LoadPrograms(ByVal datNewTime As Date, _ ByRef lngCatgBookmark As Long) ’loads programs into grid that are in the selected ’category, and are viewable between the selected ’new time and an hour past the new time Dim datMaxTime As Date Dim datMinTime As Date 193 Dim Dim Dim Dim Dim Dim Dim Dim Dim datStartTime As Date datEndTime As Date intRows As Integer lngCatgID As Long lngCurrCatgID As Long strCatgName As String strChannel As String strProgram As String blnFillin As Boolean ’get the selected record’s category name and ID PDBFindRecordbyID glngCatg, lngCatgBookmark PDBGetField glngCatg, LNG_CATG_CATGID, lngCatgID PDBGetField glngCatg, LNG_CATG_CATGNAME, _ strCatgName lblCatgName.Caption = strCatgName ’calculate datMinTime ’calculate datMaxTime the timeframe’s start time = datNewTime the timeframe’s end time = DateAdd("h", 1, datNewTime) ’Get the total number of rows in the grid intRows = grdProg.Rows ’hide the grid so it will draw faster grdProg.Visible = False ’remove any existing rows from the grid While Not (grdProg.Rows = 0) grdProg.RemoveItem (0) grdProg.Refresh intRows = grdProg.Rows Wend ’format the grid’s column widths grdProg.ColWidth(0) = 40 grdProg.ColWidth(1) = 115 ’target the left column, so that as cell tag ’properties are set below, they are set for the ’left cell in each row grdProg.Col = 0 ’start with the first record 194 PDBMoveFirst glngProg ’while not on the last record of the database While Not PDBEOF(glngProg) ’get the current program’s category id PDBGetField glngProg, LNG_PROG_CATGID, _ lngCurrCatgID ’if the current program’s category id matches ’the category being loaded If lngCurrCatgID = lngCatgID Then ’Get the start and end times for the programs ’and convert them to time only format PDBGetField glngProg, LNG_PROG_STARTTIME, _ datStartTime datStartTime = TimeSerial(Hour(datStartTime) _ , Minute(datStartTime), 0) PDBGetField glngProg, LNG_PROG_ENDTIME, _ datEndTime datEndTime = TimeSerial(Hour(datEndTime), _ Minute(datEndTime), 0) ’reset blnFillin to false blnFillin = False ’If the start time is on or within the current ’hour, set blnFillin to true If (datStartTime >= datMinTime) And _ (datStartTime < datMaxTime) Then _ blnFillin = True ’If the end time is within the or at the end ’current hour set blnFillin to true If (datEndTime > datMinTime) And (datEndTime _ <= datMaxTime) Then blnFillin = True ’If the start time is before the current hour ’and the end time is after the current hour ’set blnFillin to true If (datStartTime < datMinTime And datEndTime _ > datMaxTime) Then blnFillin = True ’If any of the above criteria were met place ’program data in the grid 195 If blnFillin Then ’get the record’s channel and program name PDBGetField glngProg, LNG_PROG_CHANNEL, _ strChannel PDBGetField glngProg, LNG_PROG_PROGRAM, _ strProgram ’add as a new program in the grid grdProg.AddItem strChannel & Chr(9) _ & strProgram, -1 ’select the row just added to the grid grdProg.Row = (grdProg.Rows - 1) ’set the cell’s tag as the current ’record’s bookmark grdProg.ItemData(grdProg.Row, grdProg.Col) = _ PDBRecordUniqueID(glngProg) ’set the cell’s current font grdProg.FontStyle = 1 End If End If ’move to the next record in the database PDBMoveNext glngProg Wend ’If no rows are in the grid, add a row indicating ’there are no listings for this time slot and ’disable the show me button. ’Otherwise enable the show me button If grdProg.Rows = 0 Then grdProg.AddItem "No" & Chr(9) & "Listings" btnShowMe.Enabled = False btnShowMe.ForeColor = afButtonLightGray Else btnShowMe.Enabled = True btnShowMe.ForeColor = afButtonBlack End If 196 ’select the first grid item grdProg.Row = 0 ’show the grid grdProg.Visible = True End Sub Notice that the start and end times were truncated to only contain time. When the date values are extracted from the database, they have a date associated with them. This would cause the time comparisons to function improperly. Determining the Top of the Hour When users choose to view the television programs corresponding to a specific category, the Category form should display the programs that can be viewed during the current hour. For example, if the time is 2:43pm, the Category form should display the television programs that can be viewed between 2:00pm and 3:00pm. To support this functionality, we will add a new function called TopOfTheHour to the standard module mdlTVTMain. This function receives a date argument containing a time value, truncates the time value down to the closest even hour, and returns the truncated time value as a date. Paste the following code into the standard module mdlTVTMain: Public Function TopOfTheHour(ByVal datNewTime _ As Date) As Date ’returns a date containing the date argument ’rounded down to the previous even ’hour (e.g., 4:53am => 4:00am) ’remove minutes past the hour datNewTime = DateAdd("n", (-1 * _ (Minute(datNewTime))), datNewTime) ’remove seconds past the hour datNewTime = DateAdd("s", (-1 * _ (Second(datNewTime))), datNewTime) ’return the rounded down date TopOfTheHour = datNewTime End Function Calling the Revised LoadPrograms Now that the Sub procedure LoadPrograms requires a date argument, the code calling LoadPrograms from frmTVTMain must be updated. The updated code in the Show Me button’s Click event will 197 determine the top of the current hour and pass that value as an argument to the Sub procedure LoadPrograms. Edit the Show Me button’s Click event procedure on the Main form so it matches the following (the bolded code indicates newly added or modified lines): Private Sub btnShowMe_Click() ’load the programs into the category ’form’s grid that ’correspond to the selected category and are ’on during the current hour Dim datThisHour As Date ’get the top of the current hour datThisHour = mdlTVTMain.TopOfTheHour(Time) ’load programs Call frmTVTCatg.LoadPrograms(datThisHour, _ CLng(lstCatg.ItemData(lstCatg.ListIndex))) ’hide this form and show the category form frmTVTMain.Hide frmTVTCatg.Show End Sub Running the Project Save the changes made to the project by selecting Save Project from the File menu. Run the application by choosing Start from the Run menu, or by clicking the Start button on the toolbar. Click on the Show Me button to navigate to the Category form. A much smaller list of matching television programs is displayed in the grid, due to the timeframe filters. Some categories may not have any matching programs for the current timeframe. 10.7 Lesson 6: Providing Control Over the Program Timeframe The Category form should show the value of the current one-hour timeframe being displayed and give the users the capability to change that timeframe. To accomplish this we will add several Ingots to the Category form, add code to Sub LoadPrograms to display the current timeframe in the user interface, and create code that gives the users control over the timeframe. Following this lesson, the Category Screen should look like the following figure. 198 Figure 26: Category Screen of the TVToday Application To support user control of the currently displayed one-hour timeframe, the following AppForge Ingots will be added during Lesson 6: Button Ingot Description AFShape Used to create rectangles or circles on your forms. AFLabel Functions as a text field that is not directly editable by the user. AFGraphicButton Works like the standard button, but instead of a caption, it can specify different graphics for the up and down click positions. Table 34: Lesson 6 - Ingots to Add Adding Ingots to Control the Timeframe Use the toolbox to draw an AFShape, AFLabel, and two AFGraphicButton Ingots on frmTVTCatg. In the Properties window, set properties for the each Ingot according to the following table. Use the default setting for all other properties. Ingot AFShape Property Setting Name BorderStyle FillColor FillStyle Height Left shpRect5 0 - Transparent &H00AAAAAA& 0 - Solid 22 95 199 Top Width 47 124 AFLabel Name Alignment BackColor Caption FontName FontSize FontStyle Height Left Top Width lblHour 2 - Center &H00FFFFFF& 12:00am AFPalm (12 Regular) 12 0 10 27 53 45 AFGraphicButton1 Name DisabledPicture DownPicture FocusPicture Height Left NoFocusPicture Top Width grbTimeBak TVT_ARBD.RGX TVT_ARBH.RGX TVT_ARBK.RGX 22 0 TVT_ARBK.RGX 47 22 AFGraphicButton2 Name DisabledPicture DownPicture FocusPicture Height Left NoFocusPicture Top Width grbTimeFwd TVT_ARFD.RGX TVT_ARFH.RGX TVT_ARFW.RGX 22 73 TVT_ARFW.RGX 47 22 Table 35: Lesson 6 - New Ingot Properties If all of the properties have been set properly, frmTVTCatg should look like the following figure. 200 Figure 27: frmTVTCatg with Shape, Label, and GraphicButtons Displaying and Retaining the Current Timeframe Value TVToday needs to display the current timeframe value for user feedback, and it also must retain the current timeframe value in global memory for tracking. To do this, two new module-wide variables are used to retain the time value and the category bookmark. They are declared in the form module of frmTVTCatg. Paste the following code into the Declarations section of frmTVTCatg: ’stores current hour shown in UI Dim datCurTime As Date ’stores the database bookmark of the currently ’displayed category Dim lngCurCatgBookmark As Long Next, append code to the Sub procedure LoadPrograms in frmTVTCatg to allow it to retain and display the current timeframe value and category bookmark. Edit Sub LoadPrograms so the last lines of code prior to End Sub appear as follows (the bold code indicates newly added or modified lines): ’select the first grid item grdProg.Row = 0 ’show the grid grdProg.Visible = True grdProg.Refresh ’show the start time in the UI lblHour.Caption = TimeToStr(datNewTime) ’store the start time datCurTime = datNewTime ’store the database bookmark of the currently ’displayed category 201 lngCurCatgBookmark = lngCatgBookmark End Sub Finally, we need to add a function to convert a time value (stored in a date variable) to a formatted string variable (for display in the user interface). Paste the following code into the standard module mdlTVTMain: Public Function TimeToStr(ByVal datNewTime As Date) _ As String ’returns a string representing the date argument ’(e.g., #12:15 PM# => "12:15pm") Dim Dim Dim Dim intHour As Integer intMinute As Integer strMinute As String str_M As String ’get the hour and minute values intHour = Hour(datNewTime) intMinute = Minute(datNewTime) ’determine if it’s AM or PM If (intHour < 12) Then str_M = "am" Else str_M = "pm" End If ’adjust the hour from 24 hour time If (intHour > 12) Then intHour = (intHour - 12) ElseIf (intHour = 0) Then intHour = 12 End If ’zero pad one If (intMinute strMinute = Else strMinute = End If digit minute values < 10) Then "0" & Trim(Str(intMinute)) Trim(Str(intMinute)) ’return the results 202 TimeToStr = Trim(Str(intHour)) & ":" & _ strMinute & str_M End Function Notice that the Sub procedure TimeToStr was called from the Sub procedure LoadPrograms to build a string value of the current time for display in the user interface. Allowing Users to Control the Timeframe To provide users with direct control of the current timeframe, we need to associate code with the Click events of both AFGraphicButton Ingots created earlier in this lesson. In each event procedure, the Sub procedure LoadPrograms is called to reload the grid with a new timeframe of programs. Double-click on the grbTimeBak to view its Click event procedure in the code window. Paste the following code into frmTVTCatg’s form module: Private Sub grbTimeBak_Click() ’show the previous hour’s programs in the UI Call LoadPrograms(DateAdd("h", -1, datCurTime), _ lngCurCatgBookmark) End Sub Notice how the time argument supplied to the Sub procedure LoadPrograms is the stored current timeframe value decreased by an hour. The bookmark argument supplied to the Sub procedure LoadPrograms is the value stored by the Sub procedure LoadPrograms the last time it was called. Next, double-click on grbTimeFwd to view its Click event procedure in the Code window. Paste the following code into frmTVTCatg’s form module: Private Sub grbTimeFwd_Click() ’show the next hour’s programs in the UI Call LoadPrograms(DateAdd("h", 1, datCurTime), _ lngCurCatgBookmark) End Sub Finally, add code to disable grbTimeFwd and grbTimeBak if the last hour or first hour of the day has been reached. Edit Sub LoadPrograms in frmTVTCatg so the last lines of code prior to End Sub appear as follows: ’show the start time in the UI txtHour.Text = TimeToStr(datNewTime) ’store the start time datCurTime = datNewTime ’store the database bookmark of the currently ’displayed category 203 lngCurCatgBookmark = lngCatgBookmark ’disable the forward graphicButton depending on ’the value of the start time If (Hour(datCurTime) = 23) Then grbTimeFwd.Enabled = False Else grbTimeFwd.Enabled = True End If ’disable the backward graphicButton depending on ’the value of the start time If (Hour(datCurTime) = 0) Then grbTimeBak.Enabled = False Else grbTimeBak.Enabled = True End If End Sub Running the Project Save the changes made to the project and run the application. Select a category in the AFListBox. Click on the Show Me button to navigate to the Category form. The form displays a list of matching television programs in the grid, as well as the start of the current one-hour timeframe. Click the AFGraphicButtons to the left and right of the current timeframe value to change the timeframe. 10.8 Lesson 7: Creating a Program Form In this lesson, we will add a new form to display detailed information on a selected television program. Once users have selected a program on the Category form, we want them to be able to click the Show Me button to view detailed program information on a third form. 204 Figure 28: frmTVTProg with AFShape, AFTextBox, and AFGraphicButtons To create the user interface for the Program form, AppForge Ingots are added to the form. Lesson 7 of the tutorial uses the following Ingots: Button Ingot Description AFShape Creates rectangles or circles on your forms. AFButton Text button that can receive user events to begin, interrupt, or end a process. AFGraphic Displays a graphic in the application. Valid graphic formats are .bmp, .rgx, .jpg, or .png*. AFLabel Functions as a text field that is not directly editable by the user. AFGraphicButton Works like the standard button, but instead of a caption, it can specify different graphics for the up and down click positions. Table 36: Lesson 7 - Ingots to Add *AppForge MobileVB 3.1 or later is required to utilize a .png file. See theBooster and PNG Files Section of the AppForge Booster And Additional Files documentation for details. Adding a New Form Before laying out the user interface for the Program form, a new form must be added to the project. 205 1. Select Add Form from the Project menu. This will bring up the Add Form dialog box. 2. Select Form from the Add Form dialog box. 3. Click the Open button. In order to identify this form later, it should be named. In the Properties window, set the form’s name property to frmTVTProg and clear the Caption property. Copying Ingots to the Program Form Nine of the Ingots we will use on the Program form are nearly identical to Ingots on the Category form. To save time, copy the matching Ingots from frmTVTCatg to frmTVTProg. The nine matching Ingots are named grbTVBack, lblTVToday, lblCatgName, shpLine1, shpRect2, shpRect3, shpRect4, btnShowMe, and gphArrowRight. To copy Ingots from one form to another: 1. Open the Category form, frmTVTCatg. You can double-click on the form’s name in the Project Explorer window to show it. 2. Select the first component to copy by clicking on it in the form. 3. Select each additional component to copy by holding down the Shift key and clicking on each component you want. 4. Copy the components by selecting Copy from the Edit menu, or by clicking the Copy button on the toolbar. 5. Open the Ingots’ destination form, frmTVTProg. 6. Paste the components by selecting Paste from the Edit menu, or by clicking the Paste button on the toolbar. Once the AppForge Ingots are pasted onto the Program form, update two Ingots’ properties: Ingot shpLine1 btnShowMe Property Left Top Width Name Caption Setting 21 48 139 btnPreview preview Table 37: Copied Ingots Properties 206 The Program Form should now look like this: Figure 29: Program Form with Copied Ingots Adding Ingots to the Program Form Use the toolbox to draw an AFShape and AFGraphicButton on frmTVTProg. In the Properties window, set properties for the Ingots according to the following table. Use the default setting for all other properties. Ingot Property Setting AFShape Name BorderStyle FillColor FillStyle Height Left Top Width shpLine2 0 - Transparent &H00AAAAAA& 0 - Solid 2 0 72 160 AFGraphicButton Name DownPicture FocusPicture Height Left NoFocusPicture Top Width grbCatgBack TVT_CGBH.RGX TVT_CGBK.RGX 23 0 TVT_CGBK.RGX 27 21 Table 38: Lesson 7 - New Ingot Properties 207 The Program Form should now look like the following figure. Figure 30: Program Form with Shape and GraphicButton Creating Navigation between Category and Program Forms When users click the Show Me button on the Category form, the Program form should replace the Category form. Double-click the Show Me button in frmTVTCatg to view the button’s Click event in the Code window. Paste the following code into frmTVTCatg’s form module: Private Sub btnShowMe_Click() ’hide this form and show the program form frmTVTCatg.Hide frmTVTProg.Show End Sub To complete the navigation between the Category and Program forms, code must be added to frmTVTProg. When users click on the lower AFGraphicButton on the Program form, the Category form should replace the Program form. Double-click the lower AFGraphicButton on the Program form to view grbCatgBack’s Click event in the Code window. Paste the following code into frmTVTProg’s form module: Private Sub grbCatgBack_Click() ’hide this form and show the category form frmTVTProg.Hide frmTVTCatg.Show End Sub Creating Navigation from Program Form to Main Form When the top AFGraphicButton on the Program Form is clicked, the Main form should replace the Program form. Double-click the top AFGraphicButton on the Program form to view grbTVBack’s Click event in the code window. Paste the following code into frmTVTProg’s form module: 208 Private Sub grbTVBack_Click() ’hide this form and show the main form frmTVTProg.Hide frmTVTMain.Show End Sub Saving the Project Save the changes made to the project by selecting Save Project from the File menu. Save the following file with the corresponding file name: File Form File Name frmTVTProg.frm Table 39: Lesson 7 - New Form Name Running the Project Run the application. Select a category in the ListBox and click on the Show Me button to navigate to the Category form. Select a program in the grid and click on the Show Me button again to see the program form. You can then click on either graphic button to navigate to one of the previous two forms. 10.9 Lesson 8: Displaying Program Information When users choose to view a program on the Program form, we want the form to display the title, the channel, the starting and ending times, and a description of the program, if available. Figure 31: Program Screen of the TVToday Application In this lesson, program information is loaded from the Program database into the user interface. Begin 209 by adding AppForge Ingots to the Program form that will display the program information. Lesson 8 of the tutorial uses the following Ingots: Button Ingot Description AFLabel Functions as a text field that is not directly editable by the user. AFTextBox Displays text on the form, or provides a text input box for the user. Table 40: Lesson 8 - Ingots to Add Adding Display Ingots to the Program Form Use the toolbox to draw one AFTextBox and one AFLabel on frmTVTProg. In the Properties window, set properties for the each Ingot according to the following table. Use the default setting for all other properties. Ingot Property Setting AFLabel Name BackColor Caption FontName FontSize FontStyle Height Left Top Width lblProgName &H00FFFFFF& Program Name AFPalm (15 Regular) 15 0 15 7 55 153 AFTextBox Name BackColor BorderStyle FontName FontSize FontStyle Height Left MultiLine ScrollBars Text txtDesc &H00FFFFFF& 1 - Single AFPalm (12 Regular) 12 0 66 0 True 2 - Vertical This is the description text for a television program. 210 Top UnderlineStyle Width 74 0 - None 160 Table 41: Lesson 8 - Ingot Properties The Program Form should now look the following figure. Figure 32: Program Form with Label and TextBox Formatting the Time Range Two points of information supplied to users on the Program form are the start time and the end time of the selected program. The data for these reside in the Program database in date-type data fields. To present this information in the user interface, the time values have to be converted to strings and formatted. This calls for the addition of a new function to the standard module mdlTVTMain. This new function, named TimeRangeToStr, will accept two time value arguments as dates and return a formatted string containing the time values. Paste the following code into the standard module mdlTVTMain: Public Function TimeRangeToStr(ByVal datStartTime _ As Date, ByVal datEndTime As Date) As String ’returns a string defining a time range based ’on the two date arguments (e.g., #12:30 PM# and ’#1:30 PM# => "12:30 - 1:30pm") Dim strStartTime As String Dim strEndTime As String ’convert the date arguments to strings 211 strStartTime = TimeToStr(datStartTime) strEndTime = TimeToStr(datEndTime) ’if the times have the same AM/PM If (Right(strStartTime, 2) = Right(strEndTime, 2)) _ Then ’remove the AM/PM from the start time strStartTime = Left(strStartTime, _ (Len(strStartTime) - 2)) End If ’build and return the date range TimeRangeToStr = strStartTime & " - " & strEndTime End Function Note that this Sub procedure calls the Sub procedure TimeToStr to convert the time values from dates to strings. Loading the Program Information To load program information into the Program form, a new Sub procedure called LoadProgramInfo needs to be added to frmTVTProg. This Sub procedure displays the current category name in the user interface, finds the selected program in the Program database, and retrieves and displays program information from the record. Paste the following code into the code window for frmTVTProg: Public Sub LoadProgramInfo(ByVal lngProgBookmark _ As Long, ByVal strCatgName As String) ’loads program information into the UI that ’corresponds to the selected program bookmark Dim Dim Dim Dim Dim Dim strChannel As String strProgram As String strDescription As String datStartTime As Date datEndTime As Date strProgTime As String ’put the category name in the UI lblCatgName.Caption = strCatgName ’target the selected program PDBFindRecordbyID glngProg, lngProgBookmark 212 ’put the program name in the UI PDBGetField glngProg, LNG_PROG_PROGRAM, strProgram lblProgName.Caption = strProgram ’get the channel PDBGetField glngProg, LNG_PROG_CHANNEL, strChannel ’get the start time PDBGetField glngProg, LNG_PROG_STARTTIME, _ datStartTime datStartTime = TimeSerial(Hour(datStartTime), _ Minute(datStartTime), Second(datStartTime)) ’get the end time PDBGetField glngProg, LNG_PROG_ENDTIME, datEndTime datEndTime = TimeSerial(Hour(datEndTime), _ Minute(datEndTime), Second(datEndTime)) ’get the description PDBGetField glngProg, LNG_PROG_DESC, _ strDescription ’build the date range string strProgTime = TimeRangeToStr(datStartTime, _ datEndTime) ’put the description in the UI txtDesc.Text = strChannel & ": " & strProgTime & _ Chr(13) & strDescription End Sub Notice how this Sub procedure calls the Sub procedure TimeRangeToStr to build the date range string. Calling Sub LoadProgramInfo The program information should be loaded into the Program form’s user interface before the Program form is shown. Therefore, the Sub procedure LoadProgramInfo should be called in the Click event of the Show Me button on frmTVTCatg. Double-click the Show Me button on the Category form to view its Click event procedure. Edit the procedure so that it matches the following (the bold code indicates newly added or modified lines): Private Sub btnShowMe_Click() 213 ’load the program info into the program form’s UI ’that correspond to the selected program ’target the gridrow’s left cell to retrieve ’its tag (i.e., the corresponding bookmark) grdProg.Col = 0 ’load the programs Call frmTVTProg.LoadProgramInfo(grdProg.ItemData _ (grdProg.Row, grdProg.Col), lblCatgName.Caption) ’hide this form and show the program form frmTVTCatg.Hide frmTVTProg.Show End Sub Notice how this procedure references a program’s database record by retrieving the record’s unique ID from the grid. In Lesson 4, the unique ID values were added as tags to the left cell of every new grid row. Running the Project Save the changes made to the project and run the application. Select a category in the ListBox. Click on the Show Me button to navigate to the Category form, and select a program in the grid. Click on the Show Me button to display the program’s category, title, channel, start time, end time, and description. 10.10 Lesson 9: Creating the Preview Form In this lesson, a new form is added to display filmstrip previews of a selected television program. When users navigate to the Program form, we want the Preview button to be enabled or disabled depending on the availability of a filmstrip preview for the selected TV program. If a filmstrip preview is available, users may click on the Preview button to watch it. 214 Figure 33: Preview Screen of the TVToday Application To create the user interface for the Preview form, Lesson 9 of the tutorial uses the following AppForge Ingots: Button Ingot Description AFShape Used to create rectangles or circles on your forms. AFLabel Functions as a text field that is not directly editable by the user. AFGraphicButton Works like the standard button, but instead of a caption, it can specify different graphics for the up and down click positions. Table 42: Lesson 9 - Ingots to Add Adding a Preview Form Before laying out the user interface for the Preview form, a new form must be added to the project. 1. Select Add Form from the Project menu. This will bring up the Add Form dialog box. 2. Select Form from the Add Form dialog box. 3. Click the Open button. In the Properties window, set the form’s name property to frmTVTPrev and clear the Caption property. 215 Copying Ingots to the Preview Form Nine of the Ingots we will use on the Preview form are nearly identical to Ingots on the Program form. To save time, copy the matching Ingots from the Program form to the Preview form. The nine matching Ingots are named: grbTVBack, lblTVToday, grbCatgBack, lblCatgName, shpLine1, shpLine2, shpRect3, shpRect4, and lblProgName. To copy Ingots from one form to another: 1. Open the Program form, frmTVTProg. You can double-click on the form’s name in the Project Explorer window to show it. 2. Select the first component to copy by clicking on it in the form. 3. Select each additional component to copy by holding down the Shift key and clicking on each component you want. 4. Copy the components by selecting Copy from the Edit menu, or by clicking the Copy button on the toolbar. 5. Open the Ingots’ destination form, frmTVTPrev. 6. Paste the components by selecting Paste from the Edit menu, or by clicking the Paste button on the toolbar. Once the AppForge Ingots are pasted onto the Preview form, change two Ingots’ properties to the following: Ingot lblProgName shpLine2 Property Left Width Left Width Setting 40 120 21 139 Table 43: Lesson 9 - Copied Ingots Property Changes The following figure shows the Preview Form as it should now appear. 216 Figure 34: Preview Form with Copied Ingots Adding Ingots to the Preview Form Use the toolbox to draw an AFGraphicButton Ingot and four AFShape Ingots on frmTVTCatg. In the Properties window, set properties for the Ingots according to the following table. Keep all other settings at their defaults. Ingot Property Setting AFGraphicButton Name DownPicture FocusPicture Height Left NoFocusPicture Top Width grbProgBack TVT_PGBH.RGX TVT_PGBK.RGX 23 0 TVT_PGBK.RGX 51 21 AFShape1 Name BorderStyle FillColor FillStyle Height Left Top Width shpRect5 0 - Transparent &H00AAAAAA& 0 - Solid 4 21 156 139 AFShape2 Name BorderStyle FillColor FillStyle shpRect6 0 - Transparent &H00AAAAAA& 0 - Solid 217 Height Left Top Width 84 0 76 21 AFShape3 Name BorderStyle FillColor FillStyle Height Left Top Width shpRect7 0 - Transparent &H00AAAAAA& 0 - Solid 80 141 76 19 AFShape4 Name BorderStyle FillColor FillStyle Height Left Top Width shpRect8 0 - Transparent &H00AAAAAA& 0 - Solid 3 0 73 160 Table 44: Lesson 9 - New Ingot Properties The Preview Form should now look like this: Figure 35: frmTVTPrev with AFGraphicButton and Shape Ingots 218 Enabling and Disabling the Preview Button Not every TV program listed in the Program database will have a filmstrip preview. Therefore, we need to add code that checks for the availability of a preview and enables or disables the Preview button accordingly. Edit the beginning of the Sub procedure LoadProgramInfo in the frmTVTProg code window so that it includes the following code (the bold code indicates the newly added line): Public Sub LoadProgramInfo(ByVal lngProgBookmark _ As Long, ByVal strCatgName As String) ’loads program information into the UI that ’corresponds to the selected program bookmark Dim Dim Dim Dim Dim Dim Dim strChannel As String strProgram As String strDescription As String strPreview As String datStartTime As Date datEndTime As Date strProgTime As String Now edit the end of LoadProgramInfo (newly added lines in bold): ’put the description in the UI txtDesc.Text = strChannel & ": " & strProgTime _ & Chr(13) & strDescription ’if there’s not a preview for the program PDBGetField glngProg, LNG_PROG_PREVIEW, _ strPreview If (strPreview = "") Then ’disable the preview button btnPreview.Enabled = False Else ’enable the preview button btnPreview.Enabled = True End If End Sub Creating Navigation between Program and Preview Forms When a filmstrip preview is available for a TV program, we want users to be able to click the Preview button to view the filmstrip clip. The Preview form should replace the Program form when they click the button. 219 Double-click the Preview button on the Program form to view the button’s Click event in the code window. Paste the following code into frmTVTProg’s form module: Private Sub btnPreview_Click() ’hide this form and show the preview form frmTVTProg.Hide frmTVTPrev.Show End Sub To complete the navigation between the Program and Preview forms, we need to add code to frmTVTPrev. When users click on the bottom AFGraphicButton on the Preview form, the Program form should replace the Preview form. Paste the following code into frmTVTPrev’s form module: Private Sub grbProgBack_Click() ’hide this form and show the program form frmTVTPrev.Hide frmTVTProg.Show End Sub Creating Navigation from Preview Form to Category Form When users click on the AFGraphicButton next to the category name on the Preview form, the Category form should replace the Preview form. Paste the following code into frmTVTPrev’s form module: Private Sub grbCatgBack_Click() ’hide this form and show the category form frmTVTPrev.Hide frmTVTCatg.Show End Sub Creating Navigation from Preview Form to Main Form When users click on the top AFGraphicButton on the Preview form, the Main form should replace the Preview form. Paste the following code into frmTVTPrev’s form module: Private Sub grbTVBack_Click() ’hide this form and show the main form frmTVTPrev.Hide frmTVTMain.Show End Sub 220 Running the Project Save and run the application. Select the Drama category in the ListBox. Click on the Show Me button to navigate to the Category form, and move to the 2:00pm timeframe. Select "Before the Storm" in the grid. Click on the Show Me button to view the program, and click on the Preview button to move to the Preview form. Click on any of the three AFGraphicButtons to navigate to one of the previous three forms. 10.11 Lesson 10: Displaying Program Previews When users choose to view a program’s preview, the Preview form should appear containing the program’s filmstrip clip. The program database provides a field that indicates the existence of a preview. The preview should play continuously until the user navigates away from the Preview form. Figure 36: Preview Screen of the TVToday Application In this lesson, filmstrip previews are loaded into the user interface using the corresponding filenames in the Program database. In Lesson 10, an AppForge Filmstrip Ingot is added to the Preview form: Button Ingot Description AFFilmstrip Allows the application designer to animate a series of graphics within the application. Table 45: Lesson 10 - New Ingots Adding the AFFilmstrip Ingot Use the toolbox to draw an AFFilmstrip Ingot on frmTVTPrev. In the Properties window, set properties for the Ingot according to the following table. Use the default setting for all other properties. 221 Ingot AFFilmstrip Property Setting Name AnimationStyle Height Interval Left Top Width flmPrev 1 - Loop 80 200 22 76 119 Table 46: Lesson 10 - New Ingot Properties Setting the Frames Property The filmstrip Ingot provides a means of animating a series of graphics. The graphics and their sequence are set through the Frames property of the AFFilmstrip Ingot. To set the Frames property of flmPrev, select Frames property in the flmPrev properties window. Figure 37: Frames Property in the flmPrev Properties Window Next, click on the ... button in the Frames Property. This brings up the frames property window. 222 Figure 38: Frames Property Window Click on the Add button to browse for graphics files. Each graphic file you add becomes part of the animation sequence. The sequence of the graphics in the filmstrip animation is changed by selecting a specific graphic and clicking on the Up or Down button. To remove a graphic from the list, click on the Remove button. The graphics we will use are located in the ...VB Toolkit\doc\VBTutorial\Graphics folder of the MobileVB™ install folder. The Property window provides the ability to browse to this location for the files, and will copy the selected files to the current project directory. Alternatively, the files may be manually copied directly from the above folder into the current project directory. The final Frames list should be as follows: Mov_00.RGX Mov_01.RGX Mov_02.RGX Mov_03.RGX Mov_03.RGX Mov_03.RGX Mov_03.RGX Mov_03.RGX Mov_02.RGX Mov_01.RGX Mov_00.RGX Mov_00.RGX Mov_04.RGX Mov_05.RGX Mov_06.RGX Mov_06.RGX 223 Mov_06.RGX Mov_06.RGX Mov_06.RGX Mov_05.RGX Mov_04.RGX Mov_00.RGX Mov_00.RGX Mov_07.RGX Mov_08.RGX Mov_09.RGX Mov_10.RGX Mov_11.RGX Mov_10.RGX Mov_09.RGX Mov_10.RGX Mov_11.RGX Mov_10.RGX Mov_09.RGX Mov_10.RGX Mov_11.RGX Mov_10.RGX Mov_09.RGX Mov_09.RGX Mov_09.RGX Mov_09.RGX Table 47: Frames Sequence Make sure to that the Frames list matches the above list exactly. If the order is altered or files omitted the preview will not appear correctly. Loading the Preview To load the preview into the Preview form, a new Sub procedure called LoadPreview should be added to frmTVTPrev. The Sub procedure places the category and program name into the user interface and starts the filmstrip preview playing. Paste the following code into the form module frmTVTPrev: Public Sub LoadPreview(ByVal strProgName As String, _ ByVal strCatgName As String) ’loads preview and plays it 224 ’load the category and program name into the UI lblCatgName.Caption = strCatgName lblProgName.Caption = strProgName ’play the filmstrip flmPrev.Play End Sub Calling Sub LoadPreview The Sub procedure LoadPreview should be called in the Click event code of the Preview button on frmTVTProg. Double-click the Preview button on the Program form to view its Click event procedure. Edit the procedure so that it matches the following (the bold code indicates newly added lines): Private Sub btnPreview_Click() ’hide this form and show the preview form frmTVTProg.Hide frmTVTPrev.Show ’load the preview Call frmTVTPrev.LoadPreview( _ lblProgName.Caption, lblCatgName.Caption) End Sub Stopping the Filmstrip Upon exiting the preview screen, the filmstrip needs to be stopped so that it does not continue running. Since there are three buttons on the preview screen that allow users to change screens, each button’s Click event must include code to stop the filmstrip. In frmTVTPrev, change the grbCatgBack button’s Click event to match the following (the bold code indicates newly added lines): Private Sub grbCatgBack_Click() ’stop the movie flmPrev.Stop ’hide this form and show the category form frmTVTPrev.Hide frmTVTCatg.Show End Sub Also, change the Click event for the grbProgBack on frmTVTPrev to match the following (the bold code 225 indicates newly added lines): Private Sub grbProgBack_Click() ’stop the movie flmPrev.Stop ’hide this form and show the program form frmTVTPrev.Hide frmTVTProg.Show End Sub Finally, edit the Click event for the grbTVBack button in frmTVTPrev as follows (new code in bold): Private Sub grbTVBack_Click() ’stop the movie flmPrev.Stop ’hide this form and show the main form frmTVTPrev.Hide frmTVTMain.Show End Sub Running the Project First, save the changes made to the project and then run the application. Select the Drama category in the AFListBox. Click on the Show Me button to navigate to the Category form, and move to the 2:00pm timeframe. Select the program "Before The Storm" in the grid. Click on the Show Me button to view the program, and click on the Preview button to move to the Preview form. Once on the Preview form, a filmstrip preview for the TV program should play. 10.12 Lesson 11: Uploading the MobileVB™ Project At this point all the functionality for the TVToday application has been added. This lesson steps through setting project dependencies, compiling, and uploading the TVToday application to a Palm OS® device. Setting the Dependencies For TVToday to function properly on a mobile device, we need to specify file dependencies that are referenced only in code (this is, files not used by Ingots such as AFGraphicButton and AFFilmstrip). In the case of TVToday, we need to add Category.PDB and Program.PDB to the list. 226 MobileVB™ project dependencies are set through the Project Properties Dialog. Open the Project Properties by selecting the MobileVB™ Project Settings... option from the MobileVB Menu. Figure 39: MobileVB Menu with MobileVB Settings Selected This will launch the MobileVB Settings window. Click on the Dependencies tab and the dependencies, currently blank, will appear. 227 Figure 40: Blank Dependencies Page Click on the Add button, and add the following files to the list: Dependency Files Category.PDB Program.PDB Table 48: Dependencies Click OK to exit the MobileVB Settings window. Uploading the Project to a Mobile Device NOTE: If the target device in running Pocket PC, make sure it is hooked up to the desktop computer and that the device’s ActiveSync® connection is activated. To upload TVToday to a mobile device, begin by selecting Deploy to Device from the MobileVB Menu. 228 Figure 41: Deploying the Project If the TVToday project was not saved prior to the start of the upload process, the dialog box prompts you to save your project before compiling. Click Yes to save and continue the uploading process. Figure 42: Click Yes to Continue Upload Now MobileVB™ will compile the TVToday application. A compilation progress box should appear. 229 Figure 43: Compilation Progress Box When compiling the code in a project, MobileVB analyzes the code for possible errors or conflicts that may prevent a project from functioning properly once uploaded to the target hardware. If MobileVB™ finds any potential difficulties, it will identify them. Otherwise, the code will be compiled and the upload will continue. If the target hardware is a Palm OS device, following the compilation of TVToday, MobileVB transfers the program to the device’s Install folder. The following sequence of windows should appear: Figure 44: Transfer In Progress 230 Figure 45: HotSync Notification Click OK to finish the upload process. If the target device is running Palm OS® , initiate a HotSync™ operation. Once TVToday and its databases have been uploaded to the handheld device, the TVToday Icon should appear in the device’s applications menu. Tap on it to start TVToday. If the target hardware is a Pocket PC device, MobileVB™ transfers the program to the device via the ActiveSync® connection. It will be installed automatically in the My Device\Program Files\AppForge Projects folder. Tap on the TVToday entry in this directory to launch the application. Viewing Messages in the Compiler If errors are discovered in the process of compiling a MobileVB™ project, the progress window will indicate there is an error. Additionally, MobileVB provides a Compiler Messages window that displays the potential error. Figure 46: MobileVB(tm) Compiler Messages Congratulations! You have successfully developed the TVToday application and completed the MobileVB™ tutorial. 231 11 11.1 AppForge MobileVB™ Add-In Guide Overview The MobileVB™ Add-In is an extension of Visual Basic® accessible under the "MobileVB" item in the Visual Basic menu bar. Figure 47: MobileVB(tm) Menu in Visual Basic When you create or open a MobileVB™ project, Visual Basic activates the MobileVB Add-In in the menu bar. You can use this menu to compile or upload your project, change project settings, install the AppForge Booster, access user help, and more. The following sections explain each menu item in detail. 232 Menu Item Compile and Validate Deploy To Device Save Project Package MobileVB Settings Install Booster To Device Open MobileVB Project Zoom Window MobileVB Messages Window AppForge Utilities MobileVB User’s Guide Samples and Tutorials AppForge on the Web License Information About MobileVB Description Compiles the current project, and checks for common mistakes Install the current project on the target device Create the files needed by the handheld device without installing them Includes device settings and dependencies (graphics, databases, etc.) Install Booster, the AppForge runtime engine, on the target device Open a new or existing MobileVB Project Shows a magnified view of the project Shows the MobileVB Messages Window. Utilities for creating and viewing AppForge-compatible support files Opens the AppForge MobileVB Users Guide Help File Provides access to the several tutorials and the many samples included with MobileVB This item links directly tohttp://support.appforge.com Opens a form for entering the registration key, evaluating, or purchasing your copy of MobileVB Version number and other product information Table 49: Add-In Overview Visual Basic is a registered trademark of Microsoft Corporation in the United States and/or other countries. Palm OS is a registered trademark of Palm, Inc. 11.2 Compile and Validate When compiling a project, MobileVB™ analyzes the code for errors and possible conflicts that may prevent the project from functioning properly once it has been uploaded to the target hardware. If MobileVB finds any potential difficulties, it will identify them in an "MobileVB Messages" window. If there are no errors, MobileVB™ compiles the current project. To compile, select Compile and Validate from the MobileVB menu. First, the project is validated. Then, the compilation of the code begins, and progress information is provided as it compiles. If the compilation is completed successfully, the progress window will disappear. 233 Figure 48: Start Compiling a MobileVB(tm) Project Figure 49: Validation In Progress 234 Figure 50: Compilation in Progress Compiler Error and Warning Messages If errors or potential conflicts are discovered in the process of compiling a project, MobileVB™ displays them in the Messages window. The window displays the error or warning code, and details on the location of the error. To be taken directly to code containing an error or flagged with a warning, double-click on the message in the Messages window. For specific help with any warning or error, select it in the Messages window and press F1. Additionally you may copy the error message to the clipboard by pressing Ctrl-C. This window can be reopened later using theMobileVB Messages Window menu option of the MobileVB Add-In. Figure 51: MobileVB Messages Window 235 11.3 Deploy To Device MobileVB™ takes a compiled project and uploads it to the target handheld device running either Palm OS® , Pocket PC, or Symbian OS. To upload a project to a Palm OS® -powered handheld device, MobileVB converts the compiled application to Palm format (.PRC), and copies it into the Palm Install directory. Any Palm databases (.PDB files) that have been specified as dependencies (see MobileVB Project Settings) will also be copied into the Install directory. The entire project is uploaded to the device during the next HotSync. To upload a project to a Pocket PC device, the device must be connected to the desktop computer via Microsoft® ActiveSync® . MobileVB™ sends the project directly to the device, which then installs it. (If a project has been installed already, the device will prompt you to re-install it.) To begin the upload, select the Deploy to Device item from the MobileVB Menu, and choose the target operating system, Palm OS® or Pocket PC. You can also choose All Compile Targets to upload the project to each kind of device. The MobileVB menu also provides a Deploy to option based on the selected design target. This provides the same functionality as the Deploy to Device menu item. Figure 52: Starting the Project Upload If the project has not been saved since the last compilation, a window will appear asking if you would like to save and continue compiling. Click Yes to save and compile the project, and No to cancel the deploy. 236 If the target is Palm OS® and a user or Creator ID for the project has not been set, a warning box will appear. Enter the information in the dialog and click OK to set the relevant options for this project. (The same dialog is available from the MobileVB Settings menu option.) Also if the target is Palm OS® , when the process is complete MobileVB™ indicates that the program is ready to be uploaded during the next HotSync™ operation. If the target is Pocket PC, the file is uploaded to the device immediately (the device must be connected to the desktop computer via ActiveSync). By default the project is installed to the My Device\Program Files\AppForge Projects directory on the device. (The installation directory can be changed by accessing the MobileVB Settings menu option.) Figure 53: Compile Prompt Figure 54: Palm OS: Ready to Upload 11.4 Save Project Package Use the Save Project Package menu item to create the files needed by the handheld device without uploading them. This includes a .PRC file for Palm OS® , a .CAB file for Pocket PC, or a .SIS file Symbian OS. The project package also includes any databases you have specified as dependencies (see MobileVB Settings). 237 Figure 55: Selecting the Save Project Package... Menu Option. If the project has not been saved since the last compile, a window will appear asking if you would like to save. Click Yes to save the project, and No to cancel the Save. Once the device package has been created, select a target folder for it using the Save install file window. Browse to the desired folder and click OK. The device package, including the necessary .PRC, .CAB, .SID, or .PDB files, is saved to the selected folder. Figure 56: Prompt to Save Before Compiling 238 Figure 57: Browsing for a Destination Folder 11.5 MobileVB Settings To change the settings for the active MobileVB™ project, select the MobileVB Settings option from the MobileVB Menu. 239 Figure 58: Selecting MobileVB Settings... This launches the MobileVB™ Settings dialog box. 240 Figure 59: MobileVB Settings It provides access to the following settings. Details on the settings are provided in the following sections. Setting App Name/Icon Dependencies Palm OS Settings Pocket PC Settings Nokia Series 80 Settings Compiler Settings My Devices Description Change the application icon and name for your application. Edit the file dependencies for your MobileVB project. Provides access to Palm OS specific settings. Specify Pocket PC project settings. Edit settings specific to the Nokia Series 9200 Communicators Set advanced options used when compiling your project. Select the devices you have connected. Used for To My Devices menu items. Setting the Application Icon and Name TheApplication Icon is the image displayed on the device to represent your application. Click on the App Name/Icon branch of the project settings to set it. The Browse button allows you to select an .ico file to associate with your application. 241 If your application name has underscores in it that you would like to replace with spaces, select the Convert underscores in project name to spaces checkbox. With that checkbox selected, a project named "My_MobileVB_Project" would be displayed on the device as "My MobileVB Project". Figure 60: MobileVB(tm) Application Name and Icon Settings Setting Project Dependencies To access and change the file dependencies for a MobileVB™ project, click on the Dependencies branch in the MobileVB Settings window. The Dependencies area is where you specify the files your project needs to function and compile properly (e.g. graphics, fonts, and databases). MobileVB can automatically scan forms for dependencies, or you can add and delete them manually. 242 Figure 61: Project Dependencies Add Dependencies To add a dependency manually, click on the Add button in the User Dependencies section. Select the file to add to the list and click Open. If the selected file does not exist in the project’s working directory, you will be prompted to copy it there. Remove Dependencies To remove a dependency, select the desired dependency and click the Remove button. Automatic Dependencies Click on the Automatic Dependencies tab to view a list of files automatically detected by MobileVB™ in your last compile. Note: The dependency scan only adds files specified through Ingot properties. Files that are referenced solely in code (e.g. databases) must be added manually. Setting Palm OS Project Properties The Palm OS project properties are broken down into Basic and Advanced settings. Basic settings include HotSync Name and CreatorID information. Advance settings include PRC settings and file packaging options. To modify these settings click on the Palm OS Setting branch in the Available Settings 243 area. Setting the HotSync Name and Creator ID The HotSync Name and Creator ID settings are accessed by selecting the Basic tab. Select the current user of MobileVB™ from a pull-down menu of available Palm OS users. The Creator ID is set by typing a unique four-character identifier into the textbox labeled Creator ID. It must meet the following criteria: • Creator ID must consist of four alpha-numeric characters • All ASCII characters between 33 and 127 are valid • Creator IDs consisting of all lowercase letters are reserved for use by Palm Inc. Note: The default CreatorID, DEMO, is intended for demonstration purposes only. Each application that runs on Palm OS must have a unique CreatorID. If a device already has an application with the same Creator ID, your application cannot be installed onto the device. AppForge recommends changing the CreatorID to one that has been registered with Palm (this is a free service). Click on the Register Creator ID button to connect to the Palm CreatorID web page. The URL for the web page ishttp://www.palmos.com/dev/tech/palmos/creatorid . Click OK to finalize all changes. 244 Figure 62: Palm OS Basic Project Settings Palm OS Advanced Settings The Palm OS Advanced settings are accessed by selecting the Advanced tab in the Palm OS Project Settings section. Advanced settings include PRC attributes and packaging options. Three options are available for PRC Attribute Bits: • Backup - Select this option to create a backup of the application on your PC during HotSync • Hidden Icon - Select this option if you do not want the application’s icon to show up in the Palm Applications Launcher • Prevent Beam - Select this option if want to prevent this application from being beamed. If the Include Booster files with install package option is selected, the .prc file produced using the Deploy to Palm OS... or the Save Project Package... will include the following: • AppForge Booster • All Dependency Files • Any Additional Ingots Required by the Application 245 • Any Additional Libraries Required by the Application The default name for the .prc is AppName-Install.prc. When this .prc is installed on a Palm OS device, the AppForge Booster is installed along with all of the additional files the application requires. If the Include Booster files with install package option is NOT selected, AppName-Install.prc is still generated, but AppForge Booster is not included in that .prc. When an application is installed using HotSync, AppName-Install.prc automatically extracts all of its compressed files on the device. If the Auto Delete Compressed Package option is selected AppNameInstall.prc is deleted following the auto extraction. If this option is not selected, AppName-Install.prc remains on the device. If you do not wish to see Palm OS specific warnings during the packaging process deselect the Show Palm OS specific warnings when making project packages option. Click OK to finalize all changes. Figure 63: Palm OS Advanced Project Settings Setting Pocket PC Project Properties To change the current Provider or Company Name or Device Installation Path, click on the Pocket PC Settings tab. 246 This window allows you to specify a creator name that will be associated with the application, and the path to which the project will be saved on the Pocket PC device. Select the Include Booster files in the generated CAB file checkbox to bundle AppForge Booster with your application. Figure 64: Pocket PC Project Settings Setting Nokia Series 80 Project Settings To change the Symbian OS application UID or deployment options for your Nokia device, click on the Nokia Series 80 Settings tab. The options on the Nokia settings screen affect the way in which an application is deployed. First, an application may be deployed to either a connected device, or to an emulator installed on the development computer. If deploying to a device, the connected device will be queried for a list of valid drives. If no device is connected or if deploying to the emulator, the C drive will be the only drive choice available. When deploying to a device, the process of checking for existing versions of an application, then removing the old version before installing the application you orginally tried to deploy may be come very time-consuming. Developers who wish to skip this process should check the Overwrite existing version option. With this option checked, any applications on the device will simply be overwritten without checking for or uninstalling existing versions. Finally, developers have the option of packaging Booster with their application. 247 Figure 65: AppForge Nokia Series 80 Settings Symbian OS application UIDs The application UID is a unique identifier for the application. Because UIDs are fundamental to Symbian, it is important that they are used correctly when developing programs. To ensure uniqueness, it is essential that UIDs are properly allocated. Uniqueness is guaranteed by managing allocation centrally from a single database. All UIDs must therefore be assigned to users by a central allocating authority. The only exception to this rule a reserved range of values which may be used as UIDs by developers during development but which must not be used in released software. During development temporary UIDs may be chosen from the range 0x01000000 to 0x0fffffff. Care must still be taken to avoid clashes within development teams and between multiple projects, including old projects which may be installed on emulator or native platforms. UID clashes may stop a program from loading correctly, typically leading to Not Found errors. Developers can request UIDs either individually or in pre-allocated blocks by e-mail to [email protected]. Including Booster In SIS Files Choosing to include Booster in a Nokia Series 80 device package means that when the ’Save Project Pacakge...’ option is selected from the MobileVB window the SIS file (Symbian OS package) that is created will include Booster. This allows the creation of a package with the required Booster so that end 248 users will not have to download Booster from the AppForge website. This option however only applies to packages created with the ’Save Project Pacakge...’ option if instead you choose the ’Deploy To Device’ option Booster will not be uploaded to the device. Setting Compiler Settings Basic Settings Tab By default, the MobileVB™ compiler prevents applications from being compiled for devices that do not support all of the associated references. For example, if a Palm application contains a reference to the Palm OS Extended Functions Library, you will be unable to compile that application for Pocket PC because that library is unsupported on Pocket PC devices. If necessary, you can turn off this check when compiling your project. But use caution when doing this. If calls are made in your code to a library that is not supported on the current device, your application will crash. To turn off this check select Compiler Settings in MobileVB Settings. Check the box next to "Turn off reference checking during compilation." In order to prevent your application from crashing, you must detect what type of device the application is running on during runtime. One way to do this is to use the screen width to determine the runtime device. The example provided below shows how this can be done. Run before any device specific code in SubMain this code snippet finds out the screen width of the current device and stores the current device in a boolean. Then every time you make a call to the library in question, you make sure you are running on a device that can support the library. ’Constants for the default form sizes of each platform Private Const L_PPC_FORM_W As Long = 240 Private Const L_PALM_FORM_W As Long = 160 Public bRunningOnPocketPC as Boolean Public Sub Main () #If APPFORGE Then ’Only perform the resize on a device, not under Visual Basic. If Screen.Width > L_PALM_FORM_W Then ’If on Pocket PC... bRunningOnPocketPC = True End If #End If End Sub Private Sub showGraffitiShiftIndicator () 249 If bRunningOnPocketPC = False then GraffitiShiftIndicatorInitialize GraffitiShiftIndicatorEnable (True) GraffitiShiftIndicatorSetLocation 135, 150 End If End Sub Figure 66: AppForge Compiler Settings Pre and Post Build Steps Tab The compiler settings section provides two additional tabs that allow the selection of Pre and Post build steps. Both tabs provide the same interface with the ability to add, remove, and arrange the order of programs that are run. The programs specified are run directly before (Pre Build) or after (Post Build) your project is compiled. 250 Figure 67: Pre Build Step Selection Setting My Devices Several menu items in the MobileVB menu have a To My Devices selection. The devices checked in the My Devices section will be used when any To My Devices menu item is selected. 251 Figure 68: My Devices Settings 11.6 Install Booster To Device The AppForge Booster is a "virtual machine" that enables MobileVB™ applications to run in Palm OS® , Pocket PC, or Nokia Series 9200 Communicator devices. The Install Booster on Device option in the MobileVB Add-In Menu prepares the Booster for installation on your handheld device. 252 Figure 69: Selecting Install Booster on Device In Palm OS® , selecting this option copies the Booster (BOOSTER.PRC) into the specified user’s Palm Install directory. During the next HotSync™ operation, the Booster will be uploaded to the Palm OS device. If more than one user is set up to use the Palm Desktop software, a window will prompt you to select a user to receive Booster. Once Booster has been copied, a window will appear indicating Booster will be loaded on your next HotSync operation. To install Booster on a Pocket PC device, the device must be connected to the desktop computer via Microsoft® ActiveSync® . MobileVB™ sends Booster directly to the device, which then installs it. (If Booster has been installed already, the device will prompt you to re-install it.) Figure 70: Palm OS: Selecting a User for Booster Installation 253 Figure 71: Palm OS: Booster Will Be Loaded In the Next HotSync In Palm OS® , after the next HotSync® operation, Booster will appear in the main applications area. In Pocket PC, Booster resides in the My Device\Program Files\AppForge directory. Booster support for individual device types is installed separately. If you do not have Booster support installed for your device, you will be prompted to download it from http://www.appforge.com/booster.html . Figure 72: Palm OS: Booster in the Main Applications Area Note: Booster is required to run MobileVB™ applications on a handheld device. 11.7 Open MobileVB Project This menu item launches the MobileVB Project Manager. The Project Manager allows you to create a new project or start a new one. If you have a project open when the menu Open MobileVB Project is selected, you will be prompted to save the current project before the Project Manager is launched. Selecting cancel when prompted will cancel the launch of the Project manager. 254 Figure 73: The MobileVB Project Manager 11.8 Zoom Window The Zoom Window magnifies the view of a project. This makes it easier to modify forms on highresolution monitors. 255 Figure 74: Opening the Zoom Window 11.9 MobileVB Messages Window Select this menu option to open the MobileVB™ Messages Window. It contains the messages from the most recent compile for the current project. Additional details on the MobileVB Messages Window, see theCompile and Validate section. Figure 75: MobileVB Messages Window 256 11.10 MobileVB User’s Guide The AppForge MobileVB™ User’s Guide is designed to help you get the most out of MobileVB™ . Select this menu option to open it. 11.11 AppForge Utilities MobileVB™ includes several utilities for programmers. Figure 76: Opening the Converters and Viewers Menu See the MobileVB™ Project Converter Guide , MobileVB™ File Converters and Viewers Guide andAppForge Universal Conduit Guide for more information. 11.12 Samples and Tutorials MobileVB provides a set of tutorials and sample applications. For details on the sample applications, see theAppForge MobileVB Samples documentation. 257 11.13 AppForge on the Web The MobileVB Support Website at http://support.appforge.com features a detailed Knowledge Base and an area to submit technical questions. 258 12 AppForge Data Storage 12.1 Introduction AppForge Data Storage features a set of libraries that provide access to databases on handheld devices within the AppForge framework. Data storage support consists of a generic database library, a PDB (Palm database) library, and a set of administration libraries specific to each supported database. The generic database object model is designed to be a fast and lightweight cross-platform, cross-database solution. It contains the basic functionality that most data access applications will need, but excludes some heavyweight features that are less commonly available with database solutions for portable devices. The PDB library contains a non-object oriented set of APIs for accessing PDBs Database Library Features • Provides a generic method for opening connections to different types of data sources. • Allows the experienced database programmer to execute any SQL statements supported by the database provider. • Includes both read-only and write access to data through the concept of read-only and writeable recordsets. • Supports SQL Server CE on Windows CE and Pocket PC devices. • Supports Pocket Access. Database Object Model Summary • IDBAccessManager. The only object creatable with the New keyword. Allows the programmer to open a connection to a particular data source. • IConnection. Represents a connection to a data source. Contains methods to execute SQL statements and to open recordsets. • IReadableRecordset. Represents a read-only view of data. This recordset only contains methods to retrieve data and information about the fields in the recordset. • IUpdatableRecordset. The updatable recordset contains all the functionality of the readable recordset, plus functions to update existing records. Note that there is no method on the IConnection object that returns an object of this type. This object definition is a placeholder for future functionality. • IWritableRecordset. The writable recordset encapsulates all the functionality of the updatable recordset and includes methods for adding and deleting records. 259 PDB Library Features • Provides easy access to the functionality of Palm databases. • Stores schema information for a PDB, allowing records to be written on a field by field basis. • Includes support for PDBs on Windows CE. The same PDB file can be copied from the desktop to both Palm and Windows CE devices. 12.2 Using the Database Model Overview The following are the basic steps for performing common database access operations 1. Create a database access manager object. 2. Open a connection from the access manager. 3. Execute a SQL statement on the connection, or: 4. Open a read-only recordset, or: 5. Open a writable recordset. 6. Move through the opened recordset, retrieving and/or modifying data. Creating the Database Access Manager The database access manager object is the only object that can be created using the New keyword. All other objects must be created through methods of the access manager and through methods of objects the access manager creates. Example Dim mgr As AFDatabaseLib.CDBAccessManager Set mgr = New AFDatabaseLib.CDBAccessManager or: Dim mgr As New AFDatabaseLib.CDBAccessManager The access manager’s sole purpose is to provide a means to connect to various data sources, which will be discussed in the next section "Opening a Connection." 260 Opening a Connection The OpenConnection method of the access manager object opens a connection to a data source and creates a connection object. The first parameter of OpenConnection indicates the type of data source to which the connection is being made. The second parameter is a custom string containing connection parameters specific to the database to which the connection is being made. The format of this string is dependent upon the type of database to which a connection is being made. Example Dim mgr As AFDatabaseLib.CDBAccessManager Dim conn As AFDatabaseLib.IConnection ’ Create a connection to a SQL Server CE database Set mgr = New AFDatabaseLib.CDBAccessManager Set conn = mgr.OpenConnection("SQLCE", _ "Data Source=\Data\database.sdf") Executing a SQL Statement Once a connection is opened, the connection object’s ExecuteStatement method may be used to execute SQL statements on that connection. The ExecuteStatement method returns a count of the number of records affected by the execution of the statement. SQL statements can be used to add records, update records, delete records, and modify the schema of your database, among other things. Refer to your database documentation for the syntax of SQL statements supported by your database engine. Example Dim mgr As AFDatabaseLib.CDBAccessManager Dim conn As AFDatabaseLib.IConnection Dim RecordsAffected As Long Set mgr = New AFDatabaseLib.CDBAccessManager Set conn = mgr.OpenConnection("SQLCE", _ "Data Source=\Data\database.sdf") RecordsAffected = conn.ExecuteStatement( _ "delete from contacts where age < 25") 261 Read-Only, Updatable, and Writable Recordsets The AppForge database model divides recordset types into three categories based on the purpose of the recordset: reading data, modifying existing records, and adding and deleting records. As the name suggests, read-only recordsets only provide methods for retrieving field data and metadata. In the current release, read-only recordsets are the only recordsets that can be opened using SQL queries. Read-Only Recordset Method Summary Method Close FieldIndex MoveFirst MoveLast MoveNext MovePrevious ReadRecord Description Closes the recordset Determines the ordinal number of a field from the field name Move to the first record in the recordset Move to the last record in the recordset Move to the next record in the recordset Move to the previous record in the recordset Reads all the fields from a particular record into a user defined type. The number, type, and order of fields in the user-defined type must exactly match the number, type, and order of fields in the recordset Read-Only Recordset Property Summary Property BOF EOF FieldAsBoolean FieldAsByte FieldAsCurrency FieldAsDate FieldAsDouble FieldAsInteger FieldAsLong FieldAsSingle FieldAsString FieldCount FieldIsNull FieldName FieldSize FieldType RecordCount Description This property is True if the recordset cursor has moved before the first record in the recordset This property is True if the recordset cursor has moved after the last record in the recordset Retrieves the value of a Boolean-type field Retrieves the value of a Byte-type field Retrieves the value of a Currency-type field Retrieves the value of a Date-type field Retrieves the value of a Double-type field Retrieves the value of an Integer-type field Retrieves the value of a Long-type field Retrieves the value of a Single-type field Retrieves the value of a String-type field Retrieves a total count of fields in the recordset This property is True if a particular field is null Retrieves the name of a field Retrieves the size of a field Retrieves the type of a field Retrieves a total count of records in the recordset. Note that not all recordsets will support this property, and may return a value of -1 262 Updatable recordsets contain all the functionality of read-only recordsets, but also include methods for updating the values of fields in existing records. Note that in the current release, the connection object does not provide a method for creating an instance of an updatable recordset object. Updatable Recordset Method Summary Method SetFieldNull Update WriteRecord Description Sets a field to a null value Writes changes made to a particular record Write the values contained in a user-defined type to a record. As with ReadRecord, the number, type, and order of fields in the user-defined type must exactly match the number, type, and order of fields in the recordset Writable recordsets contain all the functionality of updatable recordsets, but also include methods to add and delete records. Writable Recordset Method Summary Method AddNew AddRecord Delete Description Begins the process of adding a new record to the recordset Adds a new record and writes the values from a user-defined type to that record. As with ReadRecord and WriteRecord, the number, type, and order of fields in the user-defined type must exactly match the number, type, and order of fields in the recordset Deletes a record from the recordset Example Dim Dim Dim Dim mgr As AFDatabaseLib.CDBAccessManager conn As AFDatabaseLib.IConnection rs As AFDatabaseLib.IReadableRecordset tbl As AFDatabaseLib.IWritableRecordset Set mgr = New AFDatabaseLib.CDBAccessManager Set conn = mgr.OpenConnection("SQLCE", _ "Data Source=\Data\database.sdf") Set rs = conn.OpenReadOnlyRecordset( _ "select * from contacts") Set tbl = conn.OpenTable("contacts") Note that in the above sample, two recordsets were opened on the same table. Some databases may not 263 allow two recordsets on a single table to be open at the same time. Field Properties of Recordsets Field data in all recordsets is read and written using the FieldAs<type> properties. In the interest of speed and efficiency, these properties require the programmer to know the number and kind of fields present in the database. The ordinal of a field is passed to the Property Get method of the appropriate type, with field numbers starting at zero. Consider the following example below: Dim mgr As AFDatabaseLib.CDBAccessManager Dim conn As AFDatabaseLib.IConnection Dim rs As AFDatabaseLib.IReadableRecordset Set mgr = New AFDatabaseLib.CDBAccessManager Set conn = mgr.OpenConnection("SQLCE", _ "Data Source=\Data\database.sdf") Set rs = conn.OpenReadOnlyRecordset( _ "select name, birthday from contacts") rs.MoveFirst Debug.Print rs.FieldAsString(0) Debug.Print rs.FieldAsDate(1) rs.Close conn.Close In this example the fields "name" and "birthday" were selected from the table contacts. The first field in the recordset, "name", is at index zero and is of type String. Consequently the FieldAsString property with a field index of zero is used to retrieve the value of the name field. The second field, "birthday" is of type Date. The FieldAsDate property with a field index of one is used to retrieve the value of the birthday field. Using the field properties to write values to a record works in the same manner. In the example below, The name and birthday of the first contact record are updated with new values. Dim mgr As AFDatabaseLib.CDBAccessManager Dim conn As AFDatabaseLib.IConnection Dim tbl As AFDatabaseLib.IWritableRecordset Set mgr = New AFDatabaseLib.CDBAccessManager Set conn = mgr.OpenConnection("SQLCE", _ "Data Source=\Data\database.sdf") Set tbl = conn.OpenTable("contacts") 264 tbl.MoveFirst tbl.FieldAsString(0) = "George P. Burdell" tbl.FieldAsDate(1) = CDate("September 1, 1912 ") tbl.Update tbl.Close conn.Close In order for this example to work, the first two fields defined in the contacts table schema must be of type String and Date. The first field is assigned a new String value, while the second field is assigned a Date value. The Update method writes changes made to fields to the record. Note that when using String literals to assign values to non-String fields, the MobileVB™ compiler may require the use of a type conversion function like CDate. The Database Library and ADO ADO programmers will find that many of the AppForge database objects are very familiar. In general, the AppForge database library is very similar to ADO, with a few differences: 1. Instead of one monolithic recordset that contains all the functionality that you might need when opening a recordset, there are read-only and writable recordsets. When you open a recordset, you must know at the time you are opening it whether you want to open it for read-only or for read/write access. 2. The AppForge model forces you to be more aware of the types and positions of the fields in your recordset. There is no Fields collection, and field values are not retrieved as Variants. The AppForge field properties are strongly typed to minimize the amount of unnecessary data conversion and memory usage. 12.3 Using the Database Model with SQL Server CE Introduction SQL Server CE is an extension of SQL Server for Windows CE devices. Although the runtime can be used to create stand-alone database on the device, typically a subset of the tables and data from databases on a SQL Server are replicated to a device. Devices can transfer data to and from a server by using RDA or by synchronizing with the server through a PC running the SSCERelay utility. For more information on replication and remote data access, refer to your SQL Server CE documentation or to the SQL Server CEwebsite . There is also an excellentwhite paper about security models using SQL Server CE. SQL Server CE comes with a useful utility called ISQLCE. This program is something like the SQL Server 2000 Query Analyzer application, scaled down to run on the device. You can use it to create 265 and connect to databases, execute SQL statements, and view query results in a tabular format. The tool returns detailed error information when there are syntax errors or other problems with queries, and can be very useful for testing ideas on the device. Once you have created a query that works, you can save it on the device and then use the Active Sync File Explorer to copy it back to the desktop. (Note that the saved file will be a Unicode file, so you will need a text editor that is capable of reading wide characters. On Windows 2000, Notepad is sufficient.) Database Files On the device, a SQL Server CE database is stored as a single file with the extension .sdf, one database to a file. There are no tools that allow you to modify these databases on the desktop, which limits the options available for creating databases that you wish to distribute with your application. Databases can be created on the device in two ways: by using replication to create a device copy of a server’s publication, or by using the CreateDatabase method of the SQL CE administration object, described in a section below. If you use the CreateDatabase method to create a database from scratch, the resulting database will be empty, and you will need to use a series of SQL statements to create the appropriate tables for your new database. As data is added and deleted over time, a database may become fragmented and will take up more space than is necessary. This bloated database may be compacted using the CompactSQLDatabase method. The compacted version of the database is written to a separate file, leaving the original database unchanged. Connection Strings To connect to a SQL Server CE database, the first input parameter of the OpenConnection method should be "SQLCE". This string will cause the database access manager to interpret the second string as a SQL Server CE OLEDB connection string. This connection string may contain any of three properties: • Data Source. The complete path to the database file. • SSCE:Database Password. The password to the database file. • SSCE:Encrypt Database. "True" if the database file is encrypted, otherwise "False". Some Examples: Dim mgr As New CDBAccessManager Dim conn As IConnection ’ Connect to an unencrypted database that has no password set conn = mgr.OpenConnection("SQLCE", _ 266 "Data Source=\Data\database.sdf") ’ Connect to an unencrypted database with a password set conn = mgr.OpenConnection("SQLCE", _ "Data Source=\Data\database.sdf;SSCE:Database" _ & " Password=password;" ’ Connect to an encrypted database with a password set conn = mgr.OpenConnection("SQLCE", _ "Data Source=\Data\database.sdf;SSCE:Database" _ & " Password=password;SSCE:Encrypt Database=True;" Note that the Data Source property is mandatory in any connection string. Working in Hosted Mode versus Running on the Device When you are debugging your application in Visual Basic on your PC, you will not be able to test with the actual SQL Server CE database that will be present on the device. It is recommended that you test with an identical database located on a SQL Server on your local network or on your local machine. With SQL Server 2000, making a connection requires that you install a number of client connectivity tools on your development machine. See your SQL Server documentation for more information on connecting to a SQL Server. When connecting to a SQL Server from your PC, the connection string that should be used in the OpenConnection method of the database access manager will be drastically different from the connection string used on the device. This connection string will have the same format as the string you would use to connect to a SQL Server using ADO, minus the Provider property. Provider information is provided with the first parameter of the OpenConnection method. See your SQL Server documentation for more information on the format of SQL Server connection strings. Programmer’s Notes • You can have only one open connection to a SQL Server CE database at a time, and this connection must be closed before invoking replication. • Fields of type rowguid are interpreted as String fields and are read-only. • SQL Server CE does not support dynamic read-only cursors. Consequently the staticset parameter of the connection object’s OpenReadOnlyRecordset method is meaningless under SQL Server CE. All read-only recordsets are static. • Similarly, SQL Server CE does not support static read/write recordsets or forward-only read/write recordsets. As a result the forwardonly and staticset parameters of the connection object’s OpenTable method are both meaningless under SQL Server CE. 267 • String fields within a SQL Server CE database are limited to 254 characters. Synchronization Options SQL Server CE provides you with two synchronization methods: replication and RDA (remote data access). RDA allows you to push a discrete set of records from the device to a SQL Server, or to pull a set of records from the SQL Server to the device. Replication is a more complete reconciliation of the data set that exists on the device with the data set that exists on teh server. Both of these methods allow you to use Web protocols to communicate wirelessly with a SQL Server. Refer to the following excerpt from the SQL Server CE Books Online about connectivity: SQL Server CE RDA and replication are optimized for wireless communication. They automatically compress data to minimize the amount of data sent over the wireless network. They can be configured to use encryption to safeguard user data propagated between the SQL Server CE and SQL Server. Data is propagated between the Windows CE device and the server by using a simple protocol patterned after file transfer protocols. SQL Server CE RDA and replication recover from communication failures by restarting from the last successfully transmitted block of data. This makes synchronization possible even if the underlying transport is not reliable. SQL Server CE RDA and replication are primarily intended for Windows CE devices that are occasionally connected to the network. However, it is also useful for Windows CE devices that are consistently connected. (end excerpt) AppForge provides a thin wrapper for Microsoft’s ActiveX replication object and RDA object so that they may be used in MobileVB™ projects. For the most part, methods and properties in these wrappers directly correspond to the methods and properties provided by the ActiveX objects. For more information, refer to your SQL Server CE documentation. Notes: • The use of replication requires that you synchronize your devices with a SQL Server 2000 server. The native database format used in SQL Server 2000 and in SQL Server CE differs significantly from the format used in previous versions of SQL Server. Because replication is dealing intimately with the contents of tables and individual records, this difference precludes the use of replication to Windows CE devices with SQL Server 7.0. RDA, however, can be used with both SQL Server 7.0 and SQL Server 6.5. • The synchronization methods described above allow you to synchronize with SQL Server database servers only. You cannot directly synchronize devices running SQL Server CE with other database servers. A number of third-party products exist, however, to perform more flexible synchronization operations. • There is no desktop equivalent of the AppForge SQL Server CE synchronization support. This 268 means that you cannot meaningfully debug your synchronization code in Visual Basic. The PC version of all the synchronization functions will return success, but at the same time will not actually perform any actions. Data Types SQL Server bigint binary bit char* datetime decimal* float image int money nchar ntext numeric nvarchar real smalldatetime* smallint smallmoney* sql_variant* sysname text* timestamp* tinyint uniqueidentifier varbinary varchar* OLE DB DBTYPE_I8 DBTYPE_BYTES DBTYPE_BOOL DBTYPE_STR DBTYPE_DBTIMESTAMP DBTYPE_NUMERIC DBTYPE_R8 DBTYPE_BYTES DBTYPE_I4 DBTYPE_CY DBTYPE_WSTR DBTYPE_WSTR DBTYPE_NUMERIC DBTYPE_WSTR DBTYPE_R4 DBTYPE_DBTIMESTAMP DBTYPE_I2 DBTYPE_CY DBTYPE_VARIANT DBTYPE_WSTR DBTYPE_STR DBTYPE_BYTES DBTYPE_UI1 DBTYPE_GUID DBTYPE_BYTES DBTYPE_STR AppForge Conformant Long Not Supported Boolean String Date Not Supported Double Not Supported Long Currency String String Not Supported String Single Date Integer Currency Not Supported String String Not Supported Byte String (read-only) Not Supported Not Supported AppForge Native S32 Not Supported BOOL32 IString IDateTime Not Supported FLOAT64 Not Supported S32 CURRENCY64 IString IString Not Supported IString FLOAT32 IDateTime S16 CURRENCY64 Not Supported IString IString Not Supported U08 IString (read-only) Not Supported Not Supported * indicates that this type is not supported on SQL Server CE SQL Server CE Administration Library Reference TheAppForge SQLCE Administration Library contains database manipulation and synchronization functionality that are specific to SQL Server CE. 269 12.4 Using the Database Model with Pocket Access Introduction Pocket Access is the database format native to Windows CE devices. Database Files Pocket Access uses the notion of database volumes to describe database files. Each .cdb file is a separate database volume that can contain multiple tables. Pocket PC devices also contain a default database volume that contains PIM data and some system information. This default volume does not reside in a .cdb file, but you can browse its contents using the Mobile Device explorer that comes with ActiveSync. There will be a folder named "Databases" under "My Pocket PC" that contains all the tables residing in the default database volume. In order for Pocket Access databases to be accessible by ADOCE and by ActiveSync’s synchronization capabilities, they must contain a number of tables that store schema information about the database. If you create a database using AppForge’s database administration library, ADOCE, or by synchronizing an ODBC data source with ActiveSync, the new database will contain sufficient schema information. If, however, you are attempting to open a database that was not created through any of those three methods, attempting to open that database may generate a runtime error. Note also that the schema table requirement prevents you from opening databases that reside on the default database volume, as this volume does not contain schema information. Connection Strings Connection strings for Pocket Access databases need only include the fuly qualified path to the database file which should be opened. Pocket Access databases do not provide password or encryption facilities, so there is no need to specify extra properties listing these parameters. Similarly, when debugging your appliction through Visual Basic, you should specify the entire path to the Microsoft Access database you are using for testing purposes. Some Examples: Dim mgr As New CDBAccessManager Dim conn As IConnection ’ Connect to a database on the device Set conn = mgr.OpenConnection("CEDB", "\Data\database.cdb") ’ Connect to a database on the PC Set conn = mgr.OpenConnection("CEDB", "C:\Data\database.mdb") 270 Working in Hosted Mode versus Running on the Device When you are debugging your Pocket Access application using Visual Basic, the database library will emulate a database on the device using a Microsoft Access database. For best results with this emulation, it is recommended that you have the Jet 4.0 OLE DB provider installed on your system. The Pocket Access emulation is designed to also work with Jet 3.5, but has not yet been fully tested with this version of Jet. You can determine whether you have the latest version of the Jet provider installed by checking for the existence of msjetoledb40.dll in your system directory or in your Program Files directory under Common Files. If you do not have the provider installed, you candownload it from Microsoft’s universal data access web site. Note that in order to connect to an Access database on your PC, you will need to specify the full path to the .mdb file containing your database. The emulation will not translate the .cdb extension to a .mdb extension. Programmer’s Notes • Pocket Access does not natively support SQL statements. ADOCE provides its own SQL parser so that you can write SQL statements with ADOCE, but AppForge’s lightweight implementation does not attempt to duplicate such functionality. If you attempt to use the Execute or OpenReadOnlyRecordset methods of the connection object, you will receive errors indicating that the object doesn’t support those methods. • The forwardonly and staticset parameters of the OpenTable method of the connection object have no meaning with Pocket Access databases. All table recordsets are bi-directional dynamic sets. • You cannot open the default database store because it does not contain schema information. Synchronization Options ActiveSync allows you to synchronize any ODBC data source or Microsoft Access database with a Pocket Access database on your device. Note that if you are synchronizing with a non-Access database that contains irregular data types, it is possible that some loss of data may occur when those data types are translated to Pocket Access data types. Data Types Note that the native Pocket Access data types do not include a type that directly corresponds to the AppForge Byte, Single, and Currency types. If you attempt to create a table with fields that are set to any of these three types, those fields will automatically be created with the appropriate native Pocket Access types. For example, if you attempt to create a Byte field, the FieldType property of a recordset on the table containing this field will return Integer, as this is the closest matching native Pocket Access type. 271 This behavior may cause problems at run-time if you are using any of the ReadRecord, WriteRecord, or AddRecord methods. Continuing the example above, let us assume that you have created a table with a "Byte" field and that you now intend to call ReadRecord on that table. Because the AppForge runtime allocates one byte of storage in a record structure for a Byte field, and two bytes of storage for an Integer field, it is important that in the user-defined type used to read records from this table, the "Byte" field is actually declared as an Integer. If it is declared as a Byte, alignment errors will occur because the database library believes the field values to be Integers. Any of the three record methods are subject to this error. To avoid this error, when writing to a Pocket Access database use Integer fields whereever you would normally use Byte fields. Similarly, use Double fields whereever you would use Single or Currency fields. ODBC Pocket Access AppForge Native CEVT_R8 CEVT_BLOB CEVT_BOOL CEVT_LPWSTR CEVT_FILETIME CEVT_R8 CEVT_R8 CEVT_R8 Unsupported CEVT_I4 CEVT_FILETIME CEVT_BLOB CEVT_LPWSTR CEVT_R8 CEVT_I2 AppForge Conformant Long Unsupported Boolean String Date Double Double Double Unsupported Long Date Unsupported String Double Integer SQL_BIGINT SQL_BINARY SQL_BIT SQL_CHAR SQL_DATE SQL_DECIMAL SQL_DOUBLE SQL_FLOAT SQL_GUID SQL_INTEGER SQL_INTERVAL SQL_LONGVARBINARY SQL_LONGVARCHAR SQL_REAL SQL_SMALLINT, SQL_TINYINT SQL_TIME SQL_TIMESTAMP SQL_VARBINARY SQL_VARCHAR CEVT_FILETIME CEVT_FILETIME CEVT_BLOB CEVT_LPWSTR Date Date Unsupported String IDateTime IDateTime Unsupported IString S32 Unsupported BOOL32 IString IDateTime FLOAT64 FLOAT64 FLOAT64 Unsupported S32 IDateTime Unsupported String FLOAT64 S16 Pocket Access Administration Library Reference TheAppForge Pocket Access Administration Library contains database manipulation functionality that is specific to Pocket Access databases. 272 12.5 Using the Database Model with Symbian OS Databases Introduction The Symbian operating system ships with a very feature-rich database implementation. Database Files Symbian OS database files can be created using the CreateDatabase function of the Symbian OS database administration library. Although Symbian OS provides a mechanism for storing several different databases in a single file, for simplicity’s sake the AppForge database library restricts you to one database per file. If you create a database on your PC using the Nokia 9200 Series emulator, this database file can be downloaded directly from the PC to the device, with no conversion. In the same way, if you create a database on the device, you can copy it to your desktop and use it in the emulator. Note that this is for the Nokia emulator only; if you are debugging using VB, the database created will be an Access database so that the average VB developer is not required to have a Symbian SDK or emulator installed. Connection Strings Connection strings for Symbian OS databases contain a series of property definitions. Each property definition consists of a property name, followed by an equals sign ("="), followed by the property value. Each property definition is separated by a semicolon. (This format is also used by OLE DB connection strings.) Three properties may be used in a connection string: • Data Source . The complete path to the database file. Note that this property is mandatory for a valid connection string. • Exclusive . Determines whether the database will be opened for exclusive access. Possible values for this property are "True" and "False". If this property is False, then the Symbian named database server will be used to open the database, allowing shared read and write access. The default value for this parameter is "True". • Password . An encryption password for the database. If a password is provided, the database will be encrypted using the provided password as a key. Examples: Dim mgr As New CDBAccessManager Dim conn As IConnection 273 ’ Connect to an unencrypted database exclusively Set conn = mgr.OpenConnection("SYMBIANOS", _ & "Data Source=c:\system\apps\Database\database.db") ’ Connect to an unencrypted database for shared access Set conn = mgr.OpenConnection("SYMBIANOS", _ & "Data Source=c:\system\apps\Database\database.db;Exclusive=False") ’ Connect to an encrypted database exclusively Set conn = mgr.OpenConnection("SYMBIANOS", _ & "Data Source=c:\system\apps\Database\database.db;Password=password") ’ Connect to an encrypted database for shared access Set conn = mgr.OpenConnection("SYMBIANOS", _ & "Data Source=c:\system\apps\Database\database.db;Exclusive=False" _ & ";Password=password" Working in Hosted Mode versus Running on the Device If you are using Visual Basic as your primary emulation environment, Symbian OS databases are emulated using Microsoft Access. For the most part the capabilities of the two databases are comparable, however if you are using SQL statements to create tables, you may encounter some slight differences in the keywords used by the two databases. For example, you if you want to create a table with a field whose type is the Symbian OS VARCHAR, you will have to use a code snippet similar to the following: Dim mgr As New CDBAccessManager Dim conn as IConnection Set conn = mgr.OpenConnection("SYMBIANOS", "Data Source=" _ & "c:\system\apps\myapp\test.db") #If APPFORGE Then ’ Use Symbian syntax to create the table conn.ExecuteStatement "CREATE TABLE myTable (intField INTEGER, " _ & "stringField VARCHAR(30))" #Else ’ Use Access syntax to create the table conn.ExecuteStatement "CREATE TABLE myTable (intField INTEGER, " _ & "stringField CHAR(30))" #End If It is also possible to test your application using the Nokia 9200 Series emulator. In this case, the database created will be in the native Symbain format, and it will behave exactly as you would expect the database 274 to behave on the device. When an application is compiled for the emulator, the APPFORGE compiler definition is still defined, so the above code snippet does not need to be changed. Programmer’s Notes • The Symbian OS SQL language requires that date literals be surrounded by the pound ("#") character. If you do not surround date literals with this character, you will have syntax errors in your SQL statement. Synchronization Options Most devices with Symbian OS come with support for synchronizing PIM data, but there is currently no personal synchronization solution for generic databases. Data Types Symbian OS EDbColBinary EDbColBit EDbColDateTime EDbColInt8 EDbColInt16 EDbColInt32 EDbColInt64 EDbColLongBinary EDbColLongText EDbColLongText8 EDbColLongText16 EDbColReal32 EDbColReal64 EDbColText EDbColText8 EDbColText16 EDbColUint8 EDbColUint16 EDbColUint32 AppForge Conformant Unsupported Boolean Date Byte Integer Long Long Unsupported Unsupported Unsupported Unsupported Single Double String String String Byte Integer Long 275 AppForge Native Unsupported BOOL32 IDateTime S08 Long S32 S32 Unsupported Unsupported Unsupported Unsupported FLOAT32 FLOAT64 IString IString IString S08 S16 S32 Symbian OS Database Administration Library Reference TheAppForge Symbian OS Database Administration Library contains database manipulation functionality that is specific to Symbian OS databases. 12.6 Using the Database Model with PDBs Introduction The database library includes support for accessing Palm databases (PDBs). PDBs are the only database type that is supported on all platforms, and they are the simplest choice if you are looking for a completely cross-platform solution. The tradeoff comes in the speed and efficiency of the database itself, however. PDBs do not include support for SQL queries, and accessing them through the database library is slower than using the AppForge PDB library. Database Files A Palm "database" is stored in a file with the extension ".pdb". Each PDB file actually contains one table, rather than a set of related tables. Connection Strings Since there is no central database file, connection strings for PDBs are very simple: they should be empty. On all platforms, a connection for opening PDB recordsets can be created in the following manner: Dim mgr as CDBAccessManager Dim conn as IConnection Set mgr = new CDBAccessManager Set conn = mgr.OpenConnection("PDB", "") In order to open a Recordset, call OpenTable() with the name of the PDB to be opened. ’ Here we open a PDB named "MyPDB" Dim rs As IWritableRecordset set rs = conn.OpenTable("MyPDB") 276 Working in Hosted Mode versus Running on the Device AppForge provides an implementation of PDBs for the desktop, and as a result applications that are using PDBs for data access will function in more or less the same manner. The only functional difference between the two environments is that on the device, PDBs must be in the same directory as your application, while on the desktop, PDBs may be located anywhere. If you are using PDBs on the desktop and they are not located in your application directory, be sure to specify the path to the PDB files as part of the table name parameter in the OpenTable method of the PDB connection. This path may be a fully qualified or a relative path. Programmer’s Notes • As with Pocket Access, PDBs do not support SQL statements. • Read-only recordsets are not supported on PDBs. Synchronization Options If you are using PDBs on Palm OS devices, the AppForge Universal Conduit provides a complete synchronization solution for most databases. If you are using PDBs on other platforms, you will probably need to write your own application to extract the information from the PDB. 12.7 The Database Library vs. the PDB Library This section attempts to give PDB programmers a head start on adjusting to the differences between the AppForge database model and the AppForge PDB library. Tables versus Databases The concept of a PDB "database" roughly corresponds to the notion of a table in the new database model. A table is a set of records or rows, each of which contains a number of related data fields. A PDB database effectively contains only one table. The AppForge database model is intended for use with more traditional databases, which can contain a number of tables that may or may not be related to each other in some way. Retrieving Data The AppForge database library provides two methods for retrieving data. The first method is direct table access, which is very much like the PDB library in that a single table is opened as for direct read/write 277 access. To open a table for direct access, you need to open a connection, then use the OpenTable method to get a recordset that allows read/write access. It is important to note, however, that data in tables cannot be sorted or filtered when they are retrieved through this method. To sort and filter data, you must use the SQL query language to open a recordset. A recordset can be thought of as a temporary table that contains a subset of information from one or more tables. The SQL query language can be used to specify which fields from which tables the user wishes to retrieve, and how multiple tables relate to each other in a single query. A query may also contain clauses that filter, order, and group the data retrieved. A complete SQL language reference is beyond the scope of this document; please see your database server documentation. To open a recordset, the user must open a connection, then pass a query string to the OpenReadOnlyRecordset method of the connection. As the name implies, recordsets opened through SQL queries are read-only. If you need to modify existing data or insert records, you will need to open a table or use SQL statements that modify data. Modifying Data The database library allows users to modify data both through SQL statements and through methods on the recordset object. The ExecuteStatement method of the connection object may be used to execute SQL statements that add, modify, or delete data from the database. A recordset obtained though the OpenTable method also exposes a number of methods that allow data in the reocrdset to be modified. To update field values, use the FieldAs<type> properties, and commit your changes using the Update method. To add a new record, use AddRecord or AddNew followed by setting field properties followed by the Update method. To delete a record, use the Delete method, which does not require calling the Update method. PDB Function Counterparts Function PDBBOF PDBBulkRead PDBCancelRecordEdit PDBClose PDBCreateDatabase PDBCreateDBUniqueNumber PDBCreateRecord PDBCreateRecordBySchema Analogous Function/Process Recordset’s BOF property No analogue No analogue; moving to another record without calling Update effectively cancels an edit Recordset’s Close method Database dependent; for SQLCE use the CreateSQLDatabase method of CSQLAdmin No analogue; in general the database you are working with will provide unique identifiers for you Recordset’s AddNew or AddRecord methods, or the appropriate SQL statement Recordset’s AddNew or AddRecord methods, or the appropriate SQL statement 278 PDBCreateTable PDBCurrentIndex PDBDeleteDatabase PDBDeleteRecord, PDBDeleteRecordEx PDBEditRecord PDBEOF PDBFindRecordByField, PDBFindRecordByID PDBGetCategoryName PDBGetDatabaseAttributes PDBGetField, PDBGetFieldbyOffset PDBGetLastError PDBGetNumFields PDBGetSortFields PDBGotoIndex PDBMoveFirst PDBMoveLast PDBMoveNext PDBMovePrev PDBNumRecords PDBOpen PDBReadRecord PDBRecordAttributes, PDBRecordAttributesEx PDBRecordCategoryID PDBRecordSize Use the connection object’s ExecuteStatement method with a SQL statement that creates a table Database and recordset type dependent; with some databases and on some recordsets the field at index -1 is a unique record identifier or bookmark. Entire databases cannot be deleted through the AppForge database library. Tables can be deleted however, by using the connection object’s ExecuteStatement method with the appropriate SQL statement. The recordset’s Delete method, or the appropriate SQL statement No analogue; editing begins as soon as a particular field is set Recordset’s EOF property No analogue. Once a recordset is open, there is no way to seek for a particular record. You can, however, use a SQL query to open a recordset that includes only one or a few records. No analogue No analogue Recordset’s FieldAs<type> property. Fields must be retrieved using the property that corresponds to their data types, else a type mismatch may occur. No analogue; use On Error statements to catch errors thrown by the database library Recordset’s FieldCount property No analogue No analogue Recordset’s MoveFirst Recordset’s MoveLast Recordset’s MoveNext Recordset’s MovePrevious Recordset’s RecordCount property. Note: This property is not supported on some recordsets with some database providers. DBAccess object’s OpenConnection method. Recordset’s ReadRecord method. Note that as with PDBRecord, the fields in your UDT must be exactly the same in terms of number and type as the fields in the recordset, or errors may occur. No analogue No analogue No analogue 279 PDBRecordUniqueID PDBRemoveAllRecords PDBResizeRecord PDBSetCategoryName PDBSetDatabaseAttributes PDBSetFieldType, PDBSetNumFields PDBSetRecordAttributes PDBSetRecordCategoryID PDBSetSort PDBSetSortField PDBUpdateRecord PDBWriteField, PDBWriteFieldbyOffset PDBWriteRecord 12.8 Database dependent. Some tables may define a table key which is unique for every record. Some databases may create an additional bookmark field when a query is executed that can be retrieved with field index -1. Use a SQL query similar to the following: "delete from <table name>" No analogue No analogue No analogue No analogue. Depending on whether or not you need to synchronize a device with a central database server, you may be able to use SQL statements to alter a table’s fields. Changing a table is not recommended, however, if this table is to be synchronized. No analogue No analogue No analogue No analogue Recordset’s Update method. Recordset’s FieldAs<type> property. Fields must be set using the property that corresponds to their data types, else a type mismatch may occur. Recordset’s WriteRecord method. Database Library Examples All of the examples below are designed for the theoretical table employees, which has the following schema: Ordinal 0 1 2 3 4 Field Name name date_of_hire age salary brownie_points Type String Date Byte Currency Double Finding the Field Index Many database functions require that you know the exact position and type of fields in the recordset. If you only know the name of a field, you can find the ordinal of a field by using the FieldIndex function. The ordinal can then be used with the FieldType property to find the type of the field. 280 Dim Dim Dim Dim mgr As AFDatabaseLib.CDBAccessManager conn As AFDatabaseLib.IConnection rs As AFDatabaseLib.IReadableRecordset index As Long Set mgr = New AFDatabaseLib.CDBAccessManager Set conn = mgr.OpenConnection("SQLCE", "Data Source=\Data\database.sdf") Set rs = conn.OpenReadOnlyRecordset(" select * from employees") index = rs.FieldIndex("age") rs.Close conn.Close Reading Record Data Field values may be read either through recordset properties or through the ReadRecord method. ReadRecord should only be used in situations where the exact number and type of fields in a recordset is known at compile time. In order to use the ReadRecord method, you must create a user-defined type whose members match the fields in the recordset. If the fields do not match a fatal runtime error may occur. Public Type EmployeeRec name As String date_of_hire As Date age As Byte salary As Currency brownie_points As Double End Type Dim Dim Dim Dim mgr As AFDatabaseLib.CDBAccessManager conn As AFDatabaseLib.IConnection rs As AFDatabaseLib.IReadableRecordset rec As EmployeeRec Set mgr = New AFDatabaseLib.CDBAccessManager Set conn = mgr.OpenConnection("SQLCE", _ "Data Source=\Data\database.sdf") Set rs = conn.OpenReadOnlyRecordset( _ "select * from employees") rs.MoveFirst ’ Get fields using recordset properties 281 Debug.Print Debug.Print Debug.Print Debug.Print Debug.Print rs.FieldAsString(0) rs.FieldAsDate(1) rs.FieldAsByte(2) rs.FieldAsCurrency(3) rs.FieldAsDouble(4) ’ Get the fields using ReadRecord rs.ReadRecord VarPtr(rec) Debug.Print rec.name Debug.Print rec.date_of_hire Debug.Print rec.age Debug.Print rec.salary Debug.Print rec.brownie_points rs.Close conn.Close The above method will also work for queries that only retrieve a subset of a table’s fields or that select fields in a particular order. Simply define your record type so that its members match the fields you have selected in your query. Updating Record Data Records may be updated through either recordset field properties or through the WriteRecord method. Note that after using recordset properties to update fields, you must use the Update method. Dim Dim Dim Dim mgr As AFDatabaseLib.CDBAccessManager conn As AFDatabaseLib.IConnection tbl As AFDatabaseLib.IWritableRecordset rec As EmployeeRec Set mgr = New AFDatabaseLib.CDBAccessManager Set conn = mgr.OpenConnection("SQLCE", _ "Data Source=\Data\database.sdf") Set tbl = conn.OpenTable("employees") tbl.MoveFirst ’ Set fields using recordset properties tbl.FieldAsString(0) = "John Smith" tbl.FieldAsDate(1) = CDate("12/1/2001") tbl.FieldAsByte(2) = 25 tbl.FieldAsCurrency(3) = 50000 tbl.FieldAsDouble(4) = 2400.35 282 tbl.Update ’ Set the fields using WriteRecord rec.name = "John Smith" rec.date_of_hire = CDate("12/1/2001") rec.age = 25 rec.salary = 50000 rec.brownie_points = 2400.35 tbl.WriteRecord VarPtr(rec) tbl.Close conn.Close Adding New Records Records may be added through either recordset field properties or through the AddRecord method. Note that after using recordset properties to add fields, you must use the Update method. Dim Dim Dim Dim mgr As AFDatabaseLib.CDBAccessManager conn As AFDatabaseLib.IConnection tbl As AFDatabaseLib.IWritableRecordset rec As EmployeeRec Set mgr = New AFDatabaseLib.CDBAccessManager Set conn = mgr.OpenConnection("SQLCE", _ "Data Source=\Data\database.sdf") Set tbl = conn.OpenTable("employees") ’ Add a record using recordset properties tbl.AddNew tbl.FieldAsString(0) = "John Smith" tbl.FieldAsDate(1) = CDate("12/1/2001") tbl.FieldAsByte(2) = 25 tbl.FieldAsCurrency(3) = 50000 tbl.FieldAsDouble(4) = 2400.35 tbl.Update ’ Add a record using AddRecord rec.name = "John Smith" rec.date_of_hire = CDate("12/1/2001") rec.age = 25 rec.salary = 50000 rec.brownie_points = 2400.35 283 tbl.AddRecord VarPtr(rec) tbl.Close conn.Close Deleting Records The Delete method of the writable recordset will delete the current record. After deleting a record, the recordset’s cursor still points to the deleted record, so you should move to either the next or the previous record. tbl.Delete tbl.MoveNext If tbl.EOF Then tbl.MovePrevious End If A Generic Record Reader The following example subroutine will read the values from a recordset with any number of fields and add the records to a grid. Private Sub LoadRecordsIntoGrid(rs As IReadableRecordset, _ grid As AFGrid) Dim data As String Dim i As Integer On Error GoTo LoadRecords_Error ’ Reset grid grid.Clear grid.Cols = rs.FieldCount ’ Add field names to the grid data = "" For i = 0 To rs.FieldCount - 1 If i <> 0 Then data = data & Chr(9) & rs.FieldName(i) Else data = rs.FieldName(i) End If 284 Next i grid.AddItem data ’ Add all records to the grid rs.MoveFirst While Not rs.EOF data = "" For i = 0 To rs.FieldCount - 1 If i <> 0 Then data = data & Chr(9) Select Case rs.FieldType(i) Case afDBTypeInteger data = data & rs.FieldAsInteger(i) Case afDBTypeString data = data & Trim(rs.FieldAsString(i)) Case afDBTypeBoolean data = data & rs.FieldAsBoolean(i) Case afDBTypeLong data = data & rs.FieldAsLong(i) Case afDBTypeByte data = data & rs.FieldAsByte(i) Case afDBTypeDate data = data & rs.FieldAsDate(i) Case afDBTypeDouble data = data & rs.FieldAsDouble(i) Case afDBTypeCurrency data = data & rs.FieldAsCurrency(i) Case afDBTypeSingle data = data & rs.FieldAsSingle(i) End Select Next i grid.AddItem data rs.MoveNext Wend Exit Sub LoadRecords_Error: MsgBox "Error in LoadRecords: " & Hex(Err.Number) _ & " - " & Err.Description End Sub 285 12.9 AppForge PDB Library AppForge PDB Library Overview Overview The AppForge PDB Library provides a set of methods to manipulate Palm Databases (PDBs). PDB files can be loaded to and accessed on any platform that MobileVB™ supports. PDBs are different from other database types in that each PDB file stores only one table, and constraint checking is not performed (e.g., PDBs do not have primary keys). It is the developer’s responsibility to maintain appropriate database constraints within his or her application. Palm OS is a registered trademark of Palm, Inc. Typical Usage Databases are typically used for storing data for a long period of time. Data can be added to or deleted from a database, and the information can be sorted and displayed in alphabetical or numerical order. The following information includes the basic steps for creating and working with a Palm Database file. 1. First, convert a table in a Microsoft Access database to a PDB using the AppForge Database Converter. Make sure that your PDB is saved under the working directory for your MobileVB™ project, and that it has a name that does not match that of the project (PRC file). The converter can generate a database code module, which provides database constants and compatible type definitions when added to a project. For more information on converting and viewing databases, see the AppForge File Converters and Viewers Guide. 2. Open an existing PDB during run time using PDBOpen , which returns a unique database handle (as a Long value) that can be used to identify the database when calling other methods. If PDBOpen returns False, you can program the application to create a new database during run time using the PDBCreateDatabase method , and define the database’s schema using the PDBCreateTable method. 3. Use the PDB Library methods to access, modify, and sort database records. Most PDB methods require the database handle (returned by PDBOpen or PDBCreateDatabase as a Long value) as input, in order to identify the database. 4. Add the PDB to the project’s list of Dependencies via the MobileVB Settings menu, before uploading your application to the device. 5. Optional - Set up the AppForge Universal Conduit so users can synchronize a Palm Database with any ODBC database on a desktop PC. See the AppForge Universal Conduit Guide for more information. For an example database project, go Toolkit\samples\Apps\PDB Library Tutorial. 286 to C:\Program Files\AppForge\VB The following list includes the most commonly used calls in the AppForge PDB Library. Refer to the Methods section for a complete list of AppForge PDB Methods. 1. PDBOpen 2. PDBReadRecord 3. PDBCreateRecordBySchema 4. PDBWriteRecord 5. PDBEditRecord 6. PDBSetSortFields 7. PDBDeleteRecord 8. PDBUpdateRecord 9. PDBMoveFirst 10. PDBMoveLast 11. PDBMoveNext 12. PDBMovePrev 13. PDBBOF 14. PDBEOF 15. PDBRecordUniqueID 16. PDBFindRecordbyID 17. PDBFindRecordByField 18. PDBGetLastError AppForge PDB Library Methods 287 PDBBOF PDBClose PDBCreateRecord PDBCurrentIndex PDBDeleteRecordEx PDBFindRecordByField PDBGetDatabaseAttributes PDBGetLastError PDBGotoIndex PDBMoveNext PDBOpen PDBRecordAttributesEx PDBRecordUniqueID PDBSetCategoryName PDBSetNumFields PDBSetSort PDBWriteField 12.10 PDBBulkRead PDBCreateDatabase PDBCreateRecordBySchema PDBDeleteDatabase PDBEditRecord PDBFindRecordbyID PDBGetField PDBGetNumFields PDBMoveFirst PDBMovePrev PDBReadRecord PDBRecordCategoryID PDBRemoveAllRecords PDBSetDatabaseAttributes PDBSetRecordAttributes PDBSetSortFields PDBWriteFieldByOffset PDBCancelRecordEdit PDBCreateDBUniqueNumber PDBCreateTable PDBDeleteRecord PDBEOF PDBGetCategoryName PDBGetFieldByOffset PDBGetSortFields PDBMoveLast PDBNumRecords PDBRecordAttributes PDBRecordSize PDBResizeRecord PDBSetFieldType PDBSetRecordCategoryID PDBUpdateRecord PDBWriteRecord AppForge Database Library AppForge Database Library Overview The AppForge Database Library provides the following classes: AppForge Database Library Classes CDBAccessManager IWritableRecordset IConnection IReadableRecordset CDBAccessManager Overview The CDBAccessManager class provides the following method: Method OpenConnection 288 IConnection Overview The IConnection class provides the following methods: Methods Close OpenTable ExecuteStatement OpenReadOnlyRecordset IReadableRecordset Overview The IReadableRecordset class provides the following properties and methods: Properties BOF FieldAsByte FieldAsDouble FieldAsSingle FieldIsNull FieldType EOF FieldAsCurrency FieldAsInteger FieldAsString FieldName RecordCount FieldAsBoolean FieldAsDate FieldAsLong FieldCount FieldSize Methods Close FindByte FindDouble FindSingle MoveLast ReadRecord FieldIndex FindCurrency FindInteger FindString MoveNext FindBoolean FindDate FindLong MoveFirst MovePrevious IWritableRecordset Overview The IWritableRecordset class provides the following properties and methods: Properties 289 BOF FieldAsByte FieldAsDouble FieldAsSingle FieldIsNull FieldType EOF FieldAsCurrency FieldAsInteger FieldAsString FieldName RecordCount FieldAsBoolean FieldAsDate FieldAsLong FieldCount FieldSize Methods AddNew Delete FindByte FindDouble FindSingle MoveLast ReadRecord WriteRecord 12.11 AddRecord FieldIndex FindCurrency FindInteger FindString MoveNext SetFieldNull Close FindBoolean FindDate FindLong MoveFirst MovePrevious Update AppForge SQLCE Administration Library AppForge SQLCE Administration Library Overview The AppForge SQLCE Administration Library provides the following classes: AppForge SQLCE Administration Library Classes CSQLAdmin CSQLSynchronizationError CSQLRDA CSQLSynchronization CSQLAdmin Overview The CSQLAdmin class provides the following methods: Methods CompactDatabase 290 CreateDatabase CSQLRDA Overview The CSQLRDA class provides the following properties and methods: Properties ErrorCount InternetPassword InternetProxyServer Errors InternetProxyLogin InternetURL InternetLogin InternetProxyPassword LocalConnectionString Methods Pull Push SubmitSQL CSQLSynchronization Overview The CSQLSynchronization class provides the following properties and methods: Properties Distributor DistributorNetwork ErrorCount InternetLogin InternetProxyPassword LoginTimeout Publisher PublisherConflicts PublisherNetwork QueryTimeout SubscriberConflicts DistributorAddress DistributorPassword Errors InternetPassword InternetProxyServer ProfileName PublisherAddress PublisherDatabase PublisherPassword Subscriber SubscriberConnectionString DistributorLogin DistributorSecurityMode HostName InternetProxyLogin InternetURL Publication PublisherChanges PublisherLogin PublisherSecurityMode SubscriberChanges Validate Methods CreateSubscription Synchronize DropSubscription 291 ReinitializeSubscription CSQLSynchronizationError Overview The CSQLSynchronizationError class provides the following properties: Properties Description Source 12.12 ErrorNumber NativeError AppForge Pocket Access Administration Library AppForge Pocket Access Administration Library Overview The AppForge Pocket Access Administration Library provides the following classes: AppForge Pocket Access Administration Library Classes CCEDBAdmin CCEDBTableInfo CCEDBAdmin Overview The CCEDBAdmin class provides the following methods: Methods CreateDatabase DeleteTable CreateTable GetTableInfo DeleteDatabase SortTable CCEDBTableInfo Overview The CCEDBTableInfo class provides the following properties and methods: Properties FieldCount FieldType TableName FieldLength SortOrder TableType 292 FieldName SortType Methods AddField 12.13 ClearFields RemoveField AppForge Symbian OS Database Administration Library AppForge Symbian OS Database Administration Library Overview The AppForge Symbian OS Database Administration Library provides the following class: AppForge Symbian OS Database Administration Library Class CSymbianOSDBAdmin CSymbianOSDBAdmin Overview The CSymbianOSDBAdmin class provides the following methods: Methods CompactDatabase CreateDatabase DeleteDatabase GetDatabaseSize RecoverDatabaseIncremental CompactDatabaseIncremental DatabaseIsDamaged ExecuteDDLIncremental Next RefreshSizeIncremental 293 CompressDatabase DecompressDatabase ExecuteDMLIncremental RecoverDatabase