PowerTCP Introduction

Welcome to PowerTCP, the market leader in Internet Application Development Tools.

The following topics provide a general overview of PowerTCP:

  • PowerTCP Introduction

  • PowerTCP Tools Overview

  • License Installation

  • Trial Operation

  • Support

  • Distribution

  • Debugging Notes

  • PowerTCP Visual C++ Notes


PowerTCP Overview

Dart has transformed its world-class Internet Toolkit into a Component Object Model (COM) – based set of ActiveX controls that are supported in more development environments than ever before. Our ActiveX (ATL) controls and sample applications plug into all popular development environments: Visual Studio, C++Builder, Delphi, PowerBuilder, Internet Information Server (ASP), JavaScript, FoxPro, and other VB script and VBA environments. New features include:

  • Multi-tier architecture that separates all processing into 3 layers—no competing product offers this level of flexibility and modularity:

  • Formatting tier converts bytes into objects

  • Upper-layer protocol tier (Telnet, FTP, SMTP, etc.) implements communication protocols

  • Winsock tier handles all communication tasks

  • Controls can be placed on forms OR dynamically instantiated, making this product perfect for both form-based environments like Visual Basic AND formless environments like ASP.

  • Blocking behavior is included, so you can write applications using blocking or non-blocking operation. Scripting languages such as VB and JavaScript are now fully supported.

  • 'Apartment Model Threading' provides multi-thread support for the most demanding applications.

  • Superior Object Model maximizes your effectiveness in your development environment—collection properties provide superior list handling, formatting objects make it easier to manipulate complex structures (like MIME and SNMP messages), and the use of enumerated types and objects makes your job as simple as it should be.

PowerTCP is a complete collection of Internet protocol controls and formatting objects. The controls provide concise programming models for the protocols and contain events to help monitor lengthy operations, and the formatting objects transform data between network bytes and COM objects with which your application can easily work.


PowerTCP Tools Overview

This topic describes the following PowerTCP Tools:

  • Emulation Tool

  • FTP Tool

  • Mail Tool

  • SSL Tool

  • Server Tool

  • SNMP Tool

  • Telnet Tool

  • Web Tool

  • Web Enterprise Tool

  • WebServer Tool

  • Winsock Tool

PowerTCP Emulation Tool

Build terminal emulation capabilities into your application with this visual VT52/100/220/320 control. The Emulation Tool consists of the following controls:

Telnet Control – Manage Telnet, Rexec, Rsh, and Rlogin sessions

VT Control – Concise visual VT-320 display viewing, including invisible screen-scraping

Back to Top

PowerTCP FTP Tool

Copy files between your client and any FTP server. The FTP Tool consists of the following control:

FTP Control – Transfer files

Back to Top

PowerTCP Mail Tool version 2

Create advanced Internet mail applications with these controls for extended SMTP, POP3, and IMAP4. The Mail Tool consists of the following controls:

SMTP Control – Superior high-performance mail delivery

POP Control – Ultimate control for downloading mail

IMAP Control – Objects make IMAP simple to use

Back to Top

PowerTCP SSL Tool

Automatically authenticate and encrypt/decrypt all data sent and received over a TCP connection using SSL2, SSL3, PCT, and TLS. The SSL Tool consists of the following controls:

CertificateList Control – Present the user with an interface to select certificates

Daemon Control – Accept connections

Service Control – Turn your server application into an NT service

SecureFtp Control – Establish secure FTP sessions

SecureFtpServer Control – Build into your application a secure fully-functioning standalone or custom FTP server

SecurePop Control – Download mail from secure POP servers

SecureServer Control – Daemon Control and a collection of SecureTcp Controls for superior "turn-key" secure server performance

SecureTcp Control – Send data securely over the Internet

Back to Top

PowerTCP Server Tool version 2

Enable the rapid construction of custom server applications. The Server Tool consists of the following controls:

FtpServer Control – Build into your application a fully-functioning standalone or custom FTP server

Server Control – Daemon Control with a collection of TCP Controls for superior "turn–key" server performance

Service Control – Turn your server application into an NT service

TCP Control – Stream management

Back to Top

PowerTCP SNMP Tool version 2

Put the "simple" back into Simple Network Management Protocol. The SNMP Tool consists of the following controls:

SNMP Agent Control – "Drop-in" SNMP agent

SNMP Manager Control – "Drop-in" SNMP manager

Service Control – Turn your Agent application into an NT service

Back to Top

PowerTCP Telnet Tool

Manage Telnet, Rexec, Rsh, and Rlogin sessions. The Telnet Tool consists of the following control:

Telnet Control – Manage Telnet, Rexec, Rsh, and Rlogin sessions

Back to Top

PowerTCP Web Tool

Communicate with Web Servers using HTTP and HTTP/S. The Web Tool consists of the following control:

Web Control – Access Web page documents (supports secure HTTP)

Back to Top

PowerTCP WebEnterprise Tool

Communicate with Web Servers using HTTP and HTTPS with a server-optimized tool. Includes powerful Web parsing and resource grabbing objects.

CertificateList Control – Present the user with an interface to select certificates

Web Control – Wininet dependent control used to access Web page documents (supports secure HTTP)

WebASP Control – Wininet independent control used to access Web page documents using WebMessage Object (supports secure HTTP).

Back to Top

PowerTCP WebServer Tool

Build web applications in any familiar software development environment. The WebServer Tool consists of the following controls:

Service Control – Turn your server application into an NT service

WebServer Control – Add Web Server capabilities to any application

Back to Top

PowerTCP Winsock Tool version 2

A complete set of basic building blocks with controls for TCP, UDP, Daemon, DNS, Ping, and RAS. The Winsock Tool consists of the following controls:

Daemon Control – Accept connections

DNS Control – Lookup names, addresses, mail servers

Ping Control – Verify a host is reachable

RAS Control – Control system dial-up services

TCP Control – Stream management

UDP Control – Send and receive user datagrams and raw datagrams

Back to Top


PowerTCP Licensing

PowerTCP License Installation

Your PowerTCP License Agreement provides you with a single-seat development license and the right to distribute PowerTCP controls with NO ROYALTIES of any kind. Some PowerTCP objects are marked as licensed. This topic covers:

  • Trial Installation

  • Installing a Fully Licensed PowerTCP Tool

  • Re-installing a PowerTCP Tool

  • License Details

  • Special Notes on Tested Development Environments

Trial Installation

Installing a PowerTCP Tool as a fully–functional trial involves running the setup program (available from www.dart.com) without completing the Registration process. The trial will operate for 30 days after installation. Proceed to step 2 of Installing a Fully Licensed PowerTCP Tool when you are ready to license the product.

See Trial Operation for more information.

Back to Top

Installing a Fully Licensed PowerTCP Tool

Once you have downloaded the latest version, complete the following steps to register your PowerTCP Tool:

  1. From the Start menu, point to Programs, point to PowerTCP, point to the PowerTCP Tool you downloaded, and then click Registration.

  2. In the PowerTCP Registration dialog box, click Register.

  3. Enter your Serial Number, First Name, Last Name, and Organization information.

  4. Click Next.

  5. Enter your Email Address, Purchased From, and Purchased Date information.

  6. Click Next.

  7. Verify that the information is correct, and then click Next.

  8. When the registration process is complete, click Exit. (Note Clicking Done at this step displays your currently registered PowerTCP Tools. Click Exit to end the complete the registration process and close the dialog box.)

If you do not have Internet Access on your development machine, please follow these instructions:

  1. From the Start menu, point to Programs, point to PowerTCP, point to the PowerTCP Tool you downloaded, and then click Registration.

  2. In the PowerTCP Registration dialog box, click Edit.

  3. In the Currently Registered Products area, write down the number in the Key field (the fields appears dimmed).

  4. On a machine that has Internet access, log on to the Dart registration page (http://www.dart.com/register/).

  5. Enter all required information. Required information is bolded. Key is the number you wrote down in Step 3 above.

  6. Click Submit. A seven-digit registration code appears.

  7. On your machine (the machine on which you completed Steps 1-3), if necessary, access the PowerTCP Registration dialog box to display the Currently Registered Products area containing the Key number.

  8. Enter your serial number and the seven-digit registration number you obtained in Step 6.

  9. Click Update.

  10. Click Exit.

After either of the two registration procedures are complete, your PowerTCP Tool appears in the Registered Tools field of the registration form. Make sure you recompile your application after you register the PowerTCP Tool. For distribution instructions specific to your development environment, please view the Readme file. The Readme file is located in the Samples directory; for example, to locate the Readme file for the Winsock Tool in VB6, use the following path: Start>Programs>PowerTCP>WinsockTool>VB Samples>VB6>Readme.

If you do not register your PowerTCP Tool at this point, it will operate as a trial. Remember to distribute with your applications any necessary PowerTCP files and any dependent files. Dependent files are listed in the Introduction topic for each PowerTCP Control, and must be installed on each target system. See Distribution for more information on system requirements.

Back to Top

Re-installing a PowerTCP Tool

The Key provided by the Registration Program is derived from a system number that is changed when the C: drive is reformatted. If you reformat your hard disk, and need to re-install your PowerTCP Tool, follow the steps in Installing a Fully Licensed PowerTCP Tool. You will be prompted to complete a License Transfer form, and a new Registration Number will be generated.

If you need to re-install more than once, you will be prompted to complete a License Transfer form that will be sent to your sales representative for approval. Within two working days Dart will reset your Serial Number and notify you when you can re-register your product. The product will operate as a trial for up to 30 days.

Back to Top

License Details

When you insert a PowerTCP control into a project, most development environments verify that the control is licensed for development. The control will work if you correctly entered the PowerTCP Tool Serial Number. See Installing a Fully Licensed PowerTCP Tool for more information. When you compile your application, the development environment requests this Serial Number and embeds it in the application. When users run your application, the application submits this Serial Number to the control and the Serial Number is checked for validity. If the Serial Number is correct, then the application runs. This verification process occurs automatically.

Back to Top

Special Notes on Tested Development Environments

  • Visual Basic checks for a Serial Number when a PowerTCP control is first inserted on a form or first shown on a form. When a PowerTCP control is loaded as a reference and is dynamically instantiated (for example, Dim Tcp as New Tcp), the Serial Number is similarly checked.

  • Visual C++ obtains the Serial Number when you first insert a PowerTCP control on a form, and caches that number as a dialog resource. For this reason, Dart ships Visual C++ samples without inserted controls. You will need to insert them before you compile any of the samples. See the readme.txt file for more information. Information on dynamically creating objects using ClassFactory2 is included. License caching is MFC only; for our new C++ classes, you must specify the License as a parameter in the Create method.

  • Active Server Page deployment requires a Serial Number for each server because the environment checks for a development license each time a licensed control is used. If you deploy PowerTCP Tools for operation under IIS, install your development license into the registry as it appears on your development platform (check registry location HKEY_LOCAL_MACHINE / SOFTWARE / Dart / PowerTCP / License to see what should be installed). PowerTCP is royalty-free, including under IIS.

  • PowerBuilder also caches licensing information. See the readme.txt file for instructions on how to compile the sample applications.

  • Excel will cache licensing information when the control is originally inserted, so your spreadsheet will carry this information forward to any deployment platforms.

  • Delphi has special requirements. Before you can use the sample applications you MUST add the PowerTCP Tools that are in the sample to the Component Library. Refer to the readme.txt file for specific instructions.

  • C++ Builder is similar to Delphi. See the readme.txt file for specific instructions.

Back to Top


PowerTCP Trial Operation

If you install a PowerTCP product without registering a Serial Number, it operates as a fully–functional trial for up to 30 days. If you need more time to evaluate the product, reinstall it; the trial period will start over.

Trial Notification in Development Mode

When you insert a PowerTCP control on your form or dynamically create one, the control checks for a Serial Number. When it does not find one, a dialog box appears identifying the product as a trial. This dialog box does not appear if you are running under IIS; this allows the product to work within the ASP environment as a trial. After the trial period expires, you cannot insert the control without first reinstalling it.

Trial Notification during Compile

PowerTCP controls request a Serial Number when you compile your application. A dialog box appears warning you that the component is not licensed for deployment. Do not distribute your application using a trial product—the component will not work after the trial period! However, you may test your application during your trial period. To continue testing after the trial period, reinstall the product and recompile your application.

See License Installation for more information on product registration.


PowerTCP Support

Note Visit the Dart Support Forum to share ideas with PowerTCP users worldwide. This forum is monitored by the Dart support staff.

Dart offers the following six support options:

Program

Description

Length

Free Introductory Support

Includes:

  • Email support covering installation issues

  • Tool usage and application

  • Distribution

30 days after purchase

Solution Support

PowerTCP functions as a vital bridge between the desktop and other enterprise resources. Dart can help you implement this bridge by tailoring our software engineering and development services to your needs.

Pricing for Solution Support is available by quote. Please contact your sales representative.

Standard Support

Includes:

  • Unlimited email and fax support covering installation issues, tool usage and application, and deployment.

  • Email notification of free tool updates provided via web download.

  • Special incentives on new products and services.

A discount is available if purchased with the corresponding PowerTCP Tool.

One year - renewable

Priority Support

Includes:

  • Unlimited telephone, email, and fax support covering installation issues, tool usage and application, and deployment.

  • Limited code review and analysis upon request.

  • Free major version product upgrades.

  • Email notification of free tool updates provided via web download.

  • Special incentives on new products and services.

A discount is available if purchased with the corresponding PowerTCP Tool.

One year - renewable

ISV Support

Includes:

  • Unlimited telephone, email, and fax support covering installation issues, tool usage and application, and deployment.

  • Code review and analysis upon request.

  • Free major version product upgrades.

  • Email notification of free tool updates provided via web download.

  • Priority telephone access to senior support representatives.

  • Optional escrow account for software source code (Fort Knox).

  • Continued support for previously released major versions.

  • Guaranteed response within four hours of notification during business hours (M-F, 8:30-5:30 EST).

  • Interoperability resolution within five business days of notification.

Please contact your sales representative about this special program.

One year - renewable

Team Support

Team support extends ISV Support benefits to teams of developers who routinely use PowerTCP Tools.

One year - renewable


PowerTCP Distribution

This topic covers:

  • System File Updates

  • Winsock version 2 System Support

  • PowerTCP Components

  • Distribution under Internet Information Server

  • Troubleshooting

System File Updates

Windows 95

DCOM95 version 1.3 must be installed before installing PowerTCP DLLs. You can redistribute DCOM95 with your product so your users can install it. Obtain DCOM95 from www.microsoft.com/com/dcom/dcom95/download.asp .

Windows 98

DCOM98 version 1.3 must be installed before installing PowerTCP DLLs. Microsoft does not allow redistribution of DCOM98, so your users will need to obtain it from www.microsoft.com/com/dcom/dcom98/download.asp .

Windows NT4

Your system must be updated to a level of at least Service Pack 3 (the Secure DLL requires SP4) before installing PowerTCP DLLs. You must update the following OLE system files to the following levels:

DLL | Version
OLEAUT32.DLL | 2.40.4275 (or higher)
STDOLE2.TLB | 2.40.4275 (or higher)
ASYCFILT.DLL | 2.40.4275 (or higher)
OLEPRO32.DLL | 2.40.4275 (or higher)
COMCAT.DLL | 4.71 (or higher)

System updates are performed using the 4275-Ole.exe file, which is located in the Bin directory in your PowerTCP Tool install root directory. You can redistribute this file to your users. Note This system update file will not run under Win95/98 (see Windows 95 and Windows 98 for Win95/98 requirements).

Windows 2000

Windows 2000 requires no system file updates.

Back to Top

Winsock version 2 System Support

Windows 95 ships with Winsock version 1; all other operating systems (Win98/2000/NT) ship with version 2. Version 2 is only required by applications that use raw datagrams and multicast features. Dart's Ping Control and UDP Control (multicast feature) are the only products that require version 2. This update was last available at www.microsoft.com/windows95/downloads/contents/wuadmintools/s_wunetworkingtools/w95sockets2/ .

PowerTCP links to Winsock version 1, but the operating system redirects these calls to version 2 (if installed). Therefore, performance is optimal (no performance degradation occurs due to linking to Winsock version 1), while still allowing PowerTCP to be installed on Windows 95 systems that have not been updated to version 2.

If you use raw or multicast datagrams, make sure Winsock version 2 is available on your deployment platforms.

Back to Top

PowerTCP Components

Refer to each PowerTCP Control main topic in this Help system (for example, Telnet Control main topic) for a list of dependent DLLs. For example, DartFtp.dll (containing the FTP Control) is dependent upon DartSock.dll for all communications. You must install both DLLs when you distribute your application. Each DLL ships with a .dep file that lists these dependencies.

PowerTCP DLLs must be registered. Most installation utilities will do this automatically; however, you can also use Regsvr32.exe. See System File Updates for more information on system file support before registering PowerTCP Tools.

The following table summarizes PowerTCP DLL dependencies:

DLL | Dependent Upon
DartSock.dll | None
DartRas.dll | DartSock.dll
DartUtil.dll | DartSock.dll
DartFtp.dll | DartSock.dll
DartFtpServer.dll | DartSock.dll, DartServer.dll, DartFtpUtil.dll
DartTelnet.dll | DartSock.dll
DartSnmp2.dll | DartSock.dll
DartVt.dll | DartSock.dll
DartWeb.dll | DartSock.dll
DartMail.dll | DartSock.dll, DartUtil.dll
DartServer.dll | DartSock.dll
DartSecure2.dll | DartSock.dll, DartCertificate.dll
DartSecureMail.dll | DartSock.dll, DartSecure2.dll, DartCertificate.dll, DartMail.dll
DartSecureFtp.dll | DartSock.dll, DartSecure2.dll, DartCertificate.dll, DartFtp.dll
DartWebASP.dll | Wsock32.dll (Winsock v. 1.1), DartSock.dll, DartSecure2.dll, DartWebUtil.dll, DartCertificate.dll
DartWebServer.dll | DartSock.dll, DartServer.dll, DartSecure2.dll, DartWebUtil.dll, DartCertificate.dll

Back to Top

Distribution under Internet Information Server

If you are using PowerTCP under IIS and you have not installed a Serial Number, the product will work for 30 days as a Trial, but will then cease operation. Active Server Page deployment requires a Serial Number for each server because the environment checks for a development license each time a licensed control is used. If you deploy PowerTCP Tools for operation under IIS, install your development license into the registry as it appears on your development platform (check registry location HKEY_LOCAL_MACHINE / SOFTWARE / Dart / PowerTCP / License to see what should be installed).

For most compiled applications, your PowerTCP Serial Number is automatically included when you compile, so no special license considerations are necessary. The only exception is Dart's C++ wrapper, in which the Create method takes your development license as a parameter.

Back to Top

Troubleshooting

If you receive "not licensed for distribution" messages, try removing the control from your project and then re-inserting it. If a trial was already installed and used to build a project, some development environments cache the licensing information even after registering the control. Refer to environment–specific readme.txt files for more information.

Back to Top


PowerTCP Debugging Notes

Visual Basic

WARNING You can use breakpoints and the MsgBox function to stop your application at any point, but communications may not operate normally after program execution is resumed.

Visual Basic stops reporting events when execution halts at a breakpoint or upon the display of a modal dialog box. For example, suppose you place a breakpoint within the TCP State event and Receive event, and then connect to a server that sends data. You will break within the State event when the connection is established, but the Receive event will not fire. Visual Basic is "protecting" you from reentrancy. This can also occur if you display a message box after calling the Connect method, in which case no events fire. Modeless forms do not have this side effect.

Consequently, you should use:

  • A label or an edit box to display progress.

  • The Trace method to accumulate a data log.

These techniques provide necessary debugging information without affecting the communication events being monitored.


PowerTCP Visual C++ Notes

Each development environment has it's own unique way of supporting ActiveX controls. Visual Basic, for example, offers superb support for using controls both on forms (by adding it to the component bar and dragging it onto a form) and off forms (by instantiating them at run-time using "Dim" and "Set" constructs). In Visual C++ it is a little harder, and there are different techniques possible using MFC and "straight" WIN32.

MFC Support for ActiveX

MFC provides direct support for placing a control on a form. Using the ClassWizard, you then reference the control ID, add a variable, and then add event handles for each event. This mechanism works well with Dart PowerTCP controls, but has the following shortcomings that require a workaround:

  1. When you insert a control, the resource file caches license information. When you use the control as a trial and subsequently purchases a license, you must manually remove the control and then read it so that the license information is properly included and passes the license check at run time.

  2. When Dart ships the sample as part of a PowerTCP Tool, it must be shipped with the control missing, so the application does not compile as shipped (the control must be added first, even to operate as a trial).

  3. You cannot use this technique for non-MFC or formless applications, such as console applications, service applications, ATL controls, "straight" WIN32 applications, and other C++ environments (such as Borland C++ and C++ Builder).

To work around these limitations, many Dart controls have already been upgraded to provide the following benefit.

Class Support for ActiveX

Dart has provided a "wrapper" class for many controls (and objects) that uses licensing, such that:

  1. Developers may not be familiar with using using the C function to create a licensed control (CoComCreateInstanceLic). Dart has provided a Create() method to handle the instantiation of a licensed control.

  2. Developers may also be unfamiliar with manually adding event support. Dart has provided code to create this connection within the class.

  3. You can uses these classes in any C++ environment, simplifying the use of our product in these environments.

  4. Samples will compile right out of the box.


Access

Microsoft Access Environment

The Microsoft Access samples in this toolkit were created with Microsoft Access 97.

Using The Sample Applications

Each database has a Form called main. Start by opening that Form. If this is the first time you have opened the sample you will need to read any PowerTCP Tools that are in the project so that the licensing gets reset. To do this simply write down the name and type of each Dart control. Then, one at a time, delete each control and insert a new one with the same name.

Example:

Form Main contains a Dart FTP Control, whose name is FTP1. Select FTP1 and Delete it. Now insert a new Dart FTP control and name it FTP1. This will cause a new 30 day trial key to be generated and allow you to use the sample.

Environment Specific Quirks

If you began developing a database while under the trial period, you will have to follow the instructions above for reading any controls that were inserted during the trial period. This is due to the fact that Access adds license key's directly into the database at the time of insertion.


BCB4

Borland C++Builder 4 Environment

The Borland C++Builder 4 samples in this toolkit were compiled with Borland C++Builder 4.0 with NO updates applied. Due to the fact that wrapper code is not always backward compatible, some code may need to be changed if any other version is used to open these samples.

Using the Sample Applications:

Before you can use the sample applications you MUST add the PowerTCP Tools that are in the sample to the Component Library.

Adding PowerTCP Tools into the Component Library:

  1. Start BCB4 and Close any open projects.

  2. From the Main Menu choose Component | Import ActiveX Control.

  3. Choose the Tool to install:

Examples:

  • Dart FTP Control

  • Dart Telnet Control

  • Dart Server Control

  4. Click the 'Install' Button.

  5. Use the default dclusr40.bpk and click 'OK'.

  6. Answer 'Yes' to the rebuild.

  7. When the rebuilding process is done, close BCB4 saving the changes to dcluser.

Removing PowerTCP Tools from the Component Library:

  1. Start BCB4 and Close any open projects.

  2. Open the project where you installed the controls ( This is usually Lib\dclusr40.bpk ).

  3. Remove the dcr and cpp for the Control you wish to remove.

  4. Re-Compile the library.

  5. Close BCB4.

To ensure that all traces of the controls are removed from the library, delete the relevant source files from the Imports directory

Environment Specific Quirks

The samples were built by importing Dart controls via "Component / Import ActiveX Control". The wrapper code generated by the compiler was left untouched. Doing so has the following caveats (i.e., bugs) from the wrapper code created by the BCB wizard. (These may be fixed in a future BCB release):

  1. Control methods and property usage that generate run-time errors can be caught via a try/catch block that catches the Exception type in BCB 3. This is broken in 4 but works when using the global catch (...) syntax. In BCB 3 the Exception object Message property is set to the program name, source file, and line number. This is inconsistent with all other containers which set the error description to that generated by the control.

To get around this, trap the error description in the control's Error event and use that in the try/catch block.

  2. In BCB4, Control methods which do not return a value, such as the Telnet Connect method, do not get wrapped with ANY error checking whatsoever. To trap run-time errors when using these methods in blocking mode you must put in your own error wrapping as such:

try

{

....

Telnet->Connect(Rname,Rport,Lname,Lport);

if (TelnetError) throw new Exception(TelnetErrorDescription);

...

...any more lines of code to execute

...

}

catch (Exception &e)

{

Msgbox(e.Message);

}

where TelnetError and TelnetErrorDescription are String variables set in the Telnet Error event.

  3. To prevent an unwanted system messagebox popup when a control throws a run-time error:

In BCB3, put in the code:

bool TDebugHlpr<TCHAR>::PromptOnHrCheckFailure= false;

In BCB4, define the preprocessor definition: NO_PROMPT_ON_HRCHECK_FAILURE in the Conditional Defines of the project options.

  4. When using any Dart control that includes ErrorConstants, a compiler error for ambiguity between namespace conflicts may occur. You will need to physically modify the wrapper code for BCB3 and remove one of the ErrorConstants definitions or make some other such change. In BCB4, the ambiguity error is only generated if implementing the Error event.

To get around this and not modify the wrapper code: modify the client source to force the namespace in front of the ErrorConstants in the Error event in the .h and .c files like such:

void __fastcall TfrmMain::Telnet1Error(TObject *Sender,

Darttelnet_tlb::ErrorConstants Number, BSTR Description)

The IDE will complain every time a build is made with the popup: "The Telnet1Error method referenced by Telnet1->OnError has an incompatible parameter list. Remove the reference?" Always select "NO", otherwise the IDE will unlink the event and it will never occur at runtime.

This can be permanently fixed by modifying the ill-generated wrapper code in the components package where the control resides.


BCB5

Borland C++Builder 5 Environment

The Borland C++Builder 5 samples in this toolkit were compiled with Borland C++Builder 5.0 with Update 1 applied. Due to the fact that wrapper code is not always backward compatible, some code may need to be changed if any other version is used to open these samples.

Using the Sample Applications:

Before you can use the sample applications you MUST add the the PowerTCP Tools that are in the sample to the Component Library.

Adding PowerTCP Tools into the Component Library:

  1. Start BCB5 and Close any open projects.

  2. From the Main Menu choose Component | Import ActiveX Control.

  3. Choose the Tool to install:

Examples:

  • Dart FTP Control

  • Dart Telnet Control

  • Dart Server Control

  4. Click the 'Install' Button.

  5. Use the default dclusr50.bpk and click 'OK'.

  6. Answer 'Yes' to the rebuild.

  7. When the rebuilding process is done, close BCB5 saving the changes to dcluser.

Removing PowerTCP Tools from the Component Library:

  1. Start BCB5 and Close any open projects.

  2. Open the project where you installed the controls (This is usually Lib\dclusr50.bpk).

  3. Remove the dcr and cpp for the Control you wish to remove.

  4. Re-Compile the library.

  5. Close BCB5.

To ensure that all traces of the controls are removed from the library, delete the relevant source files from the Imports directory

Environment Specific Quirks

The samples were built by importing Dart controls via "Component / Import ActiveX Control". The wrapper code generated by the compiler was left untouched. Doing so has the following caveats (i.e., bugs) from the wrapper code created by the BCB wizard. (These may be fixed in a future BCB release):

  1. Control methods and property usage that generate run-time errors can be caught via a try/catch block that catches the Exception type in BCB 3. This is broken in 5 bu works when using the global catch (...) syntax. In BCB 3 the Exception object Message property is set to the program name, source file, and line number. This is inconsistent with all other containers which set the error description to that generated by the control.

To get around this, trap the error description in the control's Error event and use that in the try/catch block.

  2. In BCB5, Control Methods which do not return a value, such as the Telnet Connect method, do not get wrapped with ANY error checking whatsoever. To trap run-time errors when using these methods in blocking mode you must put in your own error wrapping as such:

try

{

....

Telnet->Connect(Rname,Rport,Lname,Lport);

if (TelnetError) throw new Exception(TelnetErrorDescription);

...

...any more lines of code to execute

...

}

catch (Exception &e)

{

Msgbox(e.Message);

}

where TelnetError and TelnetErrorDescription are String variables set in the Telnet Error event.

  3. To prevent an unwanted system messagebox popup when a control throws a run-time error:

In BCB3, put in the code:

bool TDebugHlpr<TCHAR>::PromptOnHrCheckFailure= false;

In BCB4, define the preprocessor definition: NO_PROMPT_ON_HRCHECK_FAILURE in the Conditional Defines of the project options.

  4. When using any Dart control that includes ErrorConstants, a compiler error for ambiguity between namespace conflicts may occur. You will need to physically modify the wrapper code for BCB3 and remove one of the ErrorConstants definitions or make some other such change. In BCB4, the ambiguity error is only generated if implementing the Error event.

To get around this and not modify the wrapper code: modify the client source to force the namespace in front of the ErrorConstants in the Error event in the .h and .c files like such:

void __fastcall TfrmMain::Telnet1Error(TObject *Sender,

Darttelnet_tlb::ErrorConstants Number, BSTR Description)

The IDE will complain every time a build is made with the popup: "The Telnet1Error method referenced by Telnet1->OnError has an incompatible parameter list. Remove the reference?" Always select "NO", otherwise the IDE will unlink the event and it will never occur at runtime.

This can be permanently fixed by modifying the ill-generated wrapper code in the components package where the control resides.


Delphi4

Delphi 4 Environment

The Delphi 4 samples in this toolkit were compiled with the Delphi 4.0 - Update 3

IMPORTANT - WHAT TO DO AFTER GETTING A SERIAL NUMBER

If you originally added your PowerTCP components during the trial period, you will need to remove and read the components after getting your serial number. Follow the directions below for removing the components, then follow the directions to read them. The next time you recompile your application, the correct runtime license will be inserted.

Using the Sample Applications:

Before you can use the sample applications you MUST add the PowerTCP Tools that are in the sample to the Component Library. See below for instructions.

Delphi Specific Problems

Delphi seems to have trouble recreating the DFM while our controls are displaying their trial license splash message. If you consistently get an error when loading the project, try loading Delphi before loading the project, as opposed to clicking on the DPR.

Adding PowerTCP Tools into the Component Library:

  1. Start Delphi4 and close any open projects.

  2. From the Main Menu choose Component | Import ActiveX Control.

  3. Choose the Tool to install:

Examples:

  • Dart FTP Control

  • Dart Telnet Control

  • Dart Server Control

  4. Click the 'Install' Button.

  5. Use the default dclusr40.dpk and click 'OK'.

  6. Answer 'Yes' to the rebuild.

  7. When the rebuilding process is done, close Delphi4 saving the changes to dcluser.

Removing PowerTCP Tools from the Component Library:

  1. Start Delphi4 and Close any open projects.

  2. Open the project where installed the controls. This is usually Lib\dclusr40.dpk.

  3. Remove the dcr and cpp for the Control you wish to remove.

  4. Re-Compile the library.

  5. Close Delphi4.

To ensure that all traces of the controls are removed from the library, delete the relevant source files from the Imports directory.

What To Do When Your Distributed App Displays a Trial Message:

This usually means that you originally added your PowerTCP components during the trial period and you did not remove and read the components. Follow the directions above for removing the components, then follow the directions to read them. The next time you recompile your application, the correct runtime license will be inserted.


Delphi5

Delphi 5 Environment

The Delphi 5 samples in this toolkit were compiled with the Delphi 5. If you use any other version of Delphi, or Delphi 5 with a service pack, you may have to modify the samples to get them to compile. This is because Borland changes the naming convention in the wrappers they create with each update.

IMPORTANT - WHAT TO DO AFTER GETTING A SERIAL NUMBER

If you originally added your PowerTCP components during the trial period, you will need to remove and read the components after getting your serial number. Follow the directions below for removing the components, then follow the directions to read them. The next time you recompile your application, the correct runtime license will be inserted.

Using the Sample Applications:

Before you can use the sample applications you MUST add the PowerTCP Tools that are in the sample to the Component Library. See below for instructions.

Delphi Specific Problems

Delphi seems to have trouble recreating the DFM while our controls are displaying their trial license splash message. If you consistently get an error when loading the project, try loading Delphi before loading the project, as opposed to clicking on the DPR.

Adding PowerTCP Tools into the Component Library:

  1. Start Delphi5 and close any open projects.

  2. From the Main Menu choose Component | Import ActiveX Control.

  3. Choose the Tool to install:

Examples:

  • Dart FTP Control

  • Dart Telnet Control

  • Dart Server Control

  4. Click the 'Install' Button.

  5. Use the default dclusr50.dpk and click 'OK'.

  6. Answer 'Yes' to the rebuild.

  7. When the rebuilding process is done, close Delphi5 saving the changes to dclus.

Removing PowerTCP Tools from the Component Library:

  1. Start Delphi5 and Close any open projects.

  2. Open the project where installed the controls. This is usually Lib\dclusr50.dpk.

  3. Remove the dcr and cpp for the Control you wish to remove.

  4. Re-Compile the library.

  5. Close Delphi5.

To ensure that all traces of the controls are removed from the library, delete the relevant source files from the Imports directory.

What to do When Your Distributed App Displays a Trial Message:

This usually means that you originally added your PowerTCP components during the trial period and you did not remove and read the components. Follow the directions above for removing the components, then follow the directions to read them. The next time you recompile your application, the correct runtime license will be inserted.


FoxPro

Visual FoxPro Environment

The Visual FoxPro Samples in this toolkit were compiled using Visual FoxPro 6.0 with SP3

Using the Samples

  1. Open the project's .pjx with FoxPro.

  2. Say "yes" to moving the project.

  3. From the Project Manager choose Document | Forms | Main.

  4. Press the "Run" Button.


Pb6

PowerBuilder Environment

The PowerBuilder Samples in this toolkit were compiled with PowerBuilder 6.5.

At the time this file was written, we were using build 585 EBF (Emergency Bug Fix) of the PowerBuider DLLs. This build is required to use most parts of PowerTCP Tools. If the build is not shipping by the time this toolkit is released, you will need to contact Sybase to obtain these updated DLLs.

The PowerBuilder samples are in <ROOT>\Samples\Pb6

Using the Sample Apps:

Due to the fact that PowerBuilder caches run-time licenses, there are some steps that you must take before you can run the samples apps. When you load the sample for the first time, you will need to:

  1. Copy and paste each Dart control to a new control.

  2. Delete the old control.

  3. Rename the new control to the original name.

Tips:

If you begin development of your project while in the trial period, the trial license will persist in the project. To remedy this problem:

  1. Install the valid license.

  2. Copy and paste each Dart control to a new control.

  3. Delete the old control.

  4. Rename the new control to the original name.

Inserting PowerTCP Tools

  1. Choose "Controls" from the Window Painter menu.

  2. Choose "OLE".

  3. Click the "Insert Control" Tab.

  4. Choose the Tool you wish to insert.

Examples:

  • Dart FTP Control

  • Dart Telnet Control

  • Dart Server Control

Environment Specific Quirks

Telnet Only: Cmd Event not supported due to passing of Variant Pointer.


Vb5

Visual Basic 5 Environment

The Visual Basic 5 Samples in this toolkit were compiled using Visual Basic 5.0 with Service Pack 3.

PowerTCP may not work properly without Service Pack 3, so if you experience problems, please install it before contacting support.


Vb6

Visual Basic 6 Environment

The Visual Basic 6 Samples in this toolkit were compiled using Visual Basic 6.0 with SP3 with the exception of the XMLDatabaseDemo in the WebServer Tool. In order to use that sample you must also install the following updates:

h ttp://www.microsoft.com/data/download_25SP1.htm

http://msdn.microsoft.com/downloads/default.asp?URL=/code/sample.asp?url=/msdn-files/027/001/469/msdncompositedoc.xml


Vc6

Visual C++ 6.0 Environment

Samples that use Dart's Class Wrapper

Some of the sample applications were created using a wrapper that was written by Dart. The following is a list of these samples:

Emulation Tool

  • VT Emulator (wrapper for Telnet control only, uses MFC for VT control)

FTP Tool

  • GetUrl

  • ListView Client

Mail Tool

  • SMTP Client

  • IMAP Client

  • POP Client

  • SMTP Quicksend Client

Winsock Tool

  • TCP Client

  • UDP Client

  • TCP Blaster

  • DNS Client

  • Ping Client

  • DartChat

  • WebServer

Server Tool

  • EchoServer

SNMP Tool

  • SNMP Agent

  • SNMP VarChecker

  • MibViewer

  • SNMP Manager

Telnet Tool

  • Telnet Client

  • AutoLogin Demo

Web Tool

  • PageFetch

Web Enterprise Tool

  • PageFetch

These samples require no additional effort to compile and run.

A trial message will appear periodically while on the trial period.

To eliminate the trial message after you have purchased the Tool, follow these steps:

Find your license number in the registry under:

HKEY_LOCAL_MACHINE\SOFTWARE\Dart\PowerTCP\License\<Tool>

Use the value found there for the value of LICENSE:

Example:

#define LICENSE "Number:UnlockCode:CompanyName"

Executables compiled with a valid number will not display a trial message.

Samples Where PowerTCP Controls are Inserted Using MFC Appwizard

If you insert a control during your trial period and later register you will have to follow these steps to get the new license info into your project:

  1. Open the Project.

  2. Open the Window the control is on and remember it's resource ID.

  3. Delete the control and it's Resource ID.

  4. Build clean and let the error's happen.

  5. Reinsert the control and give it the same Resource ID.

The samples are supplied without any Dart controls. You will need to drop the controls onto dialog forms inside the projects as follows:

RAS Client

Load the Ras Simple Client project into VC, bring up the IDD_RAS dialog into the dialog editor. Insert a Dart Ras Control onto the form. Uncheck the Visible flag. Bring up the IDD_VCRAS_DIALOG dialog into the dialog editor. Insert a Dart Ras Control just below the "Phonebook Entry:" Caption, and set its width to fill the Connection GroupBox.

SNMP Explorer Sample

Load the SNMPExplorer Sample project into VC, bring up the IDD_SNMPEXPLORER_DIALOG dialog into the dialog editor. Insert a Dart Manager Control onto the form.

VT Emulator

Load the Emulator Client project into VC, bring up the IDD_TELNET_FORM dialog into the dialog editor. Insert a Dart Vt Control onto the form.

SecureEchoServer

Load the SecureEchoServer project into VC, bring up the IDD_CERT dialog into the dialog editor. Insert a Dart CertificateList Control onto the form. MAKE SURE YOU USE THE /A PARAMETER TO RUN THE SERVER AS AN APP!

SecureClient

Load the SecureClient project into VC, bring up the IDD_CERT dialog into the dialog editor. Insert a Dart CertificateList Control onto the form.


PowerTCP Emulation Tool

Support Licensing Distribution

Build terminal emulation capabilities into your application with this visual VT52/100/220/320 control. The Telnet Control is also included. Screen scraping, advanced graphic fonts, and superior printing capabilities make this tool suitable for your most demanding requirements.

Use the Telnet Control to manage Telnet, Rsh, Rexec and Rlogin connections. Blocking use is suited for hidden scripting applications, and non-blocking can be easily enabled for interactive, high-performance, event-driven communications. Option negotiation (automatic and custom) is fully supported.

Controls

Control | Description
Telnet Control | Manages Telnet, Rexec, Rsh, and Rlogin sessions.
VT Control | Concise visual VT-320 display viewing, including invisible screen–scraping.

Sample Projects

The following sample project demonstrates how to use the Emulation Tool (Visual Basic, Visual C++, Delphi, and C++Builder):

Project | Description
Data Capture | Demonstrates how to use the VT Control with the aid of the Telnet control, to access data from either a local file, or a UNIX box. Once the file is accessed, it is sent to the VT Control to strip out the escape sequences. Then the data is extracted from the VT Control and sent to an Excel Application. Visual Basic 5/6
VT Emulator | Demonstrates a simple VT320 Emulation application written using non-blocking techniques. The VT Control is used for viewing and keyboard entry.


DartStream Object

Properties Methods Constants Example

Use the DartStream Object to manage a streamed buffer to/from memory or a file.

Miscellaneous

Product | All PowerTCP Tools
Prog ID | Dart.DartStream.1
Create | Yes
File | DartSock.dll
Dependencies | None
Threading | Apartment Model
Licensed | No


DeleteOnDestroy Property

Example

Specifies if the corresponding file should be deleted when the object is destroyed.

Syntax

Object.DeleteOnDestroy

Part | Description
Object | Evaluates to a DartStream Object.

Data Type

Boolean

Remarks

WARNING USE WITH CAUTION!

When set to True and FileName specifies a file, the file is deleted when this object is destroyed.


FileMode Property

How the file is to be created or opened.

Syntax

Object.FileMode

Part | Description
Object | Evaluates to a DartStream Object.

Data Type

FileModeConstants

Remarks

Set this property prior to changing FileName to determine how the file is created.


FileName Property

Example

Intended name of the file.

Syntax

Object.FileName

Part | Description
Object | Evaluates to a DartStream Object.

Data Type

String

Remarks

When set to a file name, the file is opened. When set to an empty string, the file is closed.

When set to an empty string and then changed to a file name, a file is created or opened according to FileMode. If an existing file is opened, the value of the Size property determines how the file is treated:

  • If Size = 0 when the file is opened, it is assumed the file is being opened for reading, and Size is set to the size of the file.

  • If Size > 0 when the file is opened, it is assumed the file is being opened for writing, and the existing contents of the file are replaced.

When set to a file name and then changed to an empty string, all data in the file is buffered to memory and the file is closed.

When set to a file name and then changed to a different file name, the file is moved to the new location. If FileMode = createUnique, an existing file cannot be unintentionally overwritten.

You can delete a file only by setting this property to an existing file name, setting FileMode to createOpen or createExisting, setting DeleteOnDestroy to True, and allowing the DartStream Object to be destroyed.


Position Property

Example

Current byte position in the stream.

Syntax

Object.Position

Part | Description
Object | Evaluates to a DartStream Object.

Data Type

Long

Remarks

The Read and Write methods use this starting position. This property can be set to any value between 0 and Size. Position is initialized to 0 when the buffer is empty.


Ref Property

Stores a reference to another object, data type, or value.

Syntax

Object.Ref

Part | Description
Object | Evaluates to a PowerTCP object.

Data Type

Variant

Remarks

This property is available only at run time.

Use this property to associate the control with any Variant. If the data type is String, Ref stores a copy of the string. If the data type is a Byte array, it stores a copy of the Byte array. If the data type is an object, it increases the reference count of the object.

When Object is destroyed, and Ref holds an object reference, that object's reference count is decremented.


Size Property

Example

Size of the stream in bytes.

Syntax

Object.Size

Part | Description
Object | Evaluates to a DartStream Object.

Data Type

Long

Remarks

Read-only.


UniqueName Property

Name of the file currently open.

Syntax

Object.UniqueName

Part | Description
Object | Evaluates to a DartStream Object.

Data Type

String

Remarks

Read-only.

This property is usually the same as FileName, but is different when FileMode property is createUnique and FileName already exists. In this case, a period and a number (starting at 1) is appended to FileName and saved as this property.


Clear Method

Example

Clear the stream.

Syntax

Object.Clear

Part | Description
Object | Evaluates to a DartStream Object.

Remarks

WARNING USE WITH CAUTION!

This method sets Size and Position to 0. ALL DATA IS PERMANENTLY LOST!

Error Codes

The Clear method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1

  • ptInvalidParam2

  • ptNoBufferSpace


Read Method

Example

Read one or more bytes from the stream. Reading starts at the Position property. Set Position to change the position.

Syntax

ReturnCount = Object.Read Buffer [ , Count ]

Part | Description
Object | Evaluates to a DartStream Object.
Buffer | Uninitialized String or Byte Array. Where data is to be put.
Count | Optional Long. Specifies how much data is to be read.
ReturnCount | Returned Long. Indicates how much data was read.

Remarks

If the Buffer parameter is omitted, then this method attempts to read all the data from the current position to the end of the stream. The position is advanced Count bytes upon completion.

Error Codes

The Read method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1

  • ptInvalidParam2

  • ptNoBufferSpace


ReadBytes Method

Example

Return data from the current position as a Byte Array. Reading starts at the Position property. Set Position to change the position.

Syntax

Data = Object.ReadBytes [ Count ]

Part | Description
Object | Evaluates to a DartStream Object.
Count | Optional Long. Specifies how much data is to be read.
Data | Returned Byte Array. Indicates how much data was read.

Remarks

Some environments, such as JavaScript, do not support the passing of parameters by reference. Consequently, such methods as Receive cannot be used by passing in a String. You can use the DartStream Object to circumvent this limitation (see the ReadString method Remarks section for a Java sample).

Error Codes

The ReadBytes method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1

  • ptInvalidParam2

  • ptNoBufferSpace


ReadString Method

Example

Return data from the current position as a String. Reading starts at the Position property. Set Position to change the position.

Syntax

Data = Object.ReadString [ Count ]

Part | Description
Object | Evaluates to a DartStream Object.
Count | Optional Long. Specifies how much data is to be read.
Data | Returned String. Indicates how much data was read.

Remarks

Some environments, such as JavaScript, do not support the passing of parameters by reference. Consequently, such methods as Receive cannot be used by passing in a String. You can use the DartStream Object to circumvent this limitation, as shown in the following Java sample:

<% @LANGUAGE="JScript"%>

<%

var Tcp = Server.CreateObject("Dart.Tcp.1");

Tcp.TimeOut = 30000;

Tcp.Connect("www.microsoft.com", 80);

Tcp.Send("GET / HTTP/1.0\r\n\r\n");

var Stream = Server.CreateObject("Dart.DartStream");

while(Tcp.State != 0)

Tcp.Receive(Stream);

Stream.Position = 0;

Response.Write(Stream.ReadString());

%>

Error Codes

The ReadBytes method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1

  • ptInvalidParam2

  • ptNoBufferSpace


Write Method

Example

Write one or more bytes to the stream. Writing starts at the Position property. Set Position to change the position.

Syntax

ReturnCount = Object.Write Buffer [ , Count ]

Part | Description
Object | Evaluates to a DartStream Object.
Buffer | Initialized String or Byte Array. Where data is being written from.
Count | Optional Long. Specifies how much data is to be written.
ReturnCount | Returned Long. Indicates how much data was written.

Remarks

If the Count parameter is omitted, then this method writes the entire contents of the Buffer parameter. After the data is written the Position is advanced Count bytes.

Error Codes

The Write method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1

  • ptInvalidParam2

  • ptNoBufferSpace


FileModeConstants

Enumerates values of the FileMode property:

Value | Constant | Description
0 | createAlways | If the file exists, replace the file. If the file does not exist, create the file.
1 | createExisting | If the file exists, open the file. If the file does not exist, throw an error.
2 | createUnique | If the file exists, create a file with a unique name (a period and a number are appended to the filename). If the file does not exist, create the file.
3 | createOpen | If the file exists, open the file. If the file does not exist, create the file.


Telnet Control

Properties Methods Events Constants

Use the Telnet Control to manage Telnet, Rsh, Rexec and Rlogin connections. This control simplifies the process of using these protocols by providing methods to establish, use, and terminate sessions. By default, communications block execution of your program; however, you can enable non-blocking use for applications using event-driven communications. Option negotiation automatically defaults to a standard set, but complete control of option negotiation is supported.

Miscellaneous

Product | PowerTCP Emulation Tool , PowerTCP Telnet Tool
Prog ID | Dart.Telnet.1
File | DartTelnet.dll
Dependencies | DartSock.dll
Threading | Apartment Model
Licensed | Yes


Telnet Control Usage

Telnet applications fall into two primary classes:

  • Interactive terminal applications. For these applications the Timeout property should be set to 0, and all communications should trigger off events. When data arrives, the Receive event fires and the Receive method should be used to access data, which may then be placed into a visual control. When the user types into a visual control, that event must be captured and the ASCII character (byte) should be sent over the connection. Sample interactive applications are included with the TCP Control and the Telnet Control to illustrate this application class.

  • Transparent operations. For transparent use the developer may find it convenient to set the Timeout property to a positive number and perform all processing using inline code with no user feedback. In a few short steps, the application can connect to the Telnet server, authenticate, generate a report, capture the report, and display the report to the user in any desired format.

The following steps illustrate the ease of use of the Telnet Control:

  1. Connect to the Telnet server with the Connect method.

  2. Send data to the remote host with the Send method.

  3. Receive and process data from the remote host with the Receive or Search methods. These methods receive data in slightly different ways, depending upon your requirements.

  4. Close the connection with the Close method.


Telnet Protocol Overview

This topic covers:

  • Protocol Overview

  • Telnet Connections

  • Network Virtual Terminal

  • Binary Data

  • Option Negotiation

Protocol Overview

Telnet is a data communications protocol—a set of rules for communications between computers. Telnet stands for Telecommunications Network Protocol. Telnet communication works between different types of computers and operating systems because the protocol is the same for all systems. Telnet is often used for remote login—accessing one computer from another. A typical Telnet application would use the Telnet protocol to move data between a terminal emulator and a UNIX server (host).

Many host computers support the Telnet protocol. The main use is online terminal communications; you can use Telnet to log in to a remote computer and issue commands just as if you were at the remote computer itself. You can also use Telnet to access remote databases, control other computers, distribute work among multiple computers, and remotely execute many applications.

Telnet is similar to TCP; in fact, it is built upon it. Telnet provides additional features that make it an upper-layer protocol. Using Telnet, both ends of a connection send data to each other. Typically, a terminal sends commands to a host, and the host responds with messages or data. For example, a user at a terminal may type "help" and the host may respond with "Type a command to get help on".

Telnet provides option negotiation as a method for establishing conventions between two computers. During a session, either computer may send the other a command, requesting or volunteering a specific option. A typical option is echoing. The process of option negotiation determines if either computer will support echoing.

Back to Top

Telnet Connections

Connections are made on a port, which is a method of distinguishing multiple communications on a single computer. Most Telnet connections are made to port 23, the standard Telnet port.

To make a connection you must specify a port and host name or address to connect to. All computers on a network have an IP address, a number that distinguishes them from other computers. All IP addresses have the following same format:

nnn.nnn.nnn.nnn

where each nnn is a number from 0 to 255 (except for the first n, which may be from 0 to 247).

A typical IP address might be 129.229.1.2. Most networks also support computer names, where the network will translate a name (such as "server3") into an IP address.

Back to Top

Network Virtual Terminal

The Network Virtual Terminal (NVT) is a concept Telnet uses to represent both computers in a connection. The NVT is an imaginary character-based device with a keyboard and a printer (input and output). Incoming data goes to the printer, and input from the keyboard goes to the other end of the Telnet connection. Both ends of a Telnet connection must support the concept of an NVT.

The NVT supports the 7-bit character set known as NVT ASCII. NVT ASCII is the same as normal ASCII text, except that only 7 bits represent the character. The eighth high bit of the byte must be set to 0. In NVT ASCII, an end of line is represented by a two-character sequence CR, LF (carriage return, linefeed).

Both ends of a Telnet connection map their own terminal device characteristics to and from the NVT. For example, a program must change all 8-bit ASCII characters to the NVT character set. The NVT is intended to strike a balance between being overly restrictive (not providing some computers a rich enough vocabulary for mapping into their local character sets) and being overly inclusive (penalizing users with modest terminals).

Please refer to RFC 854 for more information on the NVT.

Back to Top

Binary Data

PowerTCP provides full support for binary data transmission. The Send method applies the following basic Telnet encoding rules:

  • Every byte of value 255 (IAC) is doubled up into a two-byte (255, 255) value.

  • Every byte of value 13 (CR) not followed by a byte of value 10 (LF) is transformed into a two-byte (13, 0) value.

Suboption negotiation strings sent by the SendCommand method provide a similar encoding for the IAC. For all data received, the reciprocal transformation takes place within the Telnet Control. This mechanism, established by RFC 854, enables the transmission of 8-bit binary data over a single Telnet channel.

Back to Top

Option Negotiation

Option negotiation is the process of two computers agreeing on what features they will or will not provide. Each computer may send a command to the other, and each may respond to commands. A typical option negotiation session may occur as follows (although over 40 different options might be negotiated):

Computer A | Computer B
1. I will echo back what you send to me. |
 | 2. OK, Do echo back what I send to you.
 | 3. Do suppress go–aheads.
4. No, I won't suppress go–aheads. |
 | 5. Don't suppress go–aheads.
6. OK, I won't suppress go–aheads. |

Either computer may initiate option negotiation. One computer may request that the other computer support or not support an option, or that it will or won't support an option. The other computer may then respond that it will or won't support an option, or request that the other computer support or not support an option. The following table describes the four option negotiation commands:

Command | Description
WILL | The sender wants to support the option
WONT | The sender will not support the option
DO | The sender wants the receiver to support the option
DONT | The sender wants the receiver to not support the option

The different pairs of commands and responding commands follow:

Command | Response
WILL I will support this option | WILL I will support this option
WILL I will support this option | DONT No, don't support it
WONT I won't support this option | DONT OK, don't support it
DO Do support this option | WILL OK, I will support it
DO Do support this option | WONT No, I won't support it
DONT Don't support this option | WONT OK, I won't support it

Note If a computer does not want an option supported (WONT/DONT), then the other computer must comply, responding with a DONT or WONT.

Telnet also provides suboption negotiation—negotiating details about a specific option. An example is the "terminal type" option. For both computers to decide to support the same terminal type, instead of using a different option for each individual terminal type, use a suboption. A typical suboption negotiation is shown below:

Computer A | Computer B
1. I will support different terminal types. |
 | 2. OK, Do support different terminal types.
3. OK, send your terminal type suboption. |
 | 4. My terminal type suboption is "IBMPC".

Option negotiation and suboption negotiation make Telnet very flexible and adaptable to many different terminal configurations. Refer to the applicable RFCs for more information on Telnet and Telnet option negotiation.

Back to Top


Telnet Control Non-Blocking Sample

For interactive applications, set the Timeout property to 0 so communications can occur asynchronously as data arrives and as the user types at the keyboard.

This VB example shows how to establish a Telnet connection and illustrates the two events that fire to indicate that data needs to be displayed or sent.

Private Sub Command1_Click()

Telnet1.Timeout = 0

Telnet1.Connect "catalogue.library.ubc.ca"

End Sub

Private Sub Telnet1_Receive()

Dim s() As Byte

Dim r As Long

' when data arrives, receive it and put it into the VT Control

r = Telnet1.Receive(s)

If r > 0 Then

Vt1.Display s

End If

End Sub

Private Sub Vt1_KeyPress(KeyAscii As String)

' Make sure the user is connected, or else don't

' display the character

If Telnet1.State = tcpConnected Then

' when user hits a key, send the Ascii value to the host

Telnet1.Send KeyAscii

End If

End Sub


Telnet Control Blocking Sample

This VB sample illustrates how to connect to a Telnet server, authenticate, issue a command, receive the reply, and close the connection.

Private Sub Command1_Click()

Dim Data As String

Dim Count As Long

' Set Timeout to 5000 milliseconds to wait on communications

Telnet1.Timeout = 5000

' establish a connection to a Telnet server

Telnet1.Connect "myhostname"

' wait for login prompt

Count = Telnet1.Search(Data, "Login: ")

' send my Username

Telnet1.Send "user" & vbCrLf

' wait for the password prompt&ldots;

Count = Telnet1.Search(Data, "Password:")

' send my password

Telnet1.Send "mypassword" & vbCrLf

' wait for the shell prompt

Count = Telnet1.Search(Data, "$ ")

' run a report application

Telnet1.Send "myreport" & vbCrLf

' get the report output; terminates with a double line

Count = Telnet1.Search(Data, vbCrLf & vbCrLf)

Text1.Text = Data ' put the report into an text box for viewing

' close the connection

Telnet1.Close

End Sub


AutoOption Property

Enables automatic Telnet option negotiation.

Syntax

Object.AutoOption

Part | Description
Object | Evaluates to a Telnet Control.

Data Type

Boolean

Remarks

The default value is True.

When set to True, the Telnet Control automatically negotiates the following options (all other Telnet options are refused):

  • DO ECHO The host normally desires to echo Telnet data it receives back to the client. The client responds with the value of the Echo property.

  • DO SUPPRESS GO-AHEADS The host normally has no need to send GO-AHEAD commands.

  • WILL SUPRESS GO-AHEADS The client normally has no need to send GO-AHEAD commands.

  • WILL TERMTYPE The client responds with the terminal emulation type specified in the TermType property.

  • WILL WINDOW_SIZE The client responds with the window size specified in the WindowSize property.

When set to False, the developer has complete control and must respond to arriving options in the Command event by using the SendCommand method to send Telnet command replies.


Blocked Property

A True value indicates the control is currently executing a blocking method (Timeout is greater than 0), which has neither completed nor timed out with a ptTimeout error.

Syntax

Object.Blocked

Part | Description
Object | Evaluates to a PowerTCP control.

Data Type

Boolean

Remarks

Read-only.

Check this property to prevent your application from prematurely exiting or destroying the control while it is blocking in a method.

Your application still processes normal Windows messages while blocked, and the user interface continues to function normally. Events still fire while blocked, so code placed in these events continues to execute.

Your application cannot execute another method (except the Abort method) while it is blocked; a ptBlocked error is generated. Use the Abort method to terminate a blocked method prematurely. Abort signals the blocked method to abort, and then returns. Shortly thereafter, the blocked method releases all system resources, calls the State event (with the object's State property set to ptClosed), and returns with the ptAbort error.

WARNING Terminating your application or destroying the TCP object while blocked in a method may cause a fatal application error. To prevent this, perform either of the following:

  • Only allow object destruction if the Blocked property returns False.

  • Never use a positive Timeout value.


Echo Property

Example

Indicates that the remote host should echo all Telnet data it receives back to the client.

Syntax

Object.Echo

Part | Description
Object | Evaluates to a Telnet Control.

Data Type

Boolean

Remarks

The default value is True.

Most hosts will want to echo all data back to the client. By setting this property to False at design time or before connecting, the control refuses this option when the AutoOption property is True. Setting this property after the initial option negotiation takes place may not affect the host in any way depending on the host's operating system. If you set this property to False, you may want to do a local echo (repeat all sent characters to the local screen for interactive applications).


KeepAlive Property

When set to True, the KEEPALIVE socket option is set to monitor dropped connections. This option can only be set when the State property is tcpConnected.

Syntax

Object.KeepAlive

Part | Description
Object | Evaluates to a PowerTCP control.

Data Type

Boolean

Remarks

The default value is False.

This property is only available at run time. Registry entries are required for some TCP/IP stacks (such as Microsoft) to enable this mechanism.


LocalAddress Property

For the following controls (FTP Control, SecureFtp Control, SecureTcp Control, TCP Control, Telnet Control, Web Control, WebASP Control), when the State property is tcpConnected, LocalAddress returns the address of the local host in dot notation (for example, nnn.nnn.nnn.nnn). When not connected, it returns an empty string.

For the following controls (Daemon Control, FtpServer Control, SecureFtpServer Control, SecureServer Control, Server Control, WebServer Control), LocalAddress returns the address in use while the Daemon is active and an empty string when the Daemon socket is closed.

For the Agent Control, Manager Control, and UDP Control, LocalAddress returns the address in use while the socket is active and an empty string when the UDP socket is closed.

Syntax

Object.LocalAddress

Part | Description
Object | Evaluates to a PowerTCP control.

Data Type

String

Remarks

Read-only.

The LocalPort property identifies the corresponding local port in use. The LocalAddress, LocalPort, Request.Url, and Request.UrlPort properties uniquely define every TCP connection on the Internet.


LocalPort Property

For the following controls (FTP Control, SecureFtp Control, SecureTcp Control, TCP Control, Telnet Control, Web Control, WebASP Control), when the State property is tcpConnected, LocalPort returns the port number that the socket is bound to. When not connected, it returns 0.

For the following controls (Daemon Control, FtpServer Control, SecureFtpServer Control, SecureServer Control, Server Control, WebServer Control), LocalPort returns the port number in use while the Daemon is active and 0 when the Daemon is closed.

For the Agent Control, Manager Control, and UDP Control, LocalPort returns the port number in use while the socket is active and 0 when the socket is closed. When the Protocol property of the UDP Control is not ptUdp, LocalPort returns 0.

Syntax

Object.LocalPort

Part | Description
Object | Evaluates to a PowerTCP control.

Data Type

Long

Remarks

Read-only.

When active, values are between 1 and 65,535. The LocalAddress, LocalPort, Request.Url, and Request.UrlPort properties uniquely define every TCP connection on the Internet.


ReceiveBufferCount Property

Checks for the existence of data without removing it.

Syntax

Object.ReceiveBufferCount

Part | Description
Object | Evaluates to a PowerTCP control.

Data Type

Long

Remarks

Read-only.

Data is collected in system buffers and must be removed using the Receive method, Search method, or Fill method. The Receive event fires to indicate that data is available. The value increases as data arrives and is collected in system buffers. The value decreases as your application calls the Receive method, Search method, or Fill method to remove data. If these methods are not invoked or are seldom invoked, then "back pressure" will be exerted at the remote host and packet transmission rates will decrease.

Windows95 Note If the Winsock2 update is not installed, then this value may not accurately reflect the number of bytes available in the system buffers (it may be high). This behavior has been seen under high-throughput conditions. Refer to PowerTCP Distribution for more information.


RemoteAddress Property

Returns the address of the remote host in dot notation (i.e. nnn.nnn.nnn.nnn) when the State property is tcpConnected.

Syntax

Object.RemoteAddress

Part | Description
Object | Evaluates to a PowerTCP control.

Data Type

String

Remarks

Read-only.

When not connected, RemoteAddress returns an empty string. The LocalAddress, LocalPort, RemoteAddress, and RemotePort properties uniquely define every TCP connection on the Internet.


RemotePort Property

Returns the port number of the remote host when the State property is tcpConnected.

Syntax

Object.RemotePort

Part | Description
Object | Evaluates to a PowerTCP control.

Data Type

Long

Remarks

Read-only.

When not connected, it returns a 0. When active, values are between 1 and 65,535. The LocalAddress, LocalPort, RemoteAddress, and RemotePort properties uniquely define every TCP connection on the Internet.


SendBufferCount Property

When the Send method is used, some data may be stored in a buffer and later submitted to the system. The Send event fires to indicate that the system has accepted the submitted data.

Syntax

Object.SendBufferCount

Part | Description
Object | Evaluates to a PowerTCP control.

Data Type

Long

Remarks

Read-only.

Between the time the Send method is called and the Send event fires, SendBufferCount has a positive value that indicates how many bytes are currently in this queue.

The value increases each time the Send method is invoked with data to send. The value decreases immediately before the Send event fires. It is possible to queue up significant amounts of data by submitting large buffers; your application can adversely impact system performance by submitting megabytes of data in a short period of time.


Socket Property

Example

System identifier assigned to the TCP connection. It is normally used to assume management of an accepted socket from the Daemon Control.

Syntax

Object.Socket

Part | Description
Object | Evaluates to a TCP Control.

Data Type

Long

Remarks

This property is only available at run time.

A value of –1 indicates that no system resource is currently allocated. It is possible, but not recommended, to transfer Socket values between controls. Refer to the Accept method for more information.

CAUTION The Timeout property must be set to 0. This will ensure that all event notification operates without interference from individual connections that may capture the thread under blocking operation.

Error Codes

The Socket property may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptInvalidParam1 (assigned value is not a valid system socket identifier)


State Property

Provides status information to the user interface. The State event fires to signal that this property has changed.

Syntax

Object.State

Part | Description
Object | Evaluates to a PowerTCP control.

Data Type

StateConstants

Remarks

Read-only.

To protect you from programming errors, most methods return an error condition if your code attempts to send data when no TCP connection exists. By checking the value of this property, your application can always determine the state of the connection.

This property is exposed by most TCP-based controls.


TermType Property

Example

Specifies the desired terminal type when the AutoOption property is True.

Syntax

Object.TermType

Part | Description
Object | Evaluates to a Telnet Control.

Data Type

String

Remarks

Many hosts send a terminal type request shortly after a Telnet connection is established. By setting this property at design time or before connecting, the control responds with this value when the AutoOption property is True. If the host refuses to negotiate the terminal type, this property returns "".

Setting this property after the initial option negotiation takes place may not affect the host in any way, depending on the host's operating system.

If the server does not support this option, this property returns "" after it has been refused. Likewise, to refuse this option, set this property to "".


Timeout Property

Controls the blocking behavior of methods that can be used in blocking and non-blocking ways.

Syntax

Object.Timeout

Part | Description
Object | Evaluates to a PowerTCP object.

Data Type

Long

Remarks

The default value is 30000 (30 seconds) for all controls except the Daemon Control, which defaults to 0 (non-blocking). This is a design-time property.

Most users will start using blocking operation. The developer's decision to use blocking (Timeout > 0) or non-blocking (Timeout = 0) operation is important; these controls were designed to consistently support both methods of operation.

When set to a positive number of milliseconds, methods block while waiting for the initial response from the method. For example, an FTP or HTTP Get() method on a file will block until response is received. The Blocked property indicates this state. For example, if the Connect method is used with a Timeout of 30000, then the method only returns without error if the connection is established within 30 seconds. This is the easiest design to implement, but not the most robust. If the user attempts to initiate a different method while the Blocked property is True, an error is generated. Also, if the user attempts to close the application while the Blocked property is True, abnormal program termination may result.

When set to 0, no method blocks. It is up to the application to sense the success or failure of the operation by putting code in the related event. For example, if the Connect method is used with a Timeout of 0, then the application can test for the value of the State property from within the State event. This is the most efficient technique, as no idle loops are used to capture the thread of execution waiting for an event to occur. This is also the safest way to use PowerTCP because non-blocking use allows PowerTCP to unload gracefully under any condition.

The novice will probably use blocking operation first because this is the easiest way to immediately use the product. With no explicit error handling enabled (for example, the VB OnError statement), methods return errors into the environment and program execution stops. Once you add error-handling code, most applications will work satisfactorily. While the thread is captured in the method, an idle loop processes Windows messages and few side effects will ever be noted. There are some limits, however, that you should be aware of:

  • The only way to abort a blocking method is to call the Abort method off a Timer or some user interface event.

  • With the exception of the Abort method, the developer can only be in one method at a time (this protects your program from reentrancy problems).

  • If the user closes the application while PowerTCP is blocking, the blocking method attempts to return when this is sensed, but a general protection fault may still be experienced (because the application is being terminated while PowerTCP is in an idle loop).

Non-blocking operations are more fault-tolerant. Set the Timeout property to 0 (at design time or at run time), initiate methods as desired, and insert most of your code in the appropriate event. This eliminates problems associated with reentrancy, users performing unanticipated actions in your application, and error recovery.


WindowSize Property

Specifies the desired window size when the AutoOption property is True.

Syntax

Object.WindowSize

Part | Description
Object | Evaluates to a Telnet Control.

Data Type

String

Remarks

Many hosts send a terminal window size request shortly after a Telnet connection is established. By setting this property at design time or before connecting, the control responds with this value when the AutoOption property is True. This property specifies the number of rows and columns as follows:

Telnet1.WindowSize = "24, 80" ' 24 rows by 80 columns is the default value

If the server supports this option, the window size can be set at any time during the session. If the server does not support this option, this property will return "". Likewise, if you want to refuse this option, set this property to "".


Abort Method

Abort any blocking method and release all system resources.

Syntax

Object.Abort

Part | Description
Object | Object expression that evaluates to a PowerTCP control.

Remarks

Use this method at any time to abruptly release all resources. The State property is tcpClosed when this method returns.

Destruction of the control automatically uses this method to release all resources.

When a blocking call is in progress (like Get), and Abort is called with an immediate call to a second Get (or other method), the first Get method does not return until the subsequent Get method(s) complete. It will return a ptAbort error.

Note For TCP-based controls, the Abort method performs a "hard close", with a socket LINGER option time of 0.

CAUTION Use the Close method in most cases, as buffers are cleared and communications terminate gracefully. Use the Abort method only when the application in abruptly terminated while a blocking method is executing or under any other unusual circumstances.


About Method

Show the About Box.

Syntax

Object.About

Part | Description
Object | Object expression that evaluates to a PowerTCP control.


Close Method

Example

Close the session and release all system resources. A single control can be used for many connections, one after the other.

Syntax

Object.Close

Part | Description
Object | Object expression that evaluates to a SecureTcp Control, TCP Control, or Telnet Control.

Remarks

Use this method only when the State property is tcpConnected; otherwise, a ptNotConnected error is generated.

If Blocked and you wish to cancel the blocking method and release resources, use the Abort method. The Abort method performs a "hard close", with a socket LINGER option time of 0. Using Close when another method is blocking results in a ptBlocked error.

If Timeout is greater than 0, then this method attempts to clear all buffers and performs a graceful close on the socket within the timeout period. The "close socket" system call blocks while closing. If the operation completes within the timeout period, then this method returns successfully. If the operation does not complete within the timeout period (if SendBufferCount is large, for example), then resources are immediately released and a ptTimeout error is generated.

If Timeout is 0, then a non-blocking "close socket" system call is used with the DONTLINGER option set.

The State property is tcpClosed when closing is complete.

Error Codes

The Close method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAbort

  • ptBlocked

  • ptNetworkDown

  • ptNotConnected

  • ptTimeout


Connect Method

Example

Establish a connection. The State property immediately changes to tcpConnecting and changes to tcpConnected when the connection is established. The State Property can be checked in the body of the State event, polled off a timer, or checked immediately after this method is used when a positive Timeout is specified.

Syntax

Object.Connect RemoteName [ , RemotePort ] [ , LocalName ] [ , LocalPort ]

Part | Description
Object | Object expression that evaluates to a Telnet Control.
RemoteName | String. Specifies either a host name (host.dart.com) or dot address (nnn.nnn.nnn.nnn).
RemotePort | Optional Long. Specifies a remote port between 1 and 65535, inclusive. Defaults to the well-known port 23.
LocalName | Optional String. Specifies the local network interface (either a host name, host.dart.com, or dot address, nnn.nnn.nnn.nnn). Not usually used.
LocalPort | Optional Long. Species the local port. Not usually used.

Remarks

This method blocks if Timeout is greater than 0. The Blocked Property property may be checked to verify the control is not executing another method.

Error Codes

The Connect method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1 (RemoteName is not a valid string)

  • ptInvalidParam2 (RemotePort is not between 1 and 65535, inclusive),

  • ptNotInitialized

  • ptNetworkDown

  • ptAddressInUse

  • ptHostNotFound

  • ptTryAgain

  • ptNoData

  • ptBlocked

  • ptAbort

  • ptAddressNotAvailable

  • ptConnectionRefused

  • ptNetworkUnreachable

  • ptNoBufferSpace

  • ptTimeout


Receive Method

See Also Example

Receive an arbitrary amount of data. The specified String or Byte array is filled with bytes from the remote host.

Syntax

[ Count = ] Object.Receive Data

Part | Description
Object | Object expression that evaluates to a SecureTcp Control, TCP Control, or Telnet Control.
Data | String,Byte array, or DartStream Object. Bytes from the network are copied into this variable.
Count | Optional Long. Returns the number of Unicode characters or bytes copied into the Data variable.

Remarks

You can use this method only when the State is tcpConnected or tcpClosing; otherwise, a ptNotConnected error is generated. When the State is tcpClosing, you can use the Receive, Fill, or Search methods to flush the buffer and cause the State to change to tcpClosed.

Data can be specified as a dimensioned or undimensioned String, Byte array, or DartStream Object:

  • A String of length greater than 0 or a dimensioned Byte array of length greater than 0 indicates that the existing contents should be overwritten with received bytes. The String or Byte array is not resized. When receiving data, the actual amount transferred never exceeds the size of the Data parameter, but the Count returned may indicate that only part of the String or Byte array contains received bytes. Note Count should always be checked because the size of the Data parameter does not indicate how many bytes or characters were actually received.

  • A String of length 0 or an un-dimensioned Byte array is resized to the length of the available data before received bytes are copied into it. The returned Count matches the new size of the String or Byte array. If the same Data variable is used on a successive call, the variable is considered to be of size greater than 0 and is not resized.

When Data is specified as a String, all bytes are converted to 16-bit Unicode characters according to the default ANSI code page specified on the system. If the code page is not ASCII, multi-byte characters convert to single Unicode characters. This is not as efficient as receiving into a large Byte array. The most efficient transfer is possible when a large global Byte array is allocated once, and all network data is repeatedly read into the same array (a single memory transfer takes place directly from the system buffers into the global Byte array allocated in the user's application).

If Timeout is greater than 0, the method completes without error if at least 1 byte is received (a positive Count is returned) or the remote host closes the connection (a 0 Count is returned). A ptTimeout error is generated if at least 1 byte cannot be received within the Timeout period and the connection is still ptConnected. If Timeout is 0, then Count indicates the length of the actual data received, and may be 0 if no data was immediately available (this does not indicate a closed connection). If a ptTimeout error is generated, the session is aborted, and all system resources are released.

The remote host can close the connection at any time. If the remote host closes the connection and there is still data in the system to receive, then the State changes to ptClosing to indicate this condition. You can safely use this method to receive data when the State is either ptConnected or ptClosing. You may call this method with Timeout greater than 0 and the remote host closes the connection while you are waiting for Data. In this case no error is generated, but a 0 Count is returned and State will be ptClosed when the method returns.

Blocked returns True while performing a blocking method (Timeout is greater than 0).

Use the Send method with Urgent set to True to send Out-of-band data. PowerTCP uses the SO_OOBINLINE socket option to always receive out-of-band data "in-line". In other words, all out-of-band data is received as normal data. It is up the user to correctly process this data.

Note Some environments, such as JavaScript, do not support the passing of parameters by reference. Consequently, such methods as Receive cannot be used by passing in a String. You can use the DartStream Object to circumvent this limitation (see the ReadString method Remarks section for a Java sample).

Error Codes

The Receive method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAbort

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptInvalidParam1 (Data is not a String or Byte array)

  • ptNetworkDown

  • ptNetworkReset

  • ptNotConnected

  • ptTimeout


Rexec Method

Example

Uses the remote execute protocol common to UNIX systems, which is intended to execute commands on a remote UNIX host. User and Password must match an account on the remote host.

Syntax

Object.Rexec RemoteName, User, Password, Command [ , RemotePort ] [ , LocalName ] [ , LocalPort ]

Part | Description
Object | Object expression that evaluates to a Telnet Control.
RemoteName | String. Can be either a host name (host.dart.com) or dot address (nnn.nnn.nnn.nnn).
User | String. Login name of the user.
Password | String. Password of the user.
Command | String. Command(s) to execute on the remote host.
RemotePort | Optional Long. Must be a value between 1 and 65535, inclusive. Defaults to 512.
LocalName | Optional String. Local interface to bind socket to. Not usually specified.
LocalPort | Optional Long. Local port to bind socket to. Not usually specified.

Remarks

This method differs from the Rsh method (which implements the remote shell protocol) by performing a full login sequence on the remote host. The Rsh method is typically faster and requires no password, but does require special configuration entries for security reasons. The UNIX pages provide a complete description of this protocol.

When this method is used a connection is initiated with the remote host using the remote execute protocol. The State property immediately changes to tcpConnecting and then changes to tcpConnected when the connection is established. The State Property can be checked in the body of the State event, polled off a timer, or checked immediately after the method is invoked when a positive Timeout is specified. Once connected, User, Password and Command is formatted and sent to the remote host. Use the Receive method or Search method to capture the results. When complete, the remote host closes the connection and the State event fires with the State property set to tcpClosing. After the output is captured, the State Property changes to tcpClosed. This method is invoked as blocking or non-blocking, depending on the value of the Timeout property.

When performing blocked method calls, the Blocked property may be checked to verify the control is not busy executing another method.

The first character received from the host indicates the success or failure of the command. An ASCII '0' indicates success, and the rest of the buffer contains the result of the command sent. An ASCII '1' indicates failure, and the rest of the buffer contains the error description generated by the host.

Error Codes

The Rexec method may generate the following error codes (refer to the ErrorConstants topic for a complete list of Telnet Control error codes):

  • ptAddressInUse

  • ptAddressNotAvailable

  • ptBlocked

  • ptConnectionRefused

  • ptHostNotFound

  • ptInvalidParam1 (RemoteName is not a valid string)

  • ptInvalidParam2 (User is not a valid string)

  • ptInvalidParam3 (Password is not a valid string)

  • ptInvalidParam4 (Command is not a valid string)

  • ptNetworkDown

  • ptNetworkUnreachable

  • ptNoBufferSpace

  • ptNoData

  • ptNotInitialized

  • ptTimeout

  • ptTryAgain


Rlogin Method

Example

U ses the remote login protocol common to UNIX systems, which is similar to Telnet but simpler. It does not require Telnet option negotiation because it was intended for use between two UNIX systems.

Syntax

Object.Rlogin RemoteName, User [ , ServerUser ] [ , TermTypeSpeed ] [ , CharRows ] [ , CharsPerRow ] [ , PixelsX ] [ , PixelsY ] [ , RemotePort ] [ , LocalName ] [ , LocalPort ]

Part | Description
Object | Object expression that evaluates to a Telnet Control.
RemoteName | String. Can be either a host name (host.dart.com) or dot address (nnn.nnn.nnn.nnn).
User | String. Login name of the user on the client host.
ServerUser | Optional String. Login name of the user on the server. Defaults to User if unspecified.
TermTypeSpeed | Optional String. Terminal type and speed. Defaults to “vt320/19200” if unspecified. Separate the terminal type from speed using the “/” as shown.
CharRows | Optional Long. Number of character rows. Defaults to 24.
CharsPerRow | Optional Long. Number of characters per row. Defaults to 72.
PixelsX | Optional Long. Number of pixels for the client window in the X direction. Defaults to 640.
PixelsY | Optional Long. Number of pixels for the client window in the X direction. Defaults to 640.
RemotePort | Optional Long. Must be a value between 1 and 65535, inclusive. Defaults to 513.
LocalName | Optional String. Local interface to bind socket to. Not usually specified.
LocalPort | Optional Long. Local port to bind socket to. Not usually specified.

Remarks

The remote login protocol supports the concept of window size, where the server requests the window size of the client. Responses are automatic using the parameter values from the CharRows, CharsPerRow, PixelsX, and PixelsY parameters. See RFC 1282 for the complete remote login protocol description.

This method requires authorization for the local host running your application. This is done by adding the proper entries to the hosts.equiv or .rhosts files located on the remote host. These files enable logins to be performed from other machines and users. The hosts.equiv file is a system file containing names of remote hosts authorized to execute the remote protocol. If not authorized in this file, the remote host looks for the .rhosts file located in the user's account on the remote host. The .rhosts file contains lines of host names and login names paired together. Your local host with login name is authorized if found in this file.

When this method is called a connection is initiated with the remote host using the remote login protocol. The State property immediately changes to tcpConnecting and then changes to tcpConnected when the connection is established. The State Property can be checked in the body of the State event, polled off a timer, or checked immediately after the method is invoked when a positive Timeout is specified. The remote host prompts for the password if a password exists for the user. Rlogin is normally used as a Telnet replacement for an interactive session. Use the Rexec or Rsh method if you simply want to execute a remote command.

This method is invoked as blocking or non-blocking, depending on the value of the Timeout property.

When performing blocked method calls, the Blocked property may be checked to verify the control is not busy executing another method.

Error Codes

The Rlogin method may generate the following error codes (refer to the ErrorConstants topic for a complete list of Telnet Control error codes):

  • ptAddressInUse

  • ptAddressNotAvailable

  • ptBlocked

  • ptConnectionRefused

  • ptHostNotFound

  • ptInvalidParam1 (RemoteName is not a valid string)

  • ptInvalidParam2 (User is not a valid string)

  • ptNetworkDown

  • ptNetworkUnreachable

  • ptNoBufferSpace

  • ptNoData

  • ptNotInitialized

  • ptProtocol (the host returned an error)

  • ptTimeout

  • ptTryAgain


Rsh Method

Example

Uses the remote shell protocol common to UNIX systems, which is intended to execute shell commands on a remote UNIX host. This method differs from the Rexec method (which implements the remote execute protocol) by being faster and not requiring a full login. For full description of the remote shell protocol, see the UNIX man pages.

Syntax

Object.Rsh RemoteName, User, Command [ , RemotePort ] [ , LocalName ] [ , LocalPort ]

Part | Description
Object | Object expression that evaluates to a Telnet Control.
RemoteName | String. Can be either a host name (host.dart.com) or dot address (nnn.nnn.nnn.nnn).
User | String. Login name of the user.
Command | String. Command(s) to execute on the remote host.
RemotePort | Optional Long. Must be a value between 1 and 65535, inclusive. Defaults to 514.
LocalName | Optional String. Local interface to bind socket to. Not usually specified.
LocalPort | Optional Long. Local port to bind socket to. Not usually specified.

Remarks

This method requires authorization for the local host running your application. This is done by adding the proper entries to the hosts.equiv or .rhosts files located on the remote host. These files enable logins to be performed from other machines and users. The hosts.equiv file is a system file containing names of remote hosts authorized to execute the remote protocol. If not authorized in this file, the remote host looks for the .rhosts file located in the user's account on the remote host. The .rhosts file contains lines of host names and login names paired together. Your local host with login name is authorized if found in this file.

When invoked, a connection is initiated with the remote host using the remote shell protocol. The State property immediately changes to tcpConnecting and then changes to tcpConnected when the connection is established. The State Property can be checked in the body of the State event, polled off a timer, or checked immediately after the method is invoked when a positive Timeout is specified. Once connected, Command is sent where it executes on the remote host. Use the Receive method or Search method to capture output generated from the command. Upon command completion, the remote host closes the connection and the State event fires with the State property set to tcpClosed. This method is invoked as blocking or non-blocking, depending on the value of the Timeout property.

When performing blocked method calls, the Blocked property may be checked to verify the control is not busy executing another method.

Error Codes

The Rsh method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAddressInUse

  • ptAddressNotAvailable

  • ptBlocked

  • ptConnectionRefused

  • ptHostNotFound

  • ptInvalidParam1 (RemoteName is not a valid string)

  • ptInvalidParam2 (User is not a valid string)

  • ptInvalidParam3 (Command is not a valid string)

  • ptNetworkDown

  • ptNetworkUnreachable

  • ptNoBufferSpace

  • ptNoData

  • ptNotInitialized

  • ptProtocol (the host returned an error)

  • ptTimeout

  • ptTryAgain


Search Method

See Also Example

Receive data up to and including a terminating sequence. The data stream is searched for the specified Token, and the specified String or Byte array is filled with the data stream up to and including the specified Token.

This method is useful for processing variable-length records or lines that are defined by known delimiter strings.

Syntax

[ Count = ] Object.Search Data, Token

Part | Description
Object | Object expression that evaluates to SecureTcp Control, TCP Control, or Telnet Control.
Data | String or Byte array. Received bytes are copied into this variable.
Token | String, Byte array, or DartStream Object. Capture all bytes up to and including this terminating sequence.
Count | Optional Long. Returns the number of Unicode characters or bytes copied into Data.

Remarks

You can use this method only when the State is tcpConnected or tcpClosing; otherwise, a ptNotConnected error is generated. When the State is tcpClosing, use the Receive, Fill, or Search methods to flush the buffer and cause the State to change to tcpClosed.

If the specified token is found, then the String or Byte array is always resized to the length needed to hold all the data received, up to and including the token. Count returns the length or size of the String or Byte array, respectively. If the specified token is not found, then the String or Byte array is not altered in any way, and Count is 0. When Data is a String, all bytes are converted to 16-bit Unicode characters according to the default ANSI code page installed on the system (this is not as efficient as receiving into a Byte array). If the code page is not ASCII, multi-byte characters may convert to single Unicode characters. It is possible that ReceiveBufferCount will indicate that data is available while this method fails to return data because Token is not seen.

Token defines a terminating character sequence. Token must be an initialized String or Byte array. You may specify Token as a Byte array for those environments that do not allow Strings with embedded Null characters.

If Timeout is 0, then available data is searched for the terminating Token, and the method immediately returns a Count value of either 0 (Token was not found) or the number of bytes returned. If Timeout is greater than 0, the method blocks and waits for the Token, and no error is generated if the Token arrives within the timeout period. If the timeout period is exceeded, a ptTimeout error is generated, the session is aborted, and all system resources are released.

Blocked returns True while performing a blocking method (Timeout is greater than 0).

Out-of-band data is sent using the Send method with the Urgent parameter set to True. PowerTCP uses the SO_OOBINLINE socket option to always receive out-of-band data "in-line". In other words, all out-of-band data is received as normal data. It is up the user to correctly process this data.

Note Some environments, such as JavaScript, do not support the passing of parameters by reference. Consequently, such methods as Receive cannot be used by passing in a String. You can use the DartStream Object to circumvent this limitation (see the ReadString method Remarks section for a Java sample).

Error Codes

The Search method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAbort

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptInvalidParam1 (Data is not a String or Byte array)

  • ptInvalidParam2 (Token is not a String or Byte array)

  • ptNetworkDown

  • ptNetworkReset

  • ptNotConnected

  • ptTimeout


Send Method

Send data after a connection is established. The Send event fires when Data is accepted by the system buffers. The SendBufferCount property indicates the number of bytes that have been submitted but have not yet been accepted by the system buffers.

Syntax

[ Count = ] Object.Send Data [ , LimitCount ]

Part | Description
Object | Object expression that evaluates to a Telnet Control.
Data | String, Byte, or Byte array. Data to be sent.
LimitCount | Optional Long. Number of bytes to send (limits a String or Byte array to LimitCount bytes).
Count | Optional Long. Number of bytes submitted.

Remarks

You can use this method only when the State property is tcpConnected; otherwise, a ptNotConnected error is generated.

Data can be provided in two ways:

  • A String is converted from Unicode to US_ASCII according to the default code table. Each 16-bit Unicode character is translated to an 8-bit byte. This is a convenient coding mechanism for many environments, but is not as efficient as sending a Byte array.

  • A Byte or Byte array is sent as presented, with no translation.

If LimitCount is specified and is greater than 0, then the number of bytes sent is limited to LimitCount. For example, if a Byte array of length 8192 contains only 100 bytes that the user wants to send, then a LimitCount of 100 can be used to override the default behavior, which would be to send the entire 8192 bytes (the length of the array).

This method can be invoked as blocking or non-blocking, depending on the value of the Timeout property. When performing blocked method calls, the Blocked property may be checked to verify the control is not busy executing another method. If the Timeout property is positive, this method blocks until the system accepts the data for sending (the SendBufferCount property decrements to 0) or the timeout period expires.

Any IAC character (ASCII 255) is doubled up according to the protocol specification. Any CR character (ASCII 13) not followed by a LF character (ASCII 10) has a NULL inserted after it according to the protocol specification. The reciprocal operation is applied to received data. The user should use CR/LF (ASCII 13 and ASCII 10) to terminate each line.

Error Codes

The Send method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptInvalidParam1 (Data is not a String, Byte, or Byte array)

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptTimeout


SendCommand Method

Send a Telnet command sequence. The Telnet Control ensures all formatting is accomplished correctly. This method is normally called from within the Command event.

Syntax

[ Count = ] Object.SendCommand Command [ , Option ] [ , SubOption ] [ , Urgent ]

Part | Description
Object | Object expression that evaluates to a Telnet Control.
Command | CommandConstants . Specifies the desired Telnet command.
Option | Optional Integer or OptionConstants. Specifies the desired Telnet option.
SubOption | Optional String or Byte array. Specifies the Telnet suboption to be used.
Urgent | Optional Boolean. Defaults to False. Specifies that the option should be sent as urgent (out-of-band) data. The telnetDataMark option, for example, should be sent using this flag.
Count | Optional Long. Number of bytes sent.

Remarks

You can use this method only when the State property is tcpConnected; otherwise, a ptNotConnected error is generated.

If Command is... | Then...
telnetSubOption | The Option and SubOption parameters are required. If SubOption is a Byte array or String, then it must be dimensioned to the exact length necessary.
telnetWill, telnetWont, telnetDo, or telnetDont | Only the Option parameter is required.
telnetBreak, telnetInterruptProcess, etc. | No additional parameters are required.
telnetDataMark | No additional parameters are required except for Urgent (use True).

The Telnet Control uses an internal check to protect the using application from non-terminating acknowledgment loops.

Refer to RFC 854 and RFC 855, as well as RFCs for the desired Telnet option for further information.

Error Codes

The SendCommand method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptInvalidParam1 (Command is not a valid Telnet command)

  • ptInvalidParam2 (Option is not a valid Telnet option)

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected


Trace Method

Example

Start or stop the accumulation of trace or debug data. Once started, this method accumulates data until it is turned off.

This method provides a convenient mechanism for viewing all data being sent and received over the connection and can be used to troubleshoot host interoperability issues and expose protocol communications.

Syntax

Object.Trace [ Result ] [ , Send ] [ , Receive ] [ , SendPrompt ] [ , ReceivePrompt ]

Part | Description
Object | Object expression that evaluates to a PowerTCP control.
Result | Optional String. An undimensioned string dynamically expanded to contain trace data or a filename that is used to store all trace data. If not provided or a Null value, then trace data is no longer stored.
Send | Optional Boolean. Defaults to False. A True value indicates that sent data should be traced.
Receive | Optional Boolean. Defaults to False. A True value indicates that received data should be traced.
SendPrompt | Optional String. Prompt to precede sent data.
ReceivePrompt | Optional String. Prompt to precede received data.

Remarks

ReceivePrompt and SendPrompt allow the application to specify what delimiters separate and label data being captured.


Command Event

Example

When the AutoOption property is set to False, the Telnet Control does not respond to Telnet commands, but instead fires the Command event. The application must have the appropriate code within this event to handle all option negotiation. The presence of this event allows the user to write sophisticated Telnet clients that can support any desired option, as well as Telnet server applications. The SendCommand method is used to send Telnet option negotiation sequences and commands.

Syntax

Private Sub Object_ Command ( [ Index As Integer , ] Command As CommandConstants, Opt As OptionConstants, SubOption As Variant )

Part | Description
Object | Evaluates to an Telnet Control.
Index | Integer. Array index if the object is part of an array.
Command | CommandConstants. The command value received.
Opt | OptionConstants. If Command is telnetDo, telnetDont, telnetWill or telnetWont, then this is the specified option.
SubOption | Variant. If Command is telnetSubOption, then this is the suboption sequence in a Byte array.


Error Event

Fires when an error condition occurs.

Syntax

Private Sub Object_Error ( [ Index As Integer , ] Number As ErrorConstants, Description As String )

Private Sub Object_Error ( [ Index As Integer , ] Child As Tcp, Number As ErrorConstants, Description As String )

Private Sub Object_Error ( [ Index As Integer , ] Child As SecureTcp, Number As ErrorConstants, Description As String )

Part | Description
Object | Evaluates to one of the following controls: Agent Control, Daemon Control, DNS Control, FTP Control, IMAP Control, Manager Control, Ping Control, POP Control, SecureFtp Control, SecurePop Control, SecureServer Control, SecureTcp Control, Server Control, TCP Control, Telnet Control, UDP Control, WebASP Control.
Index | Integer. Array index if the object is part of an array.
Child | Object reporting the error. Applies only to the Server Control and the SecureServer Control.
Number | ErrorConstants value.
Description | String. ErrorConstants description.

Remarks

Some environments, such as IIS Active Server Pages, do not support event handling. In this case the application must rely on blocking and the Error object that is returned to the container when an error condition occurs.

Note See the appropriate method and property description for a list of errors that may be generated.


Receive Event

Example

Fires when ReceiveBufferCount changes.

Syntax

Private Sub Object_Receive ( [ Index As Integer ] )

Private Sub Object_Receive ( [ Index As Integer , ] Child As Tcp )

Private Sub Object_Receive ( [ Index As Integer , ] Child As SecureTcp )

Part | Description
Object | Evaluates to a SecureServer Control, SecureTcp Control, Server Control, TCP Control, or Telnet Control.
Index | Integer. Array index if the object is part of an array.
Child | Object with data to receive. Applies only to the Server Control and the SecureServer Control.

Remarks

WARNING Timeout must be 0 when calling methods from within an event. Failure to observe this rule may cause reentrancy problems and unpredictable results.

The Receive, Fill, and Search methods are used to receive data. By putting one of these methods in the body of this event, you can optimize the processing speed of your application without blocking (waiting for data to arrive) or polling (continually checking for available data).

You can allow data to build up in the system buffers by not accessing the data. In this case, the system will eventually drop packets and communications will slow. This is called back pressure, and is the application-level mechanism that the receiving side of a connection can use to slow down a data transfer.

The Receive method, Fill method, or Search method must be called to enable this event to fire more than once. Normally, you will do this by placing code within the body of this event.


Send Event

Example

Fires when the system accepts data for sending.

Syntax

Private Sub Object_Send ( [ Index As Integer ] )

Private Sub Object_Send ( [ Index As Integer , ] Child As Tcp )

Private Sub Object_Send ( [ Index As Integer , ] Child As SecureTcp )

Part | Description
Object | Evaluates to a SecureServer Control, SecureTcp Control, Server Control, TCP Control, or Telnet Control.
Index | Integer. Array index if the object is part of an array.
Child | Object reporting sent data. Applies only to the Server Control and the SecureServer Control.

Remarks

WARNING Timeout must be 0 when calling methods from within an event. Failure to observe this rule may cause reentrancy problems and unpredictable results.

Each time the Send method is used, data is stored in a buffer and submitted to the system for sending. Between the time the Send method is called and the Send event fires, SendBufferCount is a positive value that indicates how many bytes are currently in this queue. This event fires each time SendBufferCount decreases because the system has accepted more data.

Use this method for outbound spooling tasks, such as sending a file over the network. Each time the Send event fires, read the next file segment from disk and send it.


State Event

Example

Fires when the State property changes.

Syntax

Private Sub Object_State ( [ Index As Integer ] )

Private Sub Object_State ( [ Index As Integer , ] Child As Tcp )

Private Sub Object_State ( [ Index As Integer , ] Child As SecureTcp )

Part | Description
Object | Evaluates to one of the following controls: FTP Control, IMAP Control, POP Control, SecureFtp Control, SecurePop Control, SecureServer Control, SecureTcp Control, Server Control, SMTP Control, TCP Control, Telnet Control, WebASP Control.
Index | Integer. Array index if the object is part of an array.
Child | Object that is changing state. Applies only to the Server Control and the SecureServer Control.

Remarks

WARNING Timeout must be 0 when calling methods from within an event. Failure to observe this rule may cause reentrancy problems and unpredictable results.

The Connect method (used to initiate an active connection) normally causes the State property to transition from tcpClosed to tcpConnecting (while resources are being allocated and the connection is being established) to tcpConnected, at which time communications activity can start.

When the Socket property is set to manage a connection that was accepted by the Daemon Control, the State property immediately transitions from tcpClosed to tcpConnected, at which time communications activity can start.

The Close method normally causes the State property to transition from tcpConnected to tcpClosing (while resources are being de-allocated) to tcpClosed.

When the remote host closes the connection, there may still be data available in the stream. In this case, the State property is tcpClosing until all the data is received and the socket returns a 0 value (using the Receive, Fill, or Search method), after which the State property changes to tcpClosed.


CommandConstants

The following values represent some of the Telnet commands used to negotiate Telnet options:

Value | Constant | Description
240 | telnetSubOptionEnd | End of sub-negotiation parameters (not used by application)
241 | telnetNoOperation | No reply is expected
242 | telnetDataMark | The data stream portion of a Synch
243 | telnetBreak | Network Virtual Terminal (NVT) BRK
244 | telnetInterruptProcess | The function IP
245 | telnetAbortOutput | The function AO
246 | telnetAreYouThere | The function AYT
247 | telnetEraseCharacter | The function EC
248 | telnetEraseLine | The function EL
249 | telnetGoAhead | The GA signal
250 | telnetSubOption | Indicates that what follows is sub-negotiation of the indicated option
251 | telnetWill | The host WILL agree to the requested option
252 | telnetWont | The host WONT agree the requested option
253 | telnetDo | Ask the remote host to DO the specified option
254 | telnetDont | Ask the remote host to NOT DO the specified option
255 | telnetIac | The Interpret as Command signal


ErrorConstants

Errors are reported to the application with the error object and by firing the Error event. ErrorConstants fall into two classes: design-time errors and run-time errors. The Error event always fires when any error occurs. When Timeout is 0, however, run-time errors are not thrown back to the container. This allows applications that use only non-blocking operation to localize all error handling in the Error event. To summarize:

  • Timeout is 0 (non-blocking). All errors are reported via the Error event. Only errors classified as design time errors are also reported back from methods using the error object.

  • Timeout is not 0 (blocking). All errors are reported via the Error event. All errors occurring within the scope of a method are reported back to the container using the error object.

Errors are marked as INFO or FATAL. An INFO error does not affect the State property. A FATAL error performs an Abort and releases all resources.

Value | Constant | Description
0 | ptOk | No error

Design-Time Errors

Value | Constant | Description
12001 | ptInvalidParam1 | Parameter #1 is invalid. INFO
12002 | ptInvalidParam2 | Parameter #2 is invalid. INFO
12003 | ptInvalidParam3 | Parameter #3 is invalid. INFO
12004 | ptInvalidParam4 | Parameter #4 is invalid. INFO
12009 | ptInvalidProperty | Invalid property assignment. INFO

Run-Time Errors

Value | Constant | Description
10042 | ptOptionNotSupported | The specified socket option is not supported by the system. INFO.
10048 | ptAddressInUse | Address already in use. Only one usage of each socket address (protocol/IP address/port) is normally permitted. This error occurs if an application attempts to bind() a socket to an IP address/port that has already been used for an existing socket, or a socket that wasn't closed properly, or one that is still in the process of closing. For server applications that need to bind() multiple sockets to the same port number, the ReuseAddress property can be used. FATAL.
10049 | ptAddressNotAvailable | Cannot assign requested address. The requested address is not valid in its context. Normally results from an attempt to bind() to an address that is not valid for the local machine. This may also result from connect(), sendto(), WSAConnect(), WSAJoinLeaf(), or WSASendTo() when the remote address or port is not valid for a remote machine (for example, address or port 0). FATAL.
10050 | ptNetworkDown | Network is down. A socket operation encountered a dead network. This could indicate a serious failure of the network system (for example,. the protocol stack that the Winsock DLL runs over), the network interface, or the local network itself. FATAL.
10051 | ptNetworkUnreachable | Network is unreachable. A socket operation was attempted to an unreachable network. This usually means the local software knows no route to reach the remote host. FATAL.
10052 | ptNetworkReset | Network dropped connection on reset. The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress. FATAL.
10053 | ptConnectionAborted | Software caused connection abort. An established connection was aborted by the software in your host machine, possibly due to a data transmission timeout or protocol error. FATAL.
10054 | ptConnectionReset | Connection reset by peer. An existing connection was forcibly closed by the remote host. This normally results if the peer application on the remote host is suddenly stopped, the host is rebooted, or the remote host used a "hard close" (see Abort method) on the remote socket. This error may also result if a connection was broken due to keep-alive activity detecting a failure while one or more operations are in progress. Operations that were in progress fail with ptNetworkReset. Subsequent operations fail with ptConnectionReset. FATAL.
10055 | ptNoBufferSpace | No buffer space available. An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full. FATAL.
10057 | ptNotConnected | Socket is not connected. A request to send or receive data was disallowed because the socket is not connected or allocated. Any other type of operation might also return this error. FATAL.
10060 | ptTimeout | Timed out. A connection attempt failed because the connected party did not properly respond after a period of time, or an established connection failed because connected host has failed to respond. Alternatively, a blocked method failed to return within the period specified by the Timeout property. FATAL.
10061 | ptConnectionRefused | Connection refused. No connection could be made because the target machine actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host (for example,. one with no server application running). May also be generated by a Daemon that refuses a connection because its resources have been exhausted. FATAL.
10093 | ptNotInitialized | Network interface could not be initialized. FATAL.
11001 | ptHostNotFound | Host not found. No such host is known. The name is not an official hostname or alias, or it cannot be found in the database(s) being queried. This error may also be returned for protocol and service queries, and means the specified name could not be found in the relevant database. FATAL.
11002 | ptTryAgain | Non-authoritative host not found. This is usually a temporary error during hostname resolution and means that the local server did not receive a response from an authoritative server. A retry at some time later may be successful. FATAL.
11003 | ptNoRecovery | This is a non-recoverable error. This indicates some sort of non-recoverable error occurred during a database lookup. This may be because the database files (for example, BSD-compatible HOSTS, SERVICES or PROTOCOLS files) could not be found, or a DNS (Domain Name Server) request was returned by the server with a severe error. FATAL.
11004 | ptNoData | Valid name, no data record of requested type. The requested name is valid and was found in the database, but it does not have the correct associated data being resolved for. The usual example for this is a hostname -> address translation attempt which uses the DNS, and an MX record is returned but no A record - indicating the host itself exists but is not directly reachable. FATAL.
11100 | ptError | Unexpected general error. FATAL.
11101 | ptProtocol | Unexpected protocol error. FATAL.
11102 | ptFile | Error accessing local file storage. FATAL.
11103 | ptAbort | The Abort method was called. FATAL.
12005 | ptHttpInvalidUrl | The Url is unspecified or invalid.
12011 | ptBlocked | User thread is blocking in another method. INFO.
12012 | ptAuthentication | Authentication with the server failed. FATAL.
12013 | ptCompile | MIB file could not be compiled. INFO.
12014 | ptConnected | A connection already exists.
12015 | ptFormatError | The server was unable to interpret the query.
12016 | ptServerError | There was a failure on the server.
12017 | ptNotFound | The name referred to in the query does not exist.
12018 | ptNotImplemented | The server does not support the request type of query.
12019 | ptOperationRefused | The server refused to perform the specified operation.
12020 | ptNoCertificate | There was an error in creating credentials.
12021 | ptInvalidMailAddress | The Email address specified was not valid.
12022 | ptNoSecurity | Secure communications is not available on this machine.


OptionConstants

The following values represent frequently used Telnet Option numbers. You can specify additional Option numbers using a Long value for the Option parameter. This number should be between 1 and 255.

Value | Constant | Description
1 | telnetEcho | Controls echoing
3 | telnetSupressGoAheads | Suppresses GoAhead signaling
24 | telnetTerminalType | Controls terminal type
31 | telnetWindowSize | Controls terminal window size


StateConstants

The State property is one of the following values:

Value | Constant | Description
0 | tcpClosed | The session is not connected and has no resources allocated to it.
1 | tcpConnecting | The session is transitioning from tcpClosed to tcpConnected (the Connect method was called).
2 | tcpConnected | The session is active and can send/receive data.
3 | tcpClosing | The session is transitioning gracefully from tcpConnected to tcpClosed.


VT Control

Properties Methods Events Constants

Use the VT Control to process data received from a host application and targeted for a VT terminal. By streaming this data into a VT Control, you can either:

  • Display it to the user (like most emulation products).

  • Screen scrape it and format the text into a custom report of your own design.

If you do not first process the data with a VT Control, you are left with a stream of data containing numerous escape codes.

The VT Control provides terminal emulation as defined by Digital Equipment Corporation for their VT data terminals. It differs from other controls like TCP and Telnet since it used for data display and formatting, not communications. VT52, VT100, VT220, and VT320 emulation is supported. Each emulation contains formatting rules (escape codes) for interpreting incoming data. For example, one sequence may dictate that the display screen be filled with spaces, while another directs that the cursor be moved to a specified location.

DEC developed the VT escape codes for their VT terminals, which contained a screen, keyboard, printer port, and an RS-232 connection for connecting to the host. By performing this same functionality in software using high-speed LAN connectivity, the VT Control provides a faster display screen, flexible keyboard mapping, and printing to the Windows default printer—a big improvement over previous hardware devices.

Distribution Note

Powervt.fon should be included in the distribution of the VT control.

Miscellaneous

Product | PowerTCP Emulation Tool
Prog ID | Dart.Vt.1
File | DartVt.dll
Dependencies | DartSock.dll
Threading | Apartment Model
Licensed | Yes


VT Control Usage

The VT Control provides the following features:

  • The VT window is the physical window providing a display of the (simulated) VT screen. Mouse events fire the Click event when the mouse pointer is over the VT window and a user clicks a button. When the window has the focus, keyboard events fire the KeyDown and KeyPress events. A vertical scroll bar on the right side scrolls up to view the scroll-back buffer. A horizontal scroll bar on the bottom scrolls to reveal text in the rightmost columns.

  • The display screen is defined by the Rows property and Cols property—normally 24 rows high and 80 columns wide. An application may trap keys pressed on the keyboard via the KeyDown event and perform custom processing. The KeyPress event fires to inform the application that data can be sent to the host. Use the Display method to display data received from the host. This data may display text or perform a command, such as setting underline mode. Data is displayed according to the emulation mode set by the TermType property. Refer to the Display method for a VB code example.

  • The scroll-back buffer contains rows of text scrolled up from the display screen, and is indicated by a vertical scroll bar on the VT window. The user scrolls up to view the scroll-back buffer. You can remove the scroll-back buffer by setting the BufferRows property to zero; this also removes the vertical scroll bar.

  • The VT cursor indicates where text appears. When the cursor moves to the next row, the NewLine event fires. The cursor appears when the Enabled property is True, and the control has focus.

Tip Review all the VT Control properties and methods for an exhaustive description of the capabilities of this very complete implementation.


Key Mapping

The VT Control uses a default key mapping that is close to the keyboard layout of a VT terminal. For example, the PF1 key on the VT is the top left key on the numeric keypad, so the NUMLOCK key on the PC numeric keypad is mapped to the PF1 function key. The following table summarizes the default keyboard mappings:

VT Key

PC Key

Find

INSERT

InsertHere

HOME

Remove

PAGE UP

Select

DELETE

PrevScreen

END

NextScreen

PAGE DOWN

PF1

NUMLOCK

PF2

/ (on numeric keypad)

PF3

  • (on numeric keypad)

PF4

- (on numeric keypad)

, (comma)

+ (on numeric keypad)

- (minus)

CTRL + PLUS SIGN (numeric keypad)

Enter

ENTER (on numeric keypad)

F6–F10 (w/ Shift for user-defined keys)

F6 through F10 (w/ CTRL for user-defined keys)

F11–F20 (w/ Shift for user-defined keys)

SHIFT+F through Shift+F10 (w/ CTRL for user-defined keys)

Help

F11

Do

F12

To modify these default mappings, set the KeyCode parameter of the KeyDown event to 0 (canceling out the default string normally generated by the key); users can then send any arbitrary string directly out the communications channel. When F1 is pressed, for example, users may substitute the "SS3 P" sequence.

Detailed VT Character String Tables

The following tables are provided as a guide to the character strings generated by the VT. The reader may wish to obtain more complete programming information directly from Digital Equipment Corporation.

Control Sequence | 7-bit Mode | 8-bit Mode
CSI | ESC [ | 0x9b
SS3 | ESC O | 0x8f

VT/IBM Main Keypad Function Keys | Code Transmitted
BACKSPACE | DEL character
TAB | HT character
RETURN | CR or CRLF depending upon the NewLine property
CTRL, Lock, SHIFT | Does not send a code
SPACEBAR | SP character

VT Edit Key | IBM Edit Key | VT 220/320 Code | VT 100/52 Code
Find | INSERT | CSI 1 ~ | None
Insert Here | HOME | CSI 2 ~ | None
Remove | PAGE UP | CSI 3 ~ | None
Select | DELETE | CSI 4 ~ | None
Prev Screen | END | CSI 5 ~ | None
Next Screen | PAGE DOWN | CSI 6 ~ | None

VT/IBM Cursor Keys | VT100/220/320 Code Normal Cursor Key Mode | VT100/220/320 Code Application Cursor Key Mode | VT52 Code Normal Cursor Key Mode | VT52 Code Application Cursor Key Mode
UP ARROW | CSI A | SS3 A | ESC A | ESC A
DOWN ARROW | CSI B | SS3 B | ESC B | ESC B
RIGHT ARROW | CSI C | SS3 C | ESC C | ESC C
LEFT ARROW | CSI D | SS3 D | ESC D | ESC D

VT Aux Keypad | IBM Aux KeyPad | VT100/220/ 320 Code Numeric Keypad Mode | VT100/220/ 320 Code Application Keypad Mode | VT52 Code Numeric Keypad Mode | VT52 Code Application Keypad Mode
0 | 0 | 0 | SS3 p | 0 | ESC ? p
 |  |  | SS3 q |  | ESC ? q
 | 2 | 2 | SS3 r | 2 | ESC ? r
 | 3 | 3 | SS3 s | 3 | ESC ? s
 | 4 | 4 | SS3 t | 4 | ESC ? t
 | 5 | 5 | SS3 u | 5 | ESC ? u
 | 6 | 6 | SS3 v | 6 | ESC ? v
 | 7 | 7 | SS3 w | 7 | ESC ? w
 | 8 | 8 | SS3 x | 8 | ESC ? x
 | 9 | 9 | SS3 y | 9 | ESC ? y
- | Ctrl + "+" | - (minus) | SS3 m | - | ESC ? m
, | + | , (comma) | SS3 l | , | ESC ? l
. | . | . (period) | SS3 n | . | ESC ? n
Enter | Enter | CR or CR/LF | SS3 M | CR or CR/LF | ESC ? M
PF1 | NumLock | SS3 P | SS3 P | ESC P | ESC P
PF2 | / | SS3 Q | SS3 Q | ESC Q | ESC Q
PF3 |  | SS3 R | SS3 R | ESC R | ESC R
PF24 | - | SS3 S | SS3 S | ESC S | ESC S

VT Function Keys | IBM Function Keys | VT220/320 Code | VT100/52 Code
Hold Screen | F1 | (none) | (none)
Print Screen | F2 | (none) | (none)
Set-up | F3 | (none) | (none)
Data/Talk | F4 | (none) | (none)
Break | F5 | (none) | (none)
F6 | F6 | CSI 1 7 ~ | (none)
F7 | F7 | CSI 1 8 ~ | (none)
F8 | F8 | CSI 1 9 ~ | (none)
F9 | F9 | CSI 2 0 ~ | (none)
F10 | F10 | CSI 2 1 ~ | (none)
F11 (ESC) | <shift> F1 | CSI 2 3 ~ | ESC
F12 (BS) | <shift> F2 | CSI 2 4 ~ | BS
F13 (LF) | <shift> F3 | CSI 2 5 ~ | LF
F14 | <shift> F4 | CSI 2 6 ~ | (none)
Help | F11 | CSI 2 8 ~ | (none)
Do | F12 | CSI 2 9 ~ | (none)
F17 | <shift> F7 | CSI 3 1 ~ | (none)
F18 | <shift> F8 | CSI 3 2 ~ | (none)
F19 | <shift> F9 | CSI 3 3 ~ | (none)
F20 | <shift> F10 | CSI 3 4 ~ | (none)


AnswerBack Property

Returns or sets a string expression to be sent by the control whenever an ENQ is received.

Syntax

Object.AnswerBack

Part | Description
Object | Evaluates to a VT Control.

Data Type

String

Remarks

The default value is a zero-length String (no string is sent).


AutoPrint Property

Returns or sets a value that determines whether each line sent to the screen is also sent to the default system printer.

Syntax

Object.AutoPrint

Part | Description
Object | Evaluates to a VT Control.

Data Type

Boolean

Remarks

The default value is False.

The PrintPassthrough property is used with the AutoPrint and PrinterController properties and the PrintCursorLine and PrintScreen methods. You must set the PrintPassthrough property prior to using these properties and methods.


AutoRepeat Property

Returns or sets a value that determines whether depressed keys generate more than one character.

Syntax

Object.AutoRepeat

Part | Description
Object | Evaluates to a VT Control.

Data Type

Boolean

Remarks

The default value is False.

When set to False, only a single character is generated when a key is depressed for a time interval; otherwise, multiple characters are generated until the key is released.


AutoResize Property

When the Rows, Cols, Font, ColWidth, RowHeight, or StatusLine property changes, the dimensions of the window may change to accommodate the display screen.

Syntax

Object.AutoResize

Part | Description
Object | Object expression that evaluates to a VT Control.

Data Type

Boolean

Remarks

When set to True, the VT Control width and height automatically adjust to the new dimensions and the Resize event fires. Also, when set to True, the width and height of the control window are set as follows:

Height = Object.Rows * Object.RowHeight * HeightScale

Width = Object.Cols * Object.ColWidth * WidthScale

where HeightScale and WidthScale are scaling variables dependent on the current measurement units set up by the container.

Note The origin of the control window remains fixed.


AutoWrap Property

Returns or sets a value that indicates whether display text stops at the last column or wraps to the next line when a line contains more data than can fit on one row.

Syntax

Object.AutoWrap

Part | Description
Object | Evaluates to a VT Control.

Data Type

Boolean

Remarks

The default value is False.


BackColor Property

Returns or sets the background color of the control.

Syntax

Object.BackColor

Part | Description
Object | Evaluates to a VT Control.

Data Type

Long value or constant that specifies an RGB color.

Remarks

The default value is white.

Reference the standard Windows controls documentation for information on color usage.


Bell Property

Returns or sets a value that determines whether an audio bell is enabled.

Syntax

Object.Bell

Part | Description
Object | Evaluates to a VT Control.

Data Type

Boolean

Remarks

The default value is False.

When set to True, the ASCII BEL character causes the system bell to sound. Such actions as attempting to scroll past the scroll range also cause the bell to sound.


BoldColor Property

Returns or sets the color of bold text.

Syntax

Object.BoldColor

Part | Description
Object | Evaluates to a VT Control.

Data Type

Long value or constant that specifies an RGB color.

Remarks

The default value is green.

Reference the standard Windows controls documentation for information on color usage.


BufferRows Property

Returns or sets the number of rows stored in the scrollback buffer. The default value is 72.

Syntax

Object.BufferRows

Part | Description
Object | Evaluates to a VT Control.

Data Type

Long

Remarks

You can change this property at any time, and data is preserved, if possible. When set to zero, the scrollback buffer is disabled, and the vertical scroll bar on the control window is removed.


Cols Property

Returns or sets the number of columns used for the display screen.

Syntax

Object.Cols

Part | Description
Object | Evaluates to a VT Control.

Data Type

ColumnConstants

Remarks

The default value is vtCols80.

If the AutoResize property is set to True, the VT Control automatically resizes when the Cols property changes.


ColWidth Property

Returns the width of a column according to the measurement units used by the container.

Syntax

Object.ColWidth

Part | Description
Object | Evaluates to a VT Control.

Data Type

Long

Remarks

Read-only.

If the AutoResize property is set to True, the VT Control automatically resizes when this property changes.


CursorCol Property

Returns or sets the column position of the cursor.

Syntax

Object.CursorCol

Part | Description
Object | Evaluates to a VT Control.

Data Type

Long

Remarks

The default value is 1. The range is between 1 and the value of the Cols property.


CursorKeys Property

Returns or sets a value that determines whether the cursor keys send ANSI cursor control sequences (up, down, left, right) or application control sequences.

Syntax

Object.CursorKeys

Part | Description
Object | Evaluates to a VT Control.

Data Type

CursorKeyConstants

Remarks

The default value is vtCursorNormal.


CursorRow Property

Returns or sets the row position of the cursor.

Syntax

Object.CursorRow

Part | Description
Object | Evaluates to a VT Control.

Data Type

Long

Remarks

The default value is 1. The range is between 1 and the value of the Rows property.


CursorStyle Property

Returns or sets a value that determines whether the cursor style is a block cursor or an underline cursor.

Syntax

Object.CursorStyle

Part | Description
Object | Evaluates to a VT Control.

Data Type

CursorStyleConstants

Remarks

The default value is vtBlock.


DefaultPrinter Property

Controls whether the system default printer or a user-selected printer is used.

Syntax

Object.DefaultPrinter

Part | Description
Object | Evaluates to a VT Control.

Data Type

Boolean

Remarks

The default value is False.

When set to False, the VT Control uses the system default printer and its corresponding default settings. When set to True, the user is prompted to select and optionally make changes to the setup of a printer during a PrintScreen, PrintSelected, or PrintCursorLine method call. The default Select Printer dialog box is used and any settings changes the user makes (such as paper orientation) are also used for the print job.


DisableF1toF5 Property

When set to True, function keys F1, F2, F3, F4 and F5 are disabled (control and shift-modified keys still work as advertised).

Syntax

Object.DisableF1toF5

Part | Description
Object | Evaluates to a VT Control.

Data Type

Boolean

Remarks

This is a run-time property only. The only ramification is that when set to True, pressing F2 no longer prints the display.


Enabled Property

Returns or sets a value that determines the ability of the VT Control to retrieve external events, capture focus for the control, and display the cursor.

Syntax

Object.Enabled

Part | Description
Object | Evaluates to a VT Control.

Data Type

Boolean

Remarks

The default value is True.

When set to True, the VT Control can capture focus, the Click event and KeyDown event are enabled, and the cursor appears when the control has focus. When set to False, the VT Control can never capture focus, the Click event and KeyDown event are disabled, and the cursor is disabled.


Font Property

Returns or sets the font used in the display of the control. The default value is 11-point VT220_ascii font.

Syntax

Object.Font

Part | Description
Object | Evaluates to a VT Control.

Data Type

Font

Remarks

If the AutoResize property is True, the VT Control automatically resizes when the Font property changes.

The Font property is defined by Microsoft's StdFont Object and includes all members of this object including:

Properties:

Bold | Returns or sets the font style of the Font object to either bold or nonbold.
Charset | Sets or returns the character set used in the font.
Italic | Returns or sets the font style of the Font object to either italic or nonitalic.
Name | Returns the name used in code to identify a form, control, or data access object. Read-only at run time. Returns or sets the name of a font object.
Size | Returns or sets the font size used in the Font object.
Strikethrough | Returns or sets the font style of the Font object to either strikethrough or nonstrikethrough.
Underline | Returns or sets the font style of the Font object to either underlined or nonunderlined.
Weight | Returns or sets the weight of the characters that make up a Font object. The weight refers to the thickness of the characters, or the “boldness factor”. The higher the value, the bolder the character.

Events:

FontChanged

Occurs when a property of a stdFont object changes at run time.

For more information about these properties and events, search for StdFont in the MSDN Library.


ForeColor Property

Returns or sets the foreground color used for text. The default value is black.

Syntax

Object.ForeColor

Part | Description
Object | Evaluates to a VT Control.

Data Type

Long value or constant that specifies an RGB color

Remarks

The default value is black.

Reference the standard Windows controls documentation for information on color usage.


hWnd Property

Example

Returns the handle to the window of the VT Control. The window handle is needed for specialized message handling or Windows API calls.

Syntax

Object.hWnd

Part | Description
Object | Evaluates to a VT Control.

Data Type

Long

Remarks

Read-only.


Inverted Property

Returns or sets a value that determines whether the foreground and background colors are switched.

Syntax

Object.Inverted

Part | Description
Object | Evaluates to a VT Control.

Data Type

Boolean

Remarks

The default value is False.

The ForeColor property sets the text color, and the BackColor property sets the color behind the text.


Keypad Property

Returns or sets a value that determines whether the keypad sends ASCII characters or escape sequences.

Syntax

Object.Keypad

Part | Description
Object | Evaluates to a VT Control.

Data Type

KeypadConstants

Remarks

The default value is vtNumeric.

ASCII character codes correspond to the numeric characters on the keys. Escape sequences are used by some applications.


NationalCharSet Property

Returns or sets the national character set for use in VT220 7-bit or VT320 7-bit emulation modes to display special characters that normally require 8-bit emulation mode.

Syntax

Object.NationalCharSet

Part | Description
Object | Evaluates to a VT Control.

Data Type

NationalCharSetConstants

Remarks

The default value is vtAscii.


NewLine Property

Returns or sets the end-of-line character sequence to either a single CR or CR/LF combination.

Syntax

Object.NewLine

Part | Description
Object | Evaluates to a VT Control.

Data Type

NewLineConstants

Remarks

The default value is vtCrOnly.


PrinterController Property

Returns or sets a value that determines if to stop the display of text and only send data to the default system printer.

Syntax

Object.PrinterController

Part | Description
Object | Evaluates to a VT Control.

Data Type

Boolean

Remarks

The default value is False.

The PrintPassthrough property is used with the AutoPrint and PrinterController properties and the PrintCursorLine and PrintScreen methods. You must set the PrintPassthrough property prior to using these properties and methods.


PrintPassthrough Property

Returns or sets a value that determines if printing bypasses the normal printer drivers and prints directly to the printer port.

Syntax

Object.PrintPassthrough

Part | Description
Object | Evaluates to a VT Control.

Data Type

Boolean

Remarks

The default value is False.

This property is used with the AutoPrint and PrinterController properties and the PrintCursorLine and PrintScreen methods. You must set the PrintPassthrough property prior to using these properties and methods.


RowHeight Property

Returns the height of a single character (or line) according to the measurement units used by the container.

Syntax

Object.RowHeight

Part | Description
Object | Evaluates to a VT Control.

Data Type

Long

Remarks

Read-only.

If the AutoResize property is True, the VT Control automatically resizes when the RowHeight property changes.


Rows Property

Returns or sets the number of rows being used for the display screen.

Syntax

Object.Rows

Part | Description
Object | Evaluates to a VT Control.

Data Type

Long

Remarks

The default value is 24. This property is normally set to 24, but some host applications support greater values. The Telnet WindowSize property can be used to support rows in excess of 24.

If the AutoResize property is True, the VT Control automatically resizes when the Rows property changes.


ScrollType Property

Returns or sets a value that determines whether to use jump scrolling or smooth scrolling in the display screen.

Syntax

Object.ScrollType

Part | Description
Object | Evaluates to a VT Control.

Data Type

ScrollTypeConstants

Remarks

The default value is vtJump.

Jump scrolling displays new lines as fast as they are received causing lines to jump when data is received at a high rate. Smooth scrolling limits the rate at which new lines appear on the screen resulting in smother data display, even when data is received at a high rate.


SelLength Property

Returns or sets the length of the number of characters selected.

Syntax

Object.SelLength

Part | Description
Object | Evaluates to a VT Control.

Data Type

Long

Remarks

The default value is zero.

This property includes 2 additional characters for the CR/LF at the end of each line. When set to 0, no text is selected.


SelStart Property

Returns or sets the starting index of the characters currently selected.

Syntax

Object.SelStart

Part | Description
Object | Evaluates to a VT Control.

Data Type

Long

Remarks

The default value is one.

This property is one-based (if the first character in the scroll-back buffer is selected, the value would be 1).


StatusLine Property

Returns or sets a value that indicates whether a 25th line is displayed as a status line when in VT320 7-bit or 8-bit mode.

Syntax

Object.StatusLine

Part | Description
Object | Evaluates to a VT Control.

Data Type

Boolean

Remarks

The default value is False.

Some applications use the status line for status information. The TermType property must be vt320_7 or vt320_8 for the status line to appear.

If the AutoResize property is True, the VT Control automatically resizes when the StatusLine property changes.


Style Property

Returns the character styles contained in the scroll-back buffer and display screen.

Syntax

Object.Style

Part | Description
Object | Evaluates to a VT Control.

Data Type

String

Remarks

Read-only.

Each character in the string corresponds to a character in the string returned by the Text property. You can compute the size of this string as follows:

Size = (Object.Rows + Object.BufferRows) * (Object.Cols + 2)

where Object.Cols is 80 or 132 and 2 is the CR/LF at the end of each row.

Each character in the string is a sum of character style(s) represented by StyleConstants.


Tabs Property

Returns or sets a list of comma-delimited tab positions.

Syntax

Object.Tabs

Part | Description
Object | Evaluates to a VT Control.

Data Type

String

Remarks

The default value is "9,17,25,33,41,49,57,65,73,81,89,97,105,113,121,129".


TermType Property

Returns or sets the terminal type to emulate.

Syntax

Object.TermType

Part | Description
Object | Evaluates to a VT Control.

Data Type

TermTypeConstants

Remarks

The default value is vt320_7.


Text Property

Returns the characters contained in the scroll-back buffer and display screen.

Syntax

Object.Text

Part | Description
Object | Evaluates to a VT Control.

Data Type

String

Remarks

Each character in the string corresponds to the characters returned by the Style property. You can compute the size of the string as follows:

Size = (Object.Rows + Object.BufferRows) * (Object.Cols + 2)

where Object.Cols is 80 or 132, depending on the value of Object.Cols, and 2 is the CR/LF at the end of each row.

Each character in the string, except the CR/LF at the end of each line, is a printable character.


Clear Method

Clears the scrollback buffer and all rows in the display screen.

Syntax

Object.Clear

Part | Description
Object | Object expression that evaluates to a VT Control.

Remarks

The scrollback buffer and the display screen is filled with space characters.


Display Method

Example

Displays a text string or byte array and interprets all escape sequences.

Syntax

Object.Display Data

Part | Description
Object | Object expression that evaluates to a VT Control.
Data | String or Byte array to display.

Remarks

Use this method to process data received from a host. The control interprets and displays the data using the terminal type specified in the TermType property.

The entire dimensioned contents of the String or Byte array are displayed.


EnsureVisible Method

Moves the display to ensure the specified row is visible.

Syntax

Object.EnsureVisible Row

Part | Description
Object | Object expression that evaluates to a VT Control.
Row | Long. Row that is to be made visible.

Remarks

This method moves the display so that Row falls within the display area. Row must be from 0 to Rows + BufferSize.


PrintCursorLine Method

Example

Sends a copy of the line the cursor is currently on to the default system printer.

Syntax

Object.PrintCursorLine

Part | Description
Object | Object expression that evaluates to a VT Control.

Remarks

The PrintPassthrough property is used with the AutoPrint and PrinterController properties and the PrintCursorLine and PrintScreen methods. You must set the PrintPassthrough property prior to using these properties and methods.


PrintScreen Method

Example

Sends a copy of the current display screen to the default system printer.

Syntax

Object.PrintScreen

Part | Description
Object | Object expression that evaluates to a VT Control.

Remarks

The PrintPassthrough property is used with the AutoPrint and PrinterController properties and the PrintCursorLine and PrintScreen methods. You must set the PrintPassthrough property prior to using these properties and methods.


PrintSelected Method

Prints the currently selected text.

Syntax

Object.PrintSelected

Part | Description
Object | Object expression that evaluates to a VT Control.

Remarks

This method prints the currently selected text. If the DefaultPrinter property is set to True, the system default printer will be used; otherwise, the user is prompted to select a printer.


Click Event

Example

Fires when the user presses or releases a mouse button when the mouse pointer is on the VT Control window and the Enabled property is set to True. Use this event to determine the states of the mouse buttons, virtual Shift key, and virtual Control key when a mouse button is depressed or released.

Syntax

Private Sub Object_Click ( xPos As Long, yPos As Long, Click As ClickConstants, Keys As VirtualKeyConstants )

Part | Description
Object | Evaluates to a VT Control.
xPos | Long. The x-position of the mouse pointer when the user presses or releases a mouse button.
yPos | Long. The y-position of the mouse pointer when the user clicked or released a mouse button.
Click | ClickConstants. Specifies the type of mouse button press as left/right and single/double.
Keys | VirtualKeyConstants. The key(s) that was (were) held during a mouse click. The values are added together as more than one key may be pressed.

Remarks

The xPos and yPos parameters are in client coordinates.


HostCommand Event

Example

Fires when the host sends an instruction that changes a control property. This event indicates when a VT attribute is about to change. The change can be defeated by setting Ignore to True.

Syntax

Private Sub Object_HostCommand ( Attr As AttributeConstants, Value As Variant, Ignore As Boolean )

Part | Description
Object | Evaluates to a VT Control.
Attr | AttributeConstants. The attribute the host is changing.
Value | Variant. The new value for the attribute. The data type for Value is determined by Attribute.
Ignore | Boolean. Set to True to defeat the host command.

Remarks

The following table defines the type definitions for the attributes:

Attribute | Value Type
VtTerminal | TermTypeConstants
VtAutoPrint | Boolean
VtAutoWrap | Boolean
VtBackColor | OLE_COLOR (Long)
VtBoldColor | OLE_COLOR (Long)
VtBell | Boolean
VtCols | ColumnConstants
VtCursor | Boolean
VtCursorKeys | CursorKeyConstants
VtCursorStyle | CursorStyleConstants
VtEnabled | Boolean
VtForeColor | OLE_COLOR (Long)
VtInverted | Boolean
VtKeypad | KeypadConstants
VtNewLine | NewLineConstants
VtOnline | Boolean
VtPrinterController | Boolean
VtScrollType | ScrollTypeConstants
VtTabs | String


KeyDown Event

Example

Fires when the user depresses a key, the Enabled property is set to True, and the VT Control has focus. You can set KeyCode to 0 (the KeyPress event will NOT be called) and send your own substitution string to the host (this is how you can map individual keys to any arbitrary character sequence).

Syntax

Private Sub Object_KeyDown ( KeyCode As Integer, Shift As ShiftConstants, Extended As Boolean )

Part | Description
Object | Evaluates to a VT Control.
KeyCode | Integer. The virtual key code for the key pressed.
Shift | ShiftConstants . The shift key(s) that were pressed (Shift/Alt/Control).
Extended | Boolean. Set to True when the key pressed is an extended key.

Remarks

The Extended parameter is True if the key pressed is part of the extended keyboard. For example, both ENTER keys have the same virtual key code, but the ENTER key on the numeric keypad would have a value of True for Extended.


KeyPress Event

Example

Fires when the user depresses a key, the Enabled property is set to True, and the VT Control has focus. This event indicates what data may be sent to the host. The KeyDown event can be used for any key substitutions and fires prior to the KeyPress Event.

Syntax

Private Sub Object_KeyPress ( KeyAscii As String )

Part | Description
Object | Evaluates to a VT Control.
KeyAscii | String. Data to send to the host.

Remarks

ASCII characters are normally presented as a string of length one, whereas function keys and others may generate strings of greater length.


NewLine Event

Example

Fires when the cursor in the VT display changes rows. This event is useful for capturing data to a disk file or other destination.

Syntax

Private Sub Object_NewLine ( Data As String )

Part | Description
Object | Evaluates to a VT Control.
Data | String. Contains the line of text the cursor was positioned at before the cursor changed rows.


Resize Event

Example

Fires when the width or height of the VT Control changes. When the AutoResize property is True, this can occur when the Rows, Cols, Font, ColWidth, RowHeight or StatusLine property changes. It may be convenient to resize the size of the parent form when this event fires.

Syntax

Private Sub Object_Resize ( )

Part | Description
Object | Object expression that evaluates to a VT Control.


AttributeConstants

Enumerates the VT attributes that a host command is attempting to alter as represented by the Attr parameter of the HostCommand event.

Value | Constant | Description
0 | vtTerminal | Terminal emulation mode.
1 | vtAutoPrint | Auto Print mode enabled or disabled.
2 | vtAutoRepeat | Auto Repeat mode enabled or disabled.
3 | vtAutoWrap | Auto Wrap mode enabled or disabled.
4 | vtForeColor | Foreground color altered.
5 | vtBackColor | Background color altered.
6 | vtBoldColor | Bold color altered.
7 | vtBell | Terminal bell enabled or disabled.
8 | vtCols | Column width set to 80 or 132.
9 | vtCursor | Cursor displayed or disabled.
10 | vtCursorKeys | Cursor keys set to ANSI or Application.
11 | vtCursorStyle | Cursor style set to blocked or underline.
12 | vtEnabled | VT display and keyboard enabled or disabled.
13 | vtInverted | Inverted mode (swap foreground and background colors) enabled or disabled.
14 | vtKeypad | Keypad set to send ASCII chars or escape sequences.
15 | vtNewLine | End-of-line set to CR or CR/LF.
16 | vtOnline | Sets host on-line or off-line.
17 | vtPrinterController | Send all data to default system printer enabled or disabled.
18 | vtScrollType | Scroll type set to jump scrolling or smooth scrolling.
19 | vtTabs | Tab stops altered.


ClickConstants

Enumerates the values of the Click parameter of the Click event.

Value | Constant | Description
0 | vtLeftDown | Left mouse button was pressed down.
1 | vtLeftUp | Left mouse button was released.
2 | vtRightDown | Right mouse button was pressed down.
3 | vtRightUp | Right mouse button was released.
4 | vtLeftDblClick | Left mouse button was double-clicked.
5 | vtRightDblClick | Right mouse button was double-clicked.


ColumnConstants

Enumerates the values of the Cols property.

Value | Constant | Description
80 | vtCols80 | 80 character column width.
132 | vtCols132 | 132 character column width.


CursorKeyConstants

Enumerates the values of the CursorKeys property. The cursor keys can be set up to provide ANSI cursor control or application control. See Key Mapping for more information.

Value | Constant | Description
0 | vtCursorNormal | Cursor keys generate ANSI cursor control sequences to represent Up, Down, Left, and Right.
1 | vtCursorApp | Cursor keys generate application control sequences.


CursorStyleConstants

Enumerates the values of the CursorStyle property.

Value | Constant | Description
0 | vtBlock | Use a blocking cursor.
1 | vtUnderline | Use an underline cursor.


KeypadConstants

Enumerates the values of the Keypad property. The keypad can generate numeric values or application-specific values. See Key Mapping for more information.

Value | Constant | Description
0 | vtNumeric | Keypad keys generate numeric values.
1 | vtApp | Keypad keys generate application specific values.


NationalCharSetConstants

Enumerates the national character sets exposed by the NationalCharSet property.

Value | Constant | Description
0 | vtAscii | ASCII mode (no national character set replacement).
1 | vtBritish | British character set.
2 | vtDutch | Dutch character set.
3 | vtFinnish | Finnish character set.
4 | vtFrench | French character set.
5 | vtFrenchCanadian | French Canadian character set.
6 | vtGerman | German character set.
7 | vtItalian | Italian character set.
8 | vtNorwegianDanish | Norwegian Danish character set.
9 | vtPortuguese | Portuguese character set.
10 | vtSpanish | Spanish character set.
11 | vtSwedish | Swedish character set.
12 | vtSwiss | Swiss character set.


NewLineConstants

Enumerates the end-of-line sequences sent to the host in response to an end of line character (ENTER key). Used by the NewLine property.

Value | Constant | Description
0 | vtCrOnly | CR only (ASCII 13).
1 | vtCrLf | CR/LF combination (ASCII 13 and ASCII 10).


ScrollTypeConstants

Enumerates the values of the ScrollType property. The display screen can perform smooth scrolling or jump scrolling.

Value | Constant | Description
0 | vtJump | Scrolling uses jump scrolling.
1 | vtSmooth | Scrolling uses smooth scrolling.


ShiftConstants

Enumerates the values of the Shift parameter of the KeyDown event. One or more of these values are added together to represent shift combinations.

Value | Constant | Description
1 | vtShift | Shift key was pressed.
2 | vtControl | Control key was pressed.
4 | vtAlt | Alt key was pressed.


StyleConstants

Enumerates the character styles for text returned by the Style property. One or more of these values are added together to represent the style of each character.

Value | Constant | Description
0 | vtStyleNormal | Normal character style.
1 | vtStyleInverse | Foreground and background colors are reverse.
2 | vtStyleBold | Character color is bolded.
4 | vtStyleBlink | Character is set to blink.
8 | vtStyleUnderline | Character is underlined.


TermTypeConstants

Enumerates the values of the TermType property. See Key Mapping for more information.

Value | Constant | Description
0 | vtTty | No emulation.
1 | vt52 | VT52 terminal emulation.
2 | vt100 | VT100 terminal emulation.
3 | vt220_7 | VT220 terminal emulation, 7-bit only.
4 | vt220_8 | VT220 terminal emulation, 8-bit.
5 | vt320_7 | VT320 terminal emulation, 7-bit only.
6 | vt320_8 | VT320 terminal emulation, 8-bit.


VirtualKeyConstants

Enumerates the values of the Keys parameter of the Click event. One or more of these values are added together to represent key combinations.

Value | Constant | Description
1 | vtLeftBut | Left mouse button was pressed.
2 | vtRightBut | Right mouse button was pressed.
4 | vtShiftKey | Shift key was pressed.
8 | vtControlKey | Control key was pressed.
16 | vtMiddleBut | Middle mouse button was pressed.


PowerTCP FTP Tool

Support Licensing Distribution

Copy files between your client and any FTP server—a single method call will do. Set options using simple properties, and data will even spool to/from memory. List entries are captured as objects, so parsing is eliminated—a superior performer for any application.

Controls

Control | Description
FTP Control | Transfers files

Supporting Objects

Object | Description
ListEntry Object | Provides easy access to file information provided by an FTP listing
ListEntries Object | Collection of ListEntry Objects

Sample Projects

The following sample projects demonstrate how to use the FTP Tool:

Project | Description
FTP Client | Demonstrates an FTP Client application using non-blocking techniques. Visual Basic 5/6.
FTP Import | Allows users to enter file URL into a dialog. Provided that the file is the correct format it will be downloaded and imported into the database. Access 97.
FTP ListView Client | Demonstrates an FTP Client application using blocking techniques. Now includes proxy support. Visual Basic 6, Visual C++ 6, PowerBuilder, Delphi 4, and BCB5.
FTP ProxyLogin | Demonstrates how to use the 5 basic types of FTP proxies/firewalls. Visual Basic 5/6.
GetSite | Shows how to use MGet to get multiple files to a specified local directory. Visual Basic 5 and Visual C++ 6.
GetUrl | Demonstrates the use of the Get Method. Visual Basic 5/6 and Visual C++ 6.
MListView Client | Similar to the FTP ListView Client. This sample combines the "M" Commands (MGET/MPUT) with the drag and drop capabilities of VB6 to create a more familiar user interface. Now includes proxy support. Visual Basic 6 only.
PutSite | Shows how to use MPut to put multiple files from a specified local directory. Visual Basic 5 and Visual C++ 6.
PutUrl | Demonstrates the use of the Put Method. Visual Basic 5/6 only.
ManualProxy | Shows how to bypass the ProxyType Property and do manual proxy logins. Visual Basic 5/6.

Online ASP Samples

These ASP samples demonstrate the use of the FTP Tool on the Internet. You must have an active Internet connection to view these Samples.

Sample

Description

FTP on the Web

The FTP Control gets a file listing, and will download a file and show it in a text window.


FTP Control

Properties Methods Events Constants

Use the FTP Control to copy files between a local client and any FTP server. Server-to-server transfers are also supported.

Note File transfers use all available bandwidth to minimize the time it takes to transfer a file or buffer.

Miscellaneous

Product | PowerTCP FTP Tool
Prog ID | Dart.Ftp.1
File | DartFtp.dll
Dependencies | DartSock.dll
Threading | Apartment Model
Licensed | Yes


FTP Control Usage

The FTP Control provides you with the most functionality in the fewest programming steps. An invisible control, it can operate transparently in the background while the user of your application is doing other tasks, or it can operate interactively like most popular FTP applications.

Simple methods perform the following tasks:

  1. Authentication. Use the Login method to connect and log into any FTP server in one easy step.

  2. File Transfers. Send or receiver files by invoking the Store or the Retrieve method. You can even transfer to/from memory buffers!

  3. Directory Listings. Use the List method to get directory listings. Each listing is put into the Listing property, which can be subsequently cached. Since this property is a ListEntries Object, file information is automatically parsed.

  4. Other functions. PowerTCP completely supports RFC 959 so all the power of FTP is available through this control.

  5. Use the Get and Put methods to transfer a file with only one line of code.

The following sections describe two typical applications.

Transparent Use

You will want your file transfer to operate in the background with minimal system impact. We recommend that you program the file transfer using non-blocking operation, so the user interface is not affected in any way. The following VB example shows how to retrieve a file when a timer event fires:

Private Sub TimerFires()

' Set Timeout to indicate non-blocking use

Ftp1.Timeout = 0

' Specify the address of the server, your username and password

Ftp1.Login "ftp.test.com", "MyUserName", "MyPassWord"

' The Progress Event will notify us when it is done...

End Sub

Private Sub Ftp1_Progress(ByVal FtpCmd As DartFtpCtl.CommandConstants, ByVal Status As DartFtpCtl.StatusConstants, ByVal Reply As String, ByVal Count As Long, ByVal Size As Long)

If Status = ftpOk Then

' Use select to control what to do next

Select Case FtpCmd

Case ftpPassword

' we are logged in, so issue Retrieve command

Ftp1.Retrieve "RemoteFile.txt", "LocalFile.txt"

Case ftpRetrieve

' file transfer is complete...close

Ftp1.Logout

End Select

End If

End Sub

Interactive Use

Transparent operation is less important (you may want to put up an hourglass pointer, for example). It may be acceptable to use blocking operation as shown in the following VB example:

' Use the Timeout property to establish blocking behavior

Ftp1.Timeout = 1000

' Specify the address of the server, your username and password

Ftp1.Login "ftp.test.com", "MyUserName", "MyPassWord"

' Copy the file into the current default directory

Ftp1.Retrieve "RemoteFile.txt"

Ftp1.Close

Refer to FTP Control Non-Blocking Sample and FTP Control Blocking Sample for more information on blocking and non-blocking operation.


FTP Protocol Overview

This topic covers:

  • Protocol Overview

  • Control Connection

  • Data Connection

  • Data Representation

  • Common Commands

  • FTP and PowerTCP

Protocol Overview

The File Transfer Protocol (FTP) provides a standard method for transferring files between computers. You can get directory listings, retrieve files, upload files, and more. A client accesses files stored on a server. A server responds to clients, providing directory and file data. FTP uses both TCP and Telnet, differing from other protocols by using the following two connections:

  • Control connection using Telnet

  • Data connection using TCP

Back to Top

Control Connection

A control connection is formed to initiate a session. It is used for login, sending commands, and receiving information. The control connection utilizes the Telnet protocol and usually uses the FTP default port 21.

A control connection is generally made between a client and server. However, a client can control file transfers between two servers. See RFC 959 for detailed information about this and other advanced features.

During login, a user name and password must be sent. Many FTP servers support anonymous FTP where the user name is "anonymous" and the password is the user's email address.

After authentication, commands can be sent over the control connection. Typical commands are RETR (retrieve a file), STOR (upload a file), and QUIT (log off). For more information, refer to the RFC.

A server responds to commands with three-digit codes and descriptions across the control connection. Each digit has a different meaning, shown in the following tables (the code descriptions are taken directly from the RFC):

First-Digit Codes

Code | Description
1yz | Positive preliminary reply. The requested action is being initiated; expect another reply before proceeding with a new command. (The user-process of sending another command before the completion reply would be in violation of protocol; but server-FTP processes should queue any commands that arrive while a preceding command is in progress.) This type of reply can be used to indicate that the command was accepted and the user-process may now pay attention to the data connection, for implementations where simultaneous monitoring is difficult. The server-FTP process may send at most, one 1yz reply per command.
2yz | Positive completion reply. The requested action has been successfully completed. A new request may be initiated.
3yz | Positive intermediate reply. The command has been accepted, but the requested action is being held, pending receipt of further information. The user should send another command specifying this information. This reply is used in command sequence groups.
4yz | Transient negative completion reply. The command was not accepted and the requested action did not take place, but the error condition is temporary and the action may be requested again. The user should return to the beginning of the command sequence, if any. It is difficult to assign a meaning to transient, particularly when two distinct sites (Server- and User-processes) have to agree on the interpretation. Each reply in the 4yz category might have a slightly different time value, but the intent is that the user-process is encouraged to try again. A rule of thumb in determining if a reply fits into the 4yz or 5yz (Permanent Negative) category is that replies are 4yz if the commands can be repeated without any change in command form or in properties of the User or Server. For example, if the command is spelled the same with the same arguments used and the user does not change his file access or user name; then the server does not put up a new implementation.)
5yz | Permanent negative completion reply. The command was not accepted and the requested action did not take place. The User-process is discouraged from repeating the exact request (in the same sequence). Even some permanent error conditions can be corrected, so the human user may want to direct his User-process to reinitiate the command sequence by direct action at some point in the future (for example, after the spelling has been changed, or the user has altered his directory status).

Second-Digit Codes

Code | Description
x0z | Syntax. These replies refer to syntax errors, syntactically correct commands that don't fit any functional category, unimplemented or superfluous commands.
x1z | Information. These are replies to requests for information, such as status or help.
x2z | Connections. Replies referring to the control and data connections.
x3z | Authentication and accounting. Replies for the login process and accounting procedures.
x4z | Not defined.
x45z | File system. These replies indicate the status of the Server file system in relation to the requested transfer or other file system action.

Third-Digit Codes

The third-digit codes are more detailed. Refer to the RFC for these. Normally, a response consists of the code followed by an English description, as shown below:

200 PORT command successful.

150 Opening ASCII mode data connection for /bin/ls.

226 Transfer complete.

221 Goodbye.

Back to Top

Data Connection

A data connection is used when a:

  1. Client sends a file to the server.

  2. Server sends a file to the client.

  3. Server sends a directory listing to the client.

Once a data connection has transferred its data, the connection is closed—it is dynamic and only one exists at a time. Data connection consists of the following steps:

  1. Client chooses an unused port number on which to accept the connection.

  2. Client waits for a connection on that port.

  3. Client uses the PORT command to send the port number to the server over the control connection.

  4. Client sends a transfer command (for example, STOR, RETR, or LIST).

  5. Server connects to the correct port using its local port 20.

After the data connection is created, the file transfer or directory listing occurs and the connection closes.

Back to Top

Data Representation

Data can be transferred in different modes. File type, format control, structure, and transmission mode can all be controlled. However, only file type is commonly used; the other features are generally not changed.

Of the following four options for file type, only ASCII and Image are commonly used:

  • ASCII. This is the default mode. Different computer systems implement new-line characters differently. Many UNIX systems use the ASCII character 13 (CR). Microsoft Windows uses ASCII character 13 followed by 10 (CR-LF). When ASCII mode is enabled, proper conversions are made between the server and the client. Note Use this mode only for text files. Using this mode on binary files cause corruption.

  • Image (binary). This sends an exact replica of the file across the connection. Use this for all binary files, which includes all executable programs and many document files.

  • EBCDIC. Not commonly used. It is an alternative way of transferring files between two EBCDIC systems.

  • Local file type. Not commonly used. It is a method of transferring data between two computers with different byte sizes.

Back to Top

Common Commands

The table below lists some common commands:

Command | Description
ABOR | Cancel the previous command issued, and halt any data transfer in progress.
LIST filelist | List all files and directories in the directory.
PASS password | Send the user's password to the server during login.
PORT n1,n2,n3,n4,n5,n6 | Send the client's IP address in the first four arguments and the port in the fifth and sixth arguments.
QUIT | Log off the server.
RETR filename | Retrieve a file from the server.
STOR filename | Place a file on the server.
TYPE type | Specify the file type.
USER username | Send the user's name to the server.

Back to Top

FTP and PowerTCP

  1. Login. PowerTCP combines the control connection establishment process with the login (authentication) process.

  2. Command Sequencing. PowerTCP creates an internal queue of commands and executes them as each command completes.

  3. Data Connection Establishment. PowerTCP handles the details of establishing a data connection (sending the TYPE command if necessary, listening on a local port, sending the PORT or PASV command, accepting a passive connection, etc.) automatically when any data transfer commands are used.

  4. File Spooling. If a local file is specified, PowerTCP transfers data to or from that file. However, the program can still opt to have complete control over all data transferred.

  5. Renaming Files. PowerTCP sequences the RNFR and RNTO commands so the application does not have to.

  6. Restart. PowerTCP sequences the REST command with the data transfer command currently in progress.

  7. Error Checking and Synchronization. PowerTCP saves state information that is necessary for the correct interpretation of replies coming from the server. Replies are then reported to the application with the associated status information. All replies are checked for validity against the last command sent.

  8. Complete RFC 959 functionality. Supports using your own command strings, bypassing any status checking. PowerTCP can even be used to control two FTP servers, transferring data between them.

A method is provided for many of the FTP commands (except where related commands have been sequenced together for your convenience). For example, single commands like HELP have one method associated with each. Other command sequences, such as USER, PASS and ACCT are started by a single method, where PowerTCP takes care of the sequencing. File transfer commands (Store and Receive Methods) automatically sequence TYPE, PORT, REST, STRU and transfer commands, greatly simplifying the mechanism of completing both normal and passive data connections.

In general, there is a one-to-one correspondence between FTP commands and FTP Control methods and properties. The control "remembers" what command was sent last, checking for valid and invalid replies.

Refer to RFC 959 for a thorough description of each command, along with more general descriptions and guidance describing how the FTP protocol operates.

Back to Top


FTP Control Non-Blocking Sample

Structure the code so that sequencing is controlled by code in the events accomplishes the file download in a non-blocking way. The benefit of sequential code is offset by the greater benefit of robust code that allows PowerTCP to operate relatively independently of the application and any additional processing you may be doing for your user:

' Set Timeout to indicate non-blocking use

Ftp1.Timeout = 0

' Specify the address of the server, your username and password

Ftp1.Login "ftp.test.com","MyUserName","MyPassWord"

' the Login process will notify us when it is done...

Private Sub Ftp1_Progress (FtpCmd As CommandConstants, Status As StatusConstants, Reply As String, Count As Long, Size As Long)

If Status = ftpOk Then

' Use select to control what to do next

Select Case FtpCmd

Case ftpPassword

' we are logged in, so issue Retrieve command

Ftp1.Retrieve "RemoteFile.txt", "LocalFile.txt"

Case ftpRetrieve

' file transfer is complete...close

Ftp1.Logout

End Select

ElseIf Status = ftpInProgress Then

If FtpCmd = ftpRetrieve Then Label1.Caption = Count/Size*100 & "%" & " done..."

End If

End Sub

Adding code to the Error event and the State event can provide additional user feedback and error recovery mechanisms to make your application robust and bug-free.


FTP Control Blocking Sample

By default, Timeout is a positive value indicating that all methods should wait until finished before returning. This is called blocking and greatly simplifies the sequencing of operations and error recovery. Consider the following FTP code sample:

' Use the Timeout property to establish blocking behavior

Ftp1.Timeout = 1000

' Specify the address of the server, your username and password

Ftp1.Login "ftp.test.com","MyUserName","MyPassWord"

' Copy the file into the current default directory

Ftp1.Retrieve "RemoteFile.txt", "LocalFile.txt"

Ftp1.Logout

The sequencing of the initialization, the file transfer, and the termination is straightforward and errors are handled automatically—any failure will result in program termination. Since all the code executed without error, the file now resides locally.

The following code sample shows how to add error handling so the application will not terminate due to a communications failure:

On Error GoTo OnError

' Use the Timeout property to establish blocking behavior

Ftp1.Timeout = 1000

' Specify the address of the server, your username and password

Ftp1.Login "ftp.test.com","MyUserName","MyPassWord"

' Copy the file into the current default directory

Ftp1.Retrieve "RemoteFile.txt", "LocalFile.txt"

Ftp1.Logout

Exit Sub

OnError:

' Don't use MsgBox because that interrupts event notification

Label1.Caption = "Error #" + CStr(Err.Number) + ": " + Err.Description

Now we want to put up a progress indication for our user by inserting code in the following Progress event:

Private Sub Ftp1_Progress (FtpCmd As CommandConstants, Status As StatusConstants, Reply As String, Count As Long, Size As Long)

If FtpCmd = ftpRetrieve Then

Label2.Caption = (Count/Size)*100 & "%" & " done..."

End If

End Sub

The code now puts up progress information, but the following problems persist:

  1. During the file download, for single-thread applications, no other work can be done because the thread is trapped in the Retrieve method. Unfortunately, many commercial applications are still written this way.

  2. If the user wants to exit the application, you must defeat it because you cannot allow the user to unload while you are executing the download.

  3. If the user initiates another activity through the user interface, make sure the user does not affect the file download (by calling an FTP method or capturing the thread for any length of time).

You can overcome these limitations by using non-blocking operation.


Firewalls

The simplest firewall may simply restrict connections to those that originate within the local net. For this type, ensure the Passive property is True, and the data connection will always be directed outbound.

Other kinds of firewalls are either Transparent or Non-Transparent.

Transparent Firewalls

Many FTP firewalls (or proxies) are transparent, meaning that no special consideration is necessary. Your application will operate without knowing a firewall is being used. IP packets are intercepted by the firewall, operation is validated, and you get through (transparently) without knowing it is there.

Non-Transparent Firewalls

There are several types of non-transparent firewalls. The FTP Tool includes native support for a variety of firewall settings. To set the firewall type, please see ProxyType property and use ProxyHost, ProxyPassword, ProxyPort, and ProxyUsername accordingly. Manual firewall control is also possible, and different techniques are used to traverse non-transparent firewalls, as discussed below (the included examples are for educational purposes as they are handled natively in the current version of the FTP Tool):

  1. SITE hostname. Use the Login method to connect to the firewall with User and Password included. Then, use the Site method to make the connection to the remote FTP site. The Modifier parameter is used to specify the remote FTP server (for example, "ftp.dart.com").

  2. USER after logon. First, use the Login method to connect to the firewall with User and Password included. Then, use the Command method to send a second ftpUser command (for example, "USER mike@ftp.dart.com").

  3. USER with no logon. Use the Login method to connect to the firewall. The User parameter is used to specify the user and FTP server address (for example, " mike@ftp.dart.com ") and no Password is required.

  4. Proxy OPEN. Use the Login method to connect to the firewall without User or Password. Then, use the Command method to send an OPEN RemoteName command (for example, "OPEN ftp.dart.com").

It is possible that you may find other cases not documented here. Refer to your firewall documentation. The FTP Control was designed to accommodate use with any firewall; contact support if your requirement is not met.


Allocate Property

Indicates whether space must be allocated on a server as part of the Store method.

Syntax

Object.Allocate

Part | Description
Object | Evaluates to an FTP Control or a SecureFtp Control.

Data Type

Boolean

Remarks

The default value is False.

You can set this property at design time. Some servers may require its use. When set to True, an ftpAllocate command is sent with the proper file size before starting a file transfer.


Directory Property

Working directory on the server.

Syntax

Object.Directory

Part | Description
Object | Evaluates to an FTP Control or a SecureFtp Control.

Data Type

String

Remarks

After the client logs in with the Login method, this property sets or returns the working directory. If not logged in, an empty string is returned.

The value is set or returned on demand. Upon completion of the Login method and the ChangeDirectoryUp method, the actual value is unknown. When the value of this property is known, it is immediately returned without checking the server.

When this property is read and the value is unknown, a blocking ftpPrintDirectory command retrieves the value from the server. The Blocked property is True while this information is retrieved (a ptTimeout error will be thrown if the server does not respond within 30 seconds).

When this property is set, a blocking ftpChangeDirectory command is sent to the server. The Blocked property is True while this occurs (a ptTimeout error will be thrown if the server does not respond within 30 seconds). After setting this property the actual value on the server is unknown, so a blocking ftpPrintDirectory command is sent the next time this property is read.

If non-blocking operation is desired, you can set the Timeout property to 0 and:

  • Use the Command method with the string "CWD 'NewDirectory'" to change the working directory.

  • Use the Command method with the string "PWD" to get the working directory (the Status parameter of the Progress event will contain a 257 code and the name of the working directory).

Note Use error handling, since this property can return a run-time error.

Note Reading or setting this property may cause the Progress Event to fire while blocking, so you will not be able to use other methods from within this event.

Error Codes

The Directory property may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked (another blocking method is active)

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptTimeout


FileStructure Property

File structure to be used for subsequent file transfers.

Syntax

Object.FileStructure

Part | Description
Object | Evaluates to an FTP Control or a SecureFtp Control.

Data Type

FileStructureConstants

Remarks

The default value is ftpFile.

This property can be set at design time. The ftpFileStructure command is sent automatically when necessary.


Listing Property

Example

Object containing results from the last use of the List method or the NameList method.

Syntax

Object.Listing

Part | Description
Object | Evaluates to an FTP Control or a SecureFtp Control.

Data Type

ListEntries Object

Remarks

Contents are updated each time the List method or the NameList method is used to request listing information. You can save this information for later use by assigning it to a new object.


Passive Property

Indicates how the data connection is formed.

Syntax

Object.Passive

Part | Description
Object | Evaluates to an FTP Control or a SecureFtp Control.

Data Type

Boolean

Remarks

The default value is True.

You can set this property at design time. When set to True, an ftpPassive command is sent before a data transfer and the control connects to the server. When set to False, an ftpPort command is sent before a data transfer and the server connects to the control.

Firewalls often restrict incoming connections, while allowing outgoing connections, so the default value of True makes this control firewall-friendly.

If the server does not work with the ftpPassive command, set this property to False.


ProxyHost Property

Example

Specifies the name or address of the proxy server that requests are to be routed through.

Syntax

Object.ProxyHost

Part | Description
Object | Evaluates to a PowerTCP Control.

Data Type

String

Remarks

Read this property to determine the name or address of the current proxy server.

Write to this property to set the name or address of the proxy server used for the next connection.

When using the Ftp Control this property is ignored when Object.ProxyType is set to ftpProxyNone.


ProxyPassword Property

Example

Password to be sent on all requests through a proxy server that requires authentication.

Syntax

Object.ProxyPassword

Part | Description
Object | Evaluates to an PowerTCP Control.

Data Type

String

Remarks

Read this property to determine the password on the current proxy server.

Write to this property to set the password on the proxy server used for the next connection.

When using the Ftp Control this property is ignored when Object.ProxyType is set to ftpProxyNone, ftpProxyUserNoLogin, ftpProxyPipe, ftpProxyOpen or ftpProxySiteHost when no ProxyUsername is specified.


ProxyPort Property

Example

Specifies the port used by proxy server that requests are to be routed through.

Syntax

Object.ProxyPort

Part | Description
Object | Evaluates to an PowerTCP Control.

Data Type

Long

Remarks

Read this property to determine the port used by the current proxy server.

Write to this property to set the port used by the proxy server used for the next connection.

When using the Ftp Control this property is ignored when Object.ProxyType is set to ftpProxyNone.


ProxyType Property

The type of proxy server used for this connection.

Syntax

Object.ProxyType

Part | Description
Object | Evaluates to an FTP Control.

Data Type

FtpProxyTypeConstants

Remarks

Read this property to determine what type of proxy server is currently being used.

Write to this property to set the type of proxy server used for the next connection.

Please note that the SOCKS proxy implementation does not use binding due to lack of server support. If binding is needed in conjunction with SOCKS, please use the TCP Control in conjunction with its native SOCKS support.


ProxyUsername Property

Example

Username to be sent on all requests through a proxy server that requires authentication.

Syntax

Object.ProxyUsername

Part | Description
Object | Evaluates to an PowerTCP Control.

Data Type

String

Remarks

Read this property to determine the username on the current proxy server.

Write to this property to set the username on the proxy server used for the next connection.

When using the Ftp Control this property is ignored when Object.ProxyType is set to ftpProxyNone, ftpProxyUserNoLogin, ftpProxyPipe, ftpProxyOpen or ftpProxySiteHost when no ProxyPassword is specified.


Restart Property

Indicates the server supports a restart mechanism for file downloads.

Syntax

Object.Restart

Part | Description
Object | Evaluates to an FTP Control or a SecureFtp Control.

Data Type

Boolean

Remarks

Read-only.

Some servers do not support a restart mechanism for downloaded files that have been partially received. By reading this property you can discover if restarts are supported.

The value is returned on demand. Upon completion of the Login method the actual value is unknown.

When this property is read and the value is unknown, a blocking ftpRestart command is sent to test the server. The Blocked property is True while the reply is retrieved and will not timeout unless the connection fails. A True or False value is returned.

Once the value of this property is known, it is returned without checking the server.

If blocking is not desired, set the Timeout property to 0 and use the Command method with the string "REST 100" to get a reply from the server. If the Status parameter of the Progress event is ftpOk then the server supports the restart mechanism.

Note Use error handling, since this property can return a run-time error.

Error Codes

The Restart property may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked (another blocking method is active)

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptTimeout


StoreType Property

Type of store that will be performed when the Store method is called.

Syntax

Object.StoreType

Part | Description
Object | Evaluates to an FTP Control or a SecureFtp Control.

Data Type

StoreConstants

Remarks

The default is storeNormal. You can set this property at design time.


System Property

Type of operating system used by the server.

Syntax

Object.System

Part | Description
Object | Evaluates to an FTP Control or a SecureFtp Control.

Data Type

String

Remarks

Read-only.

This property is used after the Login method has completed. The value is returned on demand. The first time it is used, a blocking ftpSystem command is sent to the server. Blocked is True while this information is retrieved, and will not timeout unless the connection fails. Once the value of this property is known, it's immediately returned without checking the server.

If blocking behavior is not desired, you can set the Timeout Property to 0 and use the Command method with the string "SYST" to request system information.

User error handling, since this property can return a run-time error.

Error Codes

The System property may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptTimeout

  • ptBlocked (another blocking method is active)

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptConnectionAborted

  • ptConnectionReset


TransferMode Property

Transfer mode to be used for subsequent file transfers.

Syntax

Object.TransferMode

Part | Description
Object | Evaluates to an FTP Control or a SecureFtp Control.

Data Type

TransferModeConstants

Remarks

The default value is ftpStream (this is correct for most applications). You can set this property at design time.

The ftpTransferMode command will only be sent if the server needs it before a transfer starts.


Type Property

Data type to be used for subsequent file transfers.

Syntax

Object.Type

Part | Description
Object | Evaluates to an FTP Control or a SecureFtp Control.

Data Type

TypeConstants

Remarks

The default value is ftpAscii. You can set this property at design time.

The default value indicates that a CR/LF pair should be put at the end of every line in the file before sending it. Since the Windows operating system already uses a CR/LF pair as the native line separator, there is no need to modify the stream as it is received or sent. Another operating system that uses a single CR as the native line separator, however, must expand the size of most files it sends, and shrink the size of most files it receives (to change the line separator to/from a CR/LF pair).

When set to ftpImage, the line separator remains unmodified, making this property setting necessary for sending and receiving binary files (that may contain line separators).

The ftpType command is only sent if the server needs it before a transfer starts.


AbortCommand Method

Gracefully abort the last command sent.

Syntax

Object.AbortCommand

Part | Description
Object | Object expression that evaluates to an FTP Control or a SecureFtp Control.

Remarks

Sends the ftpAbort command. The server will abort the current command in progress (if any), and will then accept new commands.

This method immediately returns and the Progress event fires with FtpCmd = ftpAbort when the reply is received. If the Blocked property is True (another method is currently executing), then that method will immediately return with a ptBlocked error.

This method always returns immediately.

Error Codes

The AbortCommand method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptTimeout


ChangeDirectoryUp Method

Set the working directory to the parent directory. The Directory property can be checked to discover the new working directory.

Syntax

Object.ChangeDirectoryUp

Part | Description
Object | Object expression that evaluates to an FTP Control or a SecureFtp Control.

Remarks

Sends the ftpChangeDirectoryUp command.

If Timeout is greater than 0, ChangeDirectoryUp blocks until a reply is received from the server or a ptTimeout error occurs.

If Timeout is 0, ChangeDirectoryUp immediately returns and the Progress event fires with FtpCmd = ftpChangeDirectoryUp when the reply is received.

Error Codes

The ChangeDirectoryUp method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptTimeout


Command Method

Send any command string to the server. This method is useful for using servers that have an extended vocabulary.

Syntax

Object.Command FtpCommand, Result

Part | Description
Object | Object expression that evaluates to an FTP Control or a SecureFtp Control.
FtpCommand | String expression. Specifies the command to send. CR/LF is appended to each command, so you should not include it.
Result | Undimensioned string. Where the reply from the server will be put. Any contents will be replaced.

Remarks

If Timeout is greater than 0, Command blocks until a reply is received from the server or a ptTimeout error occurs.

If Timeout is 0, Command immediately returns and the Progress event event fires with FtpCmd = ftpCommand when the reply is received. The Result parameter is used to capture the reply, so it must not go out of scope while the command completes (it must have file or global scope).

Error Codes

The Command method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptInvalidParam1 (FtpCommand is empty)

  • ptInvalidParam2 (Result is not a string)

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptTimeout


Delete Method

Delete a file on the server.

Syntax

Object.Delete PathName

Part | Description
Object | Object expression that evaluates to an FTP Control or a SecureFtp Control.
PathName | String expression. Specifies the file to delete.

Remarks

Sends the ftpDelete command.

If Timeout is greater than 0, Delete blocks until a reply is received from the server or a ptTimeout error occurs. If Timeout is 0, Delete immediately returns and the Progress event fires with FtpCmd = ftpDelete when the reply is received.

Error Codes

The Delete method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptInvalidParam1 (PathName is invalid)

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptTimeout


Get Method

Example

Log in, get a file, and log out in one step.

Syntax

Object.Get URL [ , Result ] [ , Marker ]

Part | Description
Object | Object expression that evaluates to an FTP Control or a SecureFtp Control.
URL | String expression. Specifies the Universal Resource Locator. This parameter is modeled after IE 4.0.
Result | Optional String specifying the destination (local) file name, or an undimensioned String or Byte array that is dynamically expanded and filled with file data. If not specified or NULL, the filename from the URL (without path) is used in the local default directory.
Marker | Optional Long. Specifies the number of characters that should be skipped. If a file transfer was previously interrupted, the Marker parameter can be used to start at an exact location, so the entire file does not have to be transferred. See the Restart property for more information. If the server does not support restarts and you specify Marker, PowerTCP retrieves the entire file and the Restart Property is set to False.

Remarks

Note This method supports only UNIX-style file systems (forward slashes specify the file path).

Establishes a connection and if necessary, sequences the following commands (refer to the CommandConstants topic for more information on these commands):

  • ftpCwd

  • ftpFileStructure,

  • ftpList

  • ftpLogout

  • ftpPassword

  • ftpPort or ftpPassive

  • ftpRestart (if Marker > 0)

  • ftpRetrieve

  • ftpSize

  • ftpTransferMode

  • ftpType

  • ftpUser

URL format (note that file path is relative to the root directory):

ftp://username:password@hostname:port/filepath

"ftp://" is optional, and can be omitted

"username:password@", if omitted, defaults to "anonymous:powertcp@"

":port", if omitted, defaults to "21"

Always blocks until complete or throws an error. Progress event fires as file data and replies are received.

If URL specifies a directory, then Result is not used and the Listing property is filled with the listing.

Error Codes

The Get method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptProtocol (a protocol error was encountered)

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptTimeout


Help Method

Example

Request helpful information from the server. The command takes an optional argument (for example, any command name) and returns more specific information as a response.

Syntax

Object.Help Result [ , Command ]

Part | Description
Object | Object expression that evaluates to an FTP Control or a SecureFtp Control.
Result | Undimensioned string where the reply from the server will be put. Any contents will be replaced.
Command | Optional String. Specifies the command you want help on.

Remarks

Sends the ftpHelp command.

If Timeout is greater than 0, Help blocks until a reply is received from the server or a ptTimeout error occurs. If Timeout is 0, Help immediately returns and the Progress event fires with FtpCmd = ftpHelp when the reply is received. The Result parameter is used to capture the reply so it must not go out of scope while the command completes (it must have file or global scope).

Error Codes

The Help method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptTimeout


List Method

Example

Get a file directory listing. The server sends name and supplementary information on each file found within the specified PathName. The Listing property is populated with this information.

Syntax

Object.List [ PathName ]

Part | Description
Object | Object expression that evaluates to an FTP Control or a SecureFtp Control.
PathName | Optional String expression. Specifies a path on the host. Wildcards are permitted, as well as modifiers for the list command. If this parameter is omitted then it defaults to all the files in the current directory.

Remarks

Type should be ftpAscii or ftpEbcdic. If a value of ftpImage is specified then lines may not terminate with a CR/LF, creating a formatting problem.

This method sequences and sends the ftpType, ftpPort or ftpPassive, and ftpList commands.

If Timeout is greater than 0, List blocks until the listing is received or a ptTimeout error occurs. If Timeout is 0, List immediately returns and the Progress event fires multiple times as each reply is received.

Error Codes

The List method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol (a protocol error was encountered),

  • ptTimeout


Login Method

Example

Connect to a server and send the commands to authenticate a session.

Syntax

Object.Login [ RemoteName ] [ , User ] [ , Password ] [ , Account ] [ , RemotePort ]

Part | Description
Object | Object expression that evaluates to an FTP Control or a SecureFtp Control.
RemoteName | Optional String expression. Specifies the name or IP address of the server.
User | Optional String expression. Specifies a user name for an account on the server.
Password | Optional String expression. Specifies the account password associated with User.
Account | Optional String expression. Specifies an account on the server.
RemotePort | Optional Long expression. Specifies the remote port to connect to. This defaults to 21 if not specified.

Remarks

If RemoteName is specified and State is not tcpClosed, then the existing session is immediately aborted.

If RemoteName is specified, then a connection is attempted. The State event fires if it succeeds; otherwise, the Error event fires.

If RemoteName is not specified and State is not tcpConnected, then a ptNotConnected error is generated. If RemoteName is not specified and State is tcpConnected, then a ftpReinitialize command is sent to prepare the server to authenticate again.

Once connected and ready to authenticate, the ftpUser, ftpPassword, and ftpAccount commands are sent to the server.

If Timeout is greater than 0, Login blocks until authentication is complete, an error occurs, or a ptTimeout error occurs. If Timeout is 0, Login immediately returns and the Progress event fires multiple times as each server reply is received.

Error Codes

The Login method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionRefused

  • ptConnectionReset

  • ptHostNotFound

  • ptInvalidParam1 (RemoteName is not a valid string)

  • ptNetworkDown

  • ptNetworkReset

  • ptNetworkUnreachable

  • ptNoBufferSpace

  • ptNoData

  • ptNotInitialized

  • ptProtocol (a protocol error was encountered)

  • ptTimeout

  • ptTryAgain


Logout Method

Gracefully log off and terminate the connection.

Syntax

Object.Logout

Part | Description
Object | Object expression that evaluates to an FTP Control or a SecureFtp Control.

Remarks

Sends the ftpQuit command and closes the connection.

If Timeout is greater than 0, Logout blocks until the connection is closed or a ptTimeout error occurs.

If Timeout is 0, Logout immediately returns and the Progress event fires with FtpCmd = ftpQuit when the reply is received, and then the State event fires when State changes to tcpClosed.

Error Codes

The Logout method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptTimeout


MakeDirectory Method

Create a directory.

Syntax

Object.MakeDirectory Pathname

Part | Description
Object | Object expression that evaluates to an FTP Control or a SecureFtp Control.
Pathname | String expression. Specifies the desired absolute or relative directory path.

Remarks

Sends the ftpMakeDirectory command.

If Timeout is greater than 0, MakeDirectory blocks until a reply is received from the server or a ptTimeout error occurs. If Timeout is 0, MakeDirectory immediately returns and the Progress event fires with FtpCmd = ftpMakeDirectory when the reply is received.

Error Codes

The MakeDirectory method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol (directory could not be created)

  • ptTimeout


MGet Method

Example

Retrieve (get) multiple files or entire directory trees.

Syntax

Object.MGet [ Source ] [ , Destination ] [ , FilesTransferred ] [ , FileErrors ]

Part | Description
Object | Object expression that evaluates to an FTP Control.
Source | Optional string. Specifies a list of files and directories to retrieve from the server. Wildcards are allowed, and multiple paths may be specified when separated by a space. Any path with a space must be enclosed within quotes (see Remarks below). Defaults to "".
Destination | Optional string. Specifies the destination directory to store the retrieved files. Defaults to current directory.
FilesTransferred | Optional DartStrings Object. Filled with a list of files that were successfully retrieved.
FileErrors | Optional DartStrings Object. Filled with a list of files with corresponding errors that failed to be retrieved.

Remarks

Use this method to retrieve multiple files based on wildcards, file lists, or entire branches of a directory tree.

The following table shows some examples of wildcards:

Wildcard | Meaning
* | Get all files in the directory and the subdirectories.
*.* | Get all files in the directory that contain a "." in the filename.
*.txt | Get all files in the directory with filenames that end with ".txt".
Test* | Get all files in the directory with filenames that begin with "Test"
*Test* | Get all files in the directory that contain "Test" in the filename.

Warning Using wildcards may cause unexpected results. For example, getting ~/* is not the same as getting /*. Some systems may return different directory listings.

You may use a mixture of filenames and wildcards for Source. Filenames and wildcards may contain full paths, such as /Test/test.txt or /Test/*.txt. When Source is * then all subdirectories that do not exist on the local system will be created. The entire directory tree structure will be created and retrieved. Any existing files will be replaced unless file permissions do not allow. If a file in the file list specified by Source does not exist then the file and the corresponding error, separated by a space, is added to FileErrors and operation will continue on to the next file. Any file with a space in its name is wrapped with quotes ("). The following examples illustrate enclosing within quotes any path containing a space:

  • Visual Basic """File one.txt"""

  • Visual C++ "/"File one.txt/""

If Timeout is 0 before this method is called then the default value of 30 seconds will be used. If Timeout is greater than 0 then the value of Timeout will be used. A ptTimeout error will occur if no activity is received from the server within the timeout period.

If Destination is not a directory or does not exist then a ptInvalidParam2 error will occur.

The type specified by the Type property will be used to transfer all the files.

Notes

  • If Source is omitted, then all the files in the current directory, excluding the subdirectories, are retrieved.

  • The AbortCommand method may be used to abort the file transfer without closing the control connection.

  • This command is only supported on systems that support UNIX or DOS listing styles. In addition, to support recursive transfers, the system must support the -R option for the LIST command.

Error Codes

The MGet method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptInvalidParam2

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol (a protocol error was encountered)

  • ptTimeout


MPut Method

Example

Store (put) multiple files or entire directory trees.

Syntax

Object.MPut [ Source ] [ , Destination ] [ , FilesTransferred ] [ , FileErrors ]

Part | Description
Object | Object expression that evaluates to an FTP Control.
Source | Optional string. Specifies a list of files and directories to store on the server. Wildcards are allowed, and multiple paths may be specified when separated by a space. Any path with a space must be enclosed within quotes (see Remarks below). Defaults to "".
Destination | Optional string. Specifies the destination directory, on the server, to store the files. Defaults to current server directory.
FilesTransferred | Optional DartStrings Object. Filled with a list of files that were successfully stored.
FileErrors | Optional DartStrings Object. Filled with a list of files with corresponding errors that failed to be stored.

Remarks

Use this method to store multiple files based on wildcards, file lists, or entire branches of a directory tree.

The following table shows some examples of wildcards:

Wildcard | Meaning
* | Store all files in the directory and the subdirectories.
*.* | Store all files in the directory that contain a "." in the filename.
*.txt | Store all files in the directory with filenames that end with ".txt".
Test* | Store all files in the directory with filenames that begin with "Test"
*Test* | Store all files in the directory that contain "Test" in the filename.

You may use a mixture of filenames and wildcards for Source. Filenames and wildcards may contain full paths, such as C:\Test\test.txt or C:\Test\*.txt. When Source is * then all subdirectories that do not exist on the server will be created. The entire directory tree structure will be created and stored. Any existing files will be replaced unless file permissions do not allow. If a file in the file list specified by Source does not exist then the file and the corresponding error, separated by a space, is added to FileErrors and operation will continue on to the next file. Any file with a space in its name is wrapped with quotes ("). The following examples illustrate enclosing within quotes any path containing a space:

  • Visual Basic """File one.txt"""

  • Visual C++ "/"File one.txt/""

If Timeout is 0 before this method is called then the default value of 30 seconds will be used. If Timeout is greater than 0 then the value of Timeout will be used. A ptTimeout error will occur if no activity is received from the server within the timeout period.

If Destination is not a directory or does not exist then a ptInvalidParam2 error will occur.

The type specified by the Type Property will be used to transfer all the files.

Notes

  • If Source is omitted, then all the files in the current directory, excluding the subdirectories, are stored.

  • The AbortCommand method may be used to abort the file transfer without closing the control connection.

  • This command is only supported on systems the support UNIX or DOS listing styles. In addition, to support recursive transfers, the system must support the -R option for the LIST command.

Error Codes

The MPut method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptFile

  • ptInvalidParam2

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol (a protocol error was encountered)

  • ptTimeout


NameList Method

Example

Get a file directory listing without file attributes. The server sends a file name for each file found within the PathName specified. The Listing property is filled with filenames (only the Name property is initialized).

Syntax

Object.NameList [ PathName ]

Part | Description
Object | Object expression that evaluates to an FTP Control or a SecureFtp Control.
PathName | Optional String expression. Specifies a path on the host. Wildcards are permitted. If this parameter is omitted then it defaults to all the files in the current directory.

Remarks

The Type property should be ftpAscii or ftpEbcdic. If ftpImage is specified, then lines may not terminate with a CR/LF, creating a formatting problem.

This method sequences and sends the ftpType, ftpPort or ftpPassive, and ftpNameList commands.

The Progress event fires as each reply is received. If Timeout is greater than 0, this method blocks until the listing is received from the server or a ptTimeout error occurs. If Timeout is 0, this method immediately returns.

Error Codes

The NameList method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol (a protocol error was encountered)

  • ptTimeout


NoOperation Method

Check the status of the control connection. The server should send an OK reply.

Syntax

Object.NoOperation

Part | Description
Object | Object expression that evaluates to an FTP Control or a SecureFtp Control.

Remarks

Sends the ftpNoOperation command.

If Timeout is greater than 0, NoOperation blocks until a reply is received from the server or a ptTimeout error occurs. If Timeout is 0, NoOperation immediately returns and the Progress event fires with FtpCmd = ftpNoOperation when the reply is received.

Error Codes

The NoOperation method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptTimeout


Put Method

Example

Login, store a file, and logout in one easy step.

Syntax

Object.Put URL [ , Source ] [ , Marker ]

Part | Description
Object | Object expression that evaluates to an FTP Control or a SecureFtp Control.
URL | String expression. Specifies the Universal Resource Locator. This parameter is modeled after IE 4.0.
Source | Optional String expression specifing the source (local) file name, or a String or Byte array that is filled with file data. If not specified or NULL, the filename from the URL (without path) is opened in the local default directory.
Marker | Optional Long expression. Specifies the number of characters in the source file that should be skipped. If not specified or 0, the entire file is transferred. If a file transfer was previously interrupted, the Marker parameter can be used to start at an exact location, so the entire file does not have to be transferred. When specified, the ftpAppend command is used, so the application must know the amount of data that has already transferred. If Source is a String or Byte array, then the entire contents is appended to the destination file.

Remarks

Note Only UNIX-style file systems are supported by this method (forward slashes specify the file path).

This method establishes a connection and sequences (if needed) the following commands:

Establishes a connection and if necessary, sequences the following commands (refer to the CommandConstants topic for more information on these commands):

  • ftpChangeDirectory

  • ftpFileStructure

  • ftpLogout

  • ftpPassword

  • ftpPort or ftpPassive

  • ftpStore or ftpAppend

  • ftpTransferMode

  • ftpType

  • ftpUser

URL format (note that file path is relative to the root directory):

ftp://username:password@hostname:port/filepath

"ftp://" is optional, and can be omitted

"username:password@", if omitted, defaults to "anonymous:powertcp@"

":port", if omitted, defaults to "21"

Always blocks until complete or throws an error. Progress event fires as each buffer is sent and any reply is received.

Error Codes

The Put method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol (a protocol error was encountered)

  • ptTimeout


RemoveDirectory Method

Remove a directory.

Syntax

Object.RemoveDirectory PathName

Part | Description
Object | Object expression that evaluates to an FTP Control or a SecureFtp Control.
PathName | String expression. Specifies the desired absolute or relative directory path.

Remarks

Sends the ftpRemoveDirectory command.

If Timeout is greater than 0, RemoveDirectory blocks until a reply is received from the server or a ptTimeout error occurs. If Timeout is 0, RemoveDirectory immediately returns and the Progress event fires with FtpCmd = ftpRemoveDirectory when the reply is received.

Error Codes

The RemoveDirectory method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptTimeout


Rename Method

Rename a file.

Syntax

Object.Rename FromFileName, ToFileName

Part | Description
Object | Object expression that evaluates to an FTP Control or a SecureFtp Control.
FromFileName | String expression. Specifies the old file name and path.
ToFileName | String expression. Specifies the new file name and path.

Remarks

Sequences and sends the ftpRenameFrom and ftpRenameTo commands.

If Timeout is greater than 0, Rename blocks until the file in renamed or a ptTimeout error occurs. If Timeout is 0, Rename immediately returns and the Progress event fires with FtpCmd = ftpRenameFrom and FtpCmd = ftpRenameTo when replies are received.

Error Codes

The Rename method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol

  • ptTimeout


Retrieve Method

Example

Retrieve (get) a complete file or part of a file starting at a specified position.

Syntax

Object.Retrieve RemoteFileName [ , Result ] [ , Marker ]

Part | Description
Object | Object expression that evaluates to an FTP Control or a SecureFtp Control.
RemoteFileName | String expression. Specifies the remote file name (with path) to retrieve.
Result | Optional String specifying the (local) destination file name, or an undimensioned String or Byte array that is dynamically expanded and filled with file data. If not specified or NULL, the FileName parameter (without path) is used as the local file name and put into the current default directory.
Marker | Optional Long. Specifies the number of characters that should be skipped. If a file transfer was previously interrupted, the Marker parameter can be used to start at an exact location, so the entire file does not have to be transferred. See the Restart property for more information. If the server does not support restarts and you specify Marker, PowerTCP will retrieve the entire file and the Restart Property will be set to False.

Remarks

Sequences and sends (if needed) the following commands (refer to the CommandConstants topic for more information on these commands):

  • ftpFileStructure

  • ftpPort or ftpPassive

  • ftpRestart

  • ftpRetrieve

  • ftpSize

  • ftpTransferMode

  • ftpType

The Progress event fires as file data and replies are received. If Timeout is greater than 0, Retrieve blocks until the file is received from the server or a ptTimeout error occurs. If Timeout is 0, Retrieve immediately returns. In this case, if the Result parameter is used to capture the data, it must not go out of scope while the command completes (it must have file or global scope).

Error Codes

The Retrieve method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptProtocol (a protocol error was encountered)

  • ptNotConnected

  • ptTimeout


Site Method

Example

Specify or request site-specific services. The nature of these services and the specification of their syntax can be found in the Result parameter of the Help method.

Syntax

Object.Site Modifier, Result

Part | Description
Object | Object expression that evaluates to an FTP Control or a SecureFtp Control.
Modifier | String expression. Specifies a modifier.
Result | Undimensioned string. Where the reply from the server will be put. Any contents will be replaced.

Remarks

Sends the ftpSite command.

If Timeout is greater than 0, Site blocks until a reply is received from the server or a ptTimeout error occurs. If Timeout is 0, Site immediately returns and the Progress Event event fires with FtpCmd = ftpSite when the reply is received. The Result parameter is used to capture the data so it must not go out of scope while the command completes (it must have file or global scope).

Error Codes

The Site method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptTimeout


Status Method

Get server status information.

Syntax

Object.Status Result [ , PathName ]

Part | Description
Object | Object expression that evaluates to an FTP Control or a SecureFtp Control.
Result | Undimensioned String. Where the reply from the server will be put. Any contents are replaced.
PathName | Optional String expression. Usually specifies a full or partial path name.

Remarks

Sends the ftpStatus command.

This method may have an argument. If the argument is a path name, this method is analogous to the List method except data is transferred (more quickly) over the control connection. If a partial path name is given, the server may respond with a list of file names or attributes associated with that specification. If no argument is given, the server should return general status information about the server FTP process (this should include current values of all transfer parameters and the status of connections).

If Timeout is greater than 0, Status blocks until a reply is received from the server or a ptTimeout error occurs.

If Timeout is 0, Status immediately returns and the Progress event fires with FtpCmd = ftpStatus when the reply is received. The Result parameter is used to capture the reply, so it must not go out of scope while the command completes (it must have file or global scope).

Error Codes

The Status method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptTimeout


Store Method

Example

Store (send) a complete file, or part of a file starting at a specified position.

Syntax

Object.Store RemoteFileName [ , Data ] [ , Marker ]

Part | Description
Object | Object expression that evaluates to an FTP Control or a SecureFtp Control.
RemoteFileName | String expression. Specifies the remote filename (with path) to store, store unique or append to.
Data | Optional String expression specifying a local filename, or a String or Byte array that contains data to be sent. If a specified file cannot be found, then the String or Byte array is assumed to be data and is sent. If Data is not specified or NULL, FileName (without path) will be used to specify the file in the local default directory.
Marker | Optional Long expression. Specifies the number of characters that should be skipped. If a file transfer was interrupted, the Marker parameter can be used to append to the existing file so the entire file does not have to be transferred. If Data is a local file name then the first (Marker) bytes are skipped. If Data contains data it is all sent (no bytes are skipped).

Remarks

Sequences and sends (if needed) the following commands (refer to the CommandConstants topic for more information on these commands):

  • ftpFileStructure

  • ftpPort or ftpPassive

  • ftpStore

  • ftpTransferMode

  • ftpType

Depending on the value of Marker and the StoreType property, ftpStoreUnique or ftpAppend may be sent instead of ftpStore.

If Marker is used, the ftpAppend command is used to send the data, so Marker must accurately reflects the size of the file on the server (since the data will be appended).

The Progress event fires as each file segment is sent or reply is received. If Timeout is greater than 0, Store blocks until the file is received from the server or a ptTimeout error occurs. If Timeout is 0, Store immediately returns. In this case, if the Result parameter is used to capture the data, it must not go out of scope while the command completes (it must have file or global scope).

Previously the Store method would attempt to open a file, if this failed for (whatever reason) the local filename was considered a buffer. This should only be the case when the result of opening the file was ERROR_NOT_FOUND. The Store method now fires ptFile error if the file exists but could not be opened,

Error Codes

The Store method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptProtocol (a protocol error was encountered)

  • ptNotConnected

  • ptTimeout


StructureMount Method

Mount a different file system data structure without altering login or accounting information.

Syntax

Object.StructureMount PathName

Part | Description
Object | Object expression that evaluates to an FTP Control or a SecureFtp Control.
PathName | String expression. Specifies a directory or other system dependent file group designator.

Remarks

Sends the ftpStructureMount command.

If Timeout is greater than 0, StructureMount blocks until a reply is received from the server or a ptTimeout error occurs. If Timeout is 0, StructureMount immediately returns and the Progress event fires with FtpCmd = ftpStructureMount when the reply is received.

Error Codes

The StructureMount method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptTimeout


Progress Event

Example

Fires when the server replies to a command or while a file transfer takes place. The control interprets the reply and presents progress information with this event.

Syntax

Private Sub Object_Progress ( FtpCmd As CommandConstants, Status As StatusConstants, Reply As String, Count As Long, Size As Long )

Part | Description
Object | Evaluates to an FTP Control or a SecureFtp Control.
FtpCmd | CommandConstants. FTP protocol command that corresponds to Reply.
Status | StatusConstants. Indicates that Reply is a final success indication, an intermediate success indication, or a failure.
Reply | String. Provides the complete reply from the server. This is normally a 3-digit number, followed by a space, followed by descriptive text. It may be a multi-line reply. See RFC 959 for the technical details.
Count | Long. Indicates the number of bytes that have transferred (so far) for the transfer in progress. Will normally start at 0 and increase to Size. Only valid when FtpCmd is ftpRetrieve, ftpStore, ftpStoreUnique or ftpAppend; it is 0 at other times.
Size | Long. Indicates the total number of bytes in the file or buffer for the transfer in progress. This value is constant during each transfer. Only valid when FtpCmd is ftpRetrieve, ftpStore, ftpStoreUnique or ftpAppend; it is 0 at other times.

Remarks

The size of a retrieved file is found by sending the ftpSize command after ftpType command. If the server does not support the ftpSize command, then the size of the file is parsed out of the Reply parameter (the 150 reply usually includes the size of the file). The size is not usually accurate on ASCII transfers when the 150 reply is used, because the server is sending a CR/LF pair at the end of each line (instead of the single LF character that is often used on UNIX systems). Some servers (VAX systems, for example) will not even provide the size in the 150 reply, so –1 is reported (this value was chosen so you won't get an unintentional divide by 0 error).

Use the Trace method to gather any protocol level data if the Reply parameter is not adequate.


CommandConstants

These constants enumerate the FTP commands that may be sent:

Value | Constant | Description
0 | ftpCommand | The Command method was used
1 | ftpUser | User Command
2 | ftpPassword | Password Command
3 | ftpAccount | Account Command
4 | ftpChangeDirectory | Change Working Directory Command
5 | ftpChangeDirectoryUp | Change Directory Up Command
6 | ftpStructureMount | Structure Mount Command
7 | ftpQuit | Quit Command
8 | ftpReinitialize | Reinitialize Command
9 | ftpPort | Port Command
10 | ftpPassive | Passive Command
11 | ftpType | Type Command
12 | ftpFileStructure | Structure Command
13 | ftpTransferMode | Mode Command
14 | ftpRetrieve | Retrieve Command
15 | ftpStore | Store Command
16 | ftpStoreUnique | Store Unique Command
17 | ftpAppend | Append Command
18 | ftpAllocate | Allocate Command
19 | ftpRestart | Restart Command
20 | ftpRenameFrom | Rename From Command
21 | ftpRenameTo | Rename To Command
22 | ftpAbort | Abort Command
23 | ftpDelete | Delete Command
24 | ftpRemoveDirectory | Remove Directory Command
25 | ftpMakeDirectory | Make Directory Command
26 | ftpPrintDirectory | Print Working Directory Command
27 | ftpList | List Command
28 | ftpNameList | Name List Command
29 | ftpSite | Site Command
30 | ftpSystem | System Command
31 | ftpStatus | Status Command
32 | ftpHelp | Help Command
33 | ftpNoOperation | No Operation Command
34 | ftpSize | Size Command


FileStructureConstants

These constants enumerate the file structures used for file transfers. See RFC 959 for more details.

Value | Constant | Description
0 | ftpFile | Use FILE structure. There is no internal structure and the file is considered to be a continuous sequence of data bytes. Default value.
1 | ftpRecord | Use RECORD structure. The file is comprised of sequential records.
2 | ftpPage | Use PAGE structure. To transmit files that are discontinuous, FTP defines a page structure. Files of this type are sometimes known as random access files. In these files there is sometimes other information associated with the file as a whole (for example., a file descriptor), or with a section of the file (for example., page access controls), or both. In FTP, the sections of the file are called pages. To provide for various page sizes and associated information, each page is sent with a page header.

When the ftpFileStructure command is sent as part of the Retrieve or Store method, that structure is used by all subsequent data transfers until changed. The ftpFileStructure command is only sent when necessary.


FtpProxyTypeConstants

Value | Constant | Description
0 | ftpProxyNone | No proxy server. Straight connection.
1 | ftpProxySocks4 | Uses a SOCKS V4 Proxy.
2 | ftpProxySocks5 | Uses a SOCKS V5 Proxy.
3 | ftpProxySiteHost | Connects to proxy and sends: SITE <hostname> to establish connection to host, afterwards User is logged in using Username and Password. If ProxyUsername and ProxyPassword are specified, user is logged into proxy before sending SITE request.
4 | ftpProxyUserLogin | Connects to proxy and logs in with ProxyUsername and ProxyPassword, then connects to host by sending: USER <username>@<hostname>
5 | ftpProxyNoUserLogin | Connects to proxy and sends: USER <username>@<hostname>
6 | ftpProxyOpen | Connects to proxy and sends: OPEN < hostname>
7 | ftpProxyPipe | Proxy connects to a predetermined server and logs in using supplied username and password.


StatusConstants

These constants enumerate the possible values of the Status parameter of the Progress event.

Value | Constant | Description
0 | ftpOk | Operation is complete and the last command completed OK.
1 | ftpInProgress | Operation is incomplete and the last command completed OK (more FTP commands are pending).
2 | ftpError | Last command failed to complete OK.


StoreConstants

These constants enumerate the type of file stores that can be performed.

Value | Constant | Description
0 | storeReplace | Perform a normal store command. Default value.
1 | storeUnique | Perform a store unique command. Stores data under a unique name if the file already exists on the server. The name is returned in the reply.
2 | storeAppend | Perform an append. If the file already exists, this will append the data to it.


TransferModeConstants

These constants enumerate the transfer modes used for file transfers. See RFC 959 for more details.

When the ftpTransferMode command is sent as part of the Retrieve or Store method, that transfer mode is used by all subsequent data transfers until changed. The ftpTransferMode command is only sent when necessary.

Value | Constant | Description
0 | ftpStream | STREAM mode. The data is transmitted as a stream of bytes. There is no restriction on the representation type used; record structures are allowed. This is the default value.
1 | ftpBlock | BLOCK mode. The file is transmitted as a series of data blocks preceded by one or more header bytes. The header bytes contain a count field and descriptor code. The count field indicates the total length of the data block in bytes, thus marking the beginning of the next data block (there are no filler bits). The descriptor code defines: last block in the file (EOF), last block in the record (EOR), restart marker, or suspect data.
2 | ftpCompressed | COMPRESSED mode. The COMPRESSED mode transfers compressed data. This mode uses a simple run-length compression algorithm.


TypeConstants

These constants enumerate the data types used for a file transfer. See RFC 959 for more details.

When the ftpType command is sent as part of the Retrieve, Store, List or NameList method, that type will be used by all subsequent data transfers until changed. The ftpType command is only sent when necessary.

Value | Constant | Description
0 | ftpAscii | Data type ASCII. This data type is used to transfer text files between systems (ASCII characters 13 (CR) and 10 (LF) are used as line separators). The sending host must convert the text file from its native format to ASCII and the receiving host must convert it from ASCII to its native format. The ASCII format serves as a neutral format for the data transfer. This is the default value.
1 | ftpImage | Data type IMAGE or BINARY. The IMAGE data type is used to transfer binary files between systems. This type identifies the data as a sequence of contiguous bits packed into 8-bit bytes. The data should be stored as a sequence of bits by each system involved in the transfer.
2 | ftpEbcdic | Data type EBCDIC. The EBCDIC data type transfers EBCDIC text files between systems supporting the EBCDIC character set. If both systems use EBCDIC as the native character set, this data type loses no information during the transfer.


ListEntries Object

Properties Methods Constants

Collection of ListEntry Objects. Listings from UNIX and NT hosts are parsed and formatted by each ListEntry Object. Other FTP server listings are available through the unformatted Text property (see the Format property).


Count Property

Number of objects in the collection.

Syntax

Object.Count

Part | Description
Object | Evaluates to a PowerTCP object.

Data Type

Long

Remarks

Read-only.


Format Property

Format used when the list entries were parsed.

Syntax

Object.Format

Part | Description
Object | Evaluates to a ListEntries Object.

Data Type

FtpFormatConstants

Remarks

Read-only.


Text Property

Unformatted FTP listing.

Syntax

Object.Text

Part | Description
Object | Expression that evaluates to a ListEntries Object.

Data Type

String

Remarks

Set this property to a listing to have it parsed into ListEntry Objects. Set to "" to clear the collection. Read this property to get the unformatted listing.


Append Method

Append additional listing information to the internal buffer.

Syntax

Object.Append Listing

Part | Description
Object | Object expression that evaluates to a ListEntries Object.
Listing | String expression. Contains the file listing to append.


Item Method

Returns an object from a collection. This is the default method for a collection.

Syntax

Value = Object.Item Index

Part | Description
Object | Object expression that evaluates to a ListEntries Object.
Index | Long or String. If a Long is specified, it should be a number between 1 and the collection's Count property. If a String is specified, it searches for a matching entry name.
Value | ListEntry Object

Error Codes

The Item method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptInvalidParam1 (Index does not resolve to a valid Long or Name)


FtpFormatConstants

These constants enumerate the values of the Format property. Inspect this property to determine the format of each ListEntry Object.

Value | Constant | Description
0 | formatUNIX | UNIX formatted listing
1 | formatDOS | Dos formatted listing
2 | formatOther | Unrecognized format. The Text property must be used to access list entry information.


ListEntry Object

Properties Example

The ListEntry Object provides easy access to file information provided by an FTP listing. Each object represents one entry of a listing.

Listings from UNIX and NT hosts are parsed and formatted by each ListEntry Object. Other FTP server listings are available through the unformatted Text property (see the Format property of the ListEntries Object).


Destination Property

Actual location to which a link is pointing.

Syntax

Object.Destination

Part | Description
Object | Evaluates to a ListEntry Object.

Data Type

String

Remarks

Read-only.

Only valid when the Format property is formatUNIX and the FileType is "l".


Directory Property

Directory for the file entry.

Syntax

Object.Directory

Part | Description
Object | Evaluates to a ListEntry Object.

Data Type

String

Remarks

Read-only.

Only valid when the Format is formatUNIX and the List method is called with an "-r" before the path (a recursive directory listing).


GroupName Property

UNIX file group name.

Syntax

Object.GroupName

Part | Description
Object | Evaluates to a ListEntry Object.

Data Type

String

Remarks

Read-only.

Only valid when the Format property is formatUNIX. Inspect Permissions to determine group rights.


Links Property

Number of links associated with the file.

Syntax

Object.Links

Part | Description
Object | Evaluates to a ListEntry Object.

Data Type

Long

Remarks

Read-only.

Only valid when the Format property is formatUNIX.


Name Property

Name of the file.

Syntax

Object.Name

Part | Description
Object | Evaluates to a ListEntry Object.

Data Type

String

Remarks

Read-only.


Owner Property

UNIX file owner.

Syntax

Object.Owner

Part | Description
Object | Object expression that evaluates to a ListEntry Object.

Data Type

String

Remarks

Read-only.

Only valid when the Format property is formatUNIX. The owner of a file is typically the user that created the file. Inspect Permissions to determine owner rights.


Permissions Property

UNIX file permissions.

Syntax

Object.Permissions

Part | Description
Object | Object expression that evaluates to a ListEntry Object.

Data Type

Long

Remarks

Read-only.

Only valid when the Format property is formatUNIX. This field will return a value from 0 to 777. Refer to the following table to interpret this property:

Value | Meaning
1 | execute/search by others
2 | write by others
4 | read by others
10 | execute/search by group
20 | write by group
40 | read by group
100 | execute/search by owner
200 | write by owner
400 | read by owner

The values are combined to construct the permissions for the file. For example, if the file has read, write, and execute only for the owner, the permissions would be 700. Read and write permissions for groups only would be 60. All access to the file by everyone would be 777.


Size Property

Size of the file in bytes.

Syntax

Object.Size

Part | Description
Object | Evaluates to a ListEntry Object.

Data Type

Long

Remarks

Read-only.


Text Property

Unformatted listing entry.

Syntax

Object.Text

Part | Description
Object | Evaluates to a ListEntry Object.

Data Type

String

Remarks

Read-only.


TimeStamp Property

Date and time the file was last modified.

Syntax

Object.TimeStamp

Part | Description
Object | Evaluates to a ListEntry Object.

Data Type

String

Remarks

Read-only.


Type Property

Single character string that represents the type of file.

Syntax

Object.Type

Part | Description
Object | Evaluates to a ListEntry Object.

Data Type

String

Remarks

Read-only.

A UNIX directory listing can have several different types of files. DOS listings will have only directories and normal files. The following table shows some common UNIX file types:

Character | Type
- | Normal File
d | Directory
c | Character device
l | Symbolic link
p | Named Pipe
n | Network special file
s | Socket


PowerTCP Mail Tool

PowerTCP Mail Tool version 2

Support Licensing Distribution Mail Objects Overview

Create advanced Internet mail applications with these controls for extended SMTP, POP3, and IMAP4.

Controls

Control | Description
SMTP Control | Superior high-performance mail delivery
POP Control | Ultimate control for downloading mail
IMAP Control | Objects make IMAP simple to use

Supporting Objects

Object | Description
HeaderFields Object | Manage multiple strings that represent the message header.
Mailbox Object | Represent the mailboxes on the server.
Mailboxes Object | Manages multiple Mailbox Objects.
Message Object | Provide an object representation for email messages. This formatting object makes simple and complex MIME messages easy to manipulate.
Messages Object | Manage multiple Message Objects. The POP Control uses this to store downloaded messages.
Part Object | Represent the message parts in multi-part messages.
PartList Object | List all the Part Objects in a single message.
Parts Object | Manage multiple "sibling" Part Objects.

Sample Projects

The following sample projects demonstrate how to use the Mail Tool:

Project | Description
Bulk Mailer | Uses the SMTP control to show how to send the same message to many recipients. Addresses are taken from a CR/LF delimited text file. Uses the POP control to show how to maintain a list a people who have replied with REMOVE in the subject. Visual Basic 6.
DBPop | Populate a database with all messages that currently residing in a designated POP3 Account. Visual Basic 6 and Access 97.
ImapClient | Demonstrates how to manage mailboxes using the IMAP control, Mailbox and Message Objects. Visual Basic 6, Visual C++ 6, Delphi 4, and PowerBuilder 6.
Mail Forwarder | Uses the POP control to retrieve all messages for a given source address. Uses the SMTP control to forward those messages to a given destination. Visual Basic 6.
MergeMail | From a database of members of a sales force, determine the monthly sales of each member and then email each member a letter reflecting their performance. Access 97.
Message Chunker | Uses the SMTP Control and the Message Object to show how to break a large message into several smaller chunks that the receiver can later reassemble back into a single large message. Visual Basic 6.
PopClient | Demonstrates how to download mail using the Message object and the POP control. Visual Basic 6, Visual C++ 6, Delphi 4, and PowerBuilder 6.
QuickSend | Demonstrates a simpler version of the SmtpClient application. Visual Basic 6, Visual C++ 6, Delphi 4, and PowerBuilder 6.
SmtpClient | Demonstrates how to build and send a message using the Message object and SMTP Control. Visual Basic 6, Visual C++ 6, Delphi 4, and PowerBuilder 6.
Email Verifier | Shows how to use the SMTP control to verify an e-mail address. Visual Basic 6.

Online ASP Samples

These ASP samples demonstrate the use of the Mail Tool on the Internet. You must have an active Internet connection to view these Samples.

Sample

Description

Mail on the Web

The POP Control gets messages from any POP mailbox. The SMTP Control is used to reply. The DNS Control determines the recipient's Email server (by doing an MX record lookup). Build your own "Hotmail" server.

SMTP Mail on the Web

The SMTP Control Emails the message you type into an edit box.


Mail Objects Overview

The Mail Tool provides an object model that dramatically simplifies the composition, interpretation, and management of mail. The formatting objects provide a "source" or "sink" for the controls that transfer mail to/from a server. The drawing below summarizes how these objects work together to make your job easier than ever before.

The Messages Collection holds a list of Message Objects. The POP Control fills this object when it gets a set of messages from the server.

The Message Object uses Part Objects to represent each part of a multi-part message. Most applications will not have to manipulate Part Objects because methods are provided for most common tasks. The Reply method and the Forward method reply to and forward mail, the AddPart method and the AddAttachment method compose mail, and the AddDigest method and the AddMessage method create more complex messages.

The Message object generates the encoded message on demand. If you need to manipulate encoded messages, the SMTP and POP controls provide message management in memory and spooling to/from disk.

For sophisticated applications requiring manipulation of MIME structures and custom processing, the Message object is unsurpassed. Uniquely, the Message Objects and the Part Objects provide a Parts Collection of Part Objects as a property, so hierarchical operations are fully supported. To complement this structure, the Message Object PartList property provides a flat collection containing all Part Objects in the message. The availability of the dual PartList Collection and Parts collections make any search or manipulation operation just a few lines of code.

One of the most powerful features of the product is the HeaderFields Collection. This collection is full of tools to make programming easier. Complete with the versatile Add method and Remove method, the HeaderFields collection handles the nastiest mail header manipulation tasks.


Mail Primer Email Primer

Email Primer

The function of this primer is simply to provide information about the various protocols and components that make up today's Internet email model. This information is not necessary to begin using our tools, however, we feel that it may be beneficial in the development of mail based applications to have a reference on hand. This primer does NOT address to any great extent the actual usage of the PowerTCP Mail Tool. Additional primers will be added in the coming weeks to directly address this subject.

The Email Primer is made up of these topics.

Email Short History

  • The beginnings of SMTP.

  • The advent of POP, IMAP, and MIME.

  • Today's email model.

Sending Mail-SMTP

  • An overview of SMTP.

  • Sample SMTP dialogue.

  • Description of ESMTP.

Receiving Mail-POP3 and IMAP4

  • Comparison of POP3 and IMAP4.

  • An Overview of POP3.

  • Sample POP3 dialog.

  • An Overview of IMAP4.

  • Sample IMAP4 dialog.

Message Structure

  • Basic Message Structure.

  • ASCII Message description.

  • MIME overview.

  • MIME encoding description.

  • Non-ASCII Message description.


Mail Primer Email Beginnings

Email Beginnings

Early Stages of TCP/IP

Back in the late 70's and early 80's, while ARPANET was beginning to become what would be known as the Internet, email was a very popular, albeit chaotic, application. Popular because it was quickly seen as a communications technology that would revolutionize the way our culture exchanged ideas and chaotic because it was implemented by many proprietary email technologies which could not interact with each other. It was quickly discerned that a protocol would be needed to truly make email technology a universal way to exchange ideas.

The Development of Simple Mail Transfer Protocol (SMTP)

The Simple Mail Transfer Protocol was developed to be a reliable, efficient, and universal way to transport mail The SMTP model is made up of two elements, mail transfer agents (MTAs) and user agents (UAs). MTAs are located on the mail server and UAs are located on the user's machine. For the remainder of this primer, any reference to a mail server implies the use of a mail transfer agent and any reference to a mail client implies the use of a user agent.

The mail transfer agent has two tasks:

  • to send and receive messages from other mail transfer agents

  • to interface with user agents

The user agent also has two tasks:

  • to interface with mail transfer agents

  • to provide a user friendly environment, shielding the user from the implementations of SMTP.

Through this model, the creators of SMTP had achieved a universal implementation. They assured that it would be a reliable one as well, by using TCP as the connection means. They achieved their final objective, efficiency, through the use what became known as the "store and forward method". Basically this worked because email, although expected to be transferred in a reasonable amount of time, was not needed in "real time". MTAs can store the incoming email, and forward them at such a time as to provide maximum efficiency.

When SMTP was designed, the only fathomable use for it was to transfer plain ASCII text, which is 7-bit data. As a result, MTAs were all implemented to carry this form of data. This would cause some problem in the future with the advent of multimedia and the preponderance of 8-bit data (see MIME topic). There was another problem with SMTP, the ability to queue messages at the receiving end. As a result the mail server and associated local mail delivery system was needed to be resident and running at all times on the client. A great deal of smaller computers, which were in the midst of an explosion in use, lacked the resources to have the mail delivery system resident and running. In addition, multiple sustained connections was taking its toll on the mail servers as well. A new protocol, Post Office Protocol (POP), was developed to queue messages on the final mail server, and thus reduce the load on both client and server.

More info about the SMTP Protocol is available in the "SMTP Overview" topic.


Mail Primer Continued Email Developments

Improvements in Email Technology

The Development of Post Office Protocol (POP)

Simple Mail Transfer Protocol succeeded in implementing universal, reliable, and efficient email transfer. However, the lack of a final "pick up" point resulted in sustained connections. Post Office Protocol (now in its third version and commonly called POP3) was implemented to have a common system for queuing and delivering mail to the user agent. This protocol called for the creation of a "maildrop" on the mail server, in which mail, delivered by SMTP, would be placed and held for pickup by the recipient. POP basically works by allowing a user agent to interface with the mail drop. This interfacing takes the form of logging in, downloading messages, and logging out. The implementation of POP was a success as it required that the entire mail transfer system not always be connected and resident. The combination of SMTP and POP worked well, but was not perfect. Still missing was the ability to transfer non-ASCII data and a sophisticated way to manipulate email on the server. Solutions to these problems were found in the development of Multipurpose Internet Mail Extensions (MIME) and Internet Message Application Protocol (IMAP).

More info about the POP protocol is available in the "POP Overview" topic.

The Development of Multipurpose Internet Mail Extensions (MIME)

The development of MIME was necessary because the ability to send only 7-bit ASCII text was extremely limiting, especially with the advent of multimedia files. Sending other, non-ASCII files was a challenge, as most of these file types in their natural state are 8-bit files. You may recall that mail transfer agents only have the ability to transfer 7-bit data. MIME specified a new way to structure messages, as well as algorithms to encode the 8-bit data so that non-ASCII files could be transported.

More info about the MIME is available in the "MIME Overview" topic.

The Development of Internet Message Application Protocol (IMAP)

POP, while useful in its current function, still was lacking in several areas. POP did not allow for email manipulation while it was still on the server, or for accessing mail from more than one computer (with POP, once messages are downloaded, they are deleted from the mail server and a single copy remains on the local machine). IMAP allows messages to be manipulated through the use of "mailboxes" which are functionally equivalent to folders on a local machine. The user agent has the ability to create, delete, and rename mailboxes, as well as to move email into different mailboxes, download email, and delete email. Since the email remains on the mail server, IMAP also allows access from different computers. IMAP clearly is a more sophisticated protocol than POP but not all mail servers support IMAP, so POP is still very prevalent today.

More info about the IMAP protocol is available in the "IMAP4 Overview" topic.


Mail Primer Internet Email Model Today

Internet Email Model Today

Today's email model is a hybrid of SMTP, POP, IMAP, and MIME (as well as many other technologies). SMTP is used to send messages, POP is used to queue messages on the receiver mail server for downloading, IMAP is used to store messages on the receiver's mail server for server side manipulation, and MIME specifies a method of sending non-ASCII data. The following diagram illustrates this:


Mail Primer SMTP Overview

SMTP Overview

SMTP Described

Simple Mail Transfer Protocol is the Internet standard for transmission of email messages from sender to the receiver mail server. You may recall from the Email Short History that this transmission is accomplished through the use of mail transfer agents (MTAs) located on the mail server and user agents (UAs) located on the user's local machine. The job of the MTA is to send and receive mail from other MTA's. The job of the UA is to interface with the MTA and to provide a user friendly environment for the end user.

The SMTP protocol essentially provides a means to transfer from mail server to mail server. This transfer may be to a server which is the final destination or simply a relay point for the message. Receiving email is accomplished with either of the protocols POP or IMAP. More information about them can be found in the POP3 Overview topic or the IMAP4 Overview topic. The SMTP transfer is a three step process: authenticating the sender, sending mail, and closing the connection. These processes ensue "lock step", meaning the sender sends a command which the recipient processes and responds to.

The examples that follow show the SMTP commands that occur between two SMTP mail transfer agents. For descriptions of PowerTCP Mail Tool commands which replicate this behavior, please refer to the Mail Tool programmer's reference found here.

SMTP Authentication Described

Prior to authentication, the receiver will be listening on port 25 for TCP connections. Once a connection is made, the sender may issue the HELO command, followed by the sender's domain name. The recipient will in turn identify itself to the sender. The process may look something like this.

Recipient < wait for connection on port 25 >

Sender: < make TCP connection >

Sender: HELO sender.com

Recipient: 250 server1.dart.com

An alternative authentication method is specified using the EHLO command. This command is functionally equivalent to the HELO command except it expresses the desire of the sender to use service extensions (these are a way to enhance SMTP and are covered here). Authentication using the EHLO command may look like this.

Recipient < wait for connection on port 25 >

Sender: < make TCP connection >

Sender: EHLO sender.com

Recipient: 250 server1.dart.com
250-HELP
250-EXPN
250-XREMOTEQUEUE
250-ETRN
250-PIPELINING
250-SIZE

In this example the response from the server is the same as with the HELO command except it announces the service extensions it supports. At this point the authentication stage is complete, and the sending mail process can continue. This process is accomplished using the PowerTCP Tool with the Login method.

SMTP Sending Mail Described

Once the sender has been authenticated, it proceeds to begin sending the mail message. This is a simple process involving three commands, MAIL FROM, RCPT TO, and DATA. The process begins with the MAIL FROM command followed by the sender's address, which specifies the sender of the mail. If the recipient can accept mail, it responds positively with 250 OK. The sender then sends a series of RCPT TO command, each followed by the address of a mail recipient. The receiver will either accept or reject each mail recipient. If a recipient is rejected, the mail transaction still continues. The sender will then use the DATA command to send the actual message. The server should respond to this with a 354 Intermediate reply and will consider all succeeding lines to be the message. This message includes header fields with labels such as Date, Subject, To, Cc, and From followed by the message body. When all data has been sent, the sender issues a <CRLF>.<CRLF>, letting the recipient know all data has been transmitted. The DATA command should fail only if the mail transaction was incomplete (for example, no recipients), or if resources are not available on the server. The process of sending mail may look like this:

Sender: MAIL FROM: <Smith@Alpha.ARPA>

Recipient: 250 OK

Sender: RCPT TO: <Jones@Beta.ARPA>

Recipient: 250 OK

Sender: RCPT TO: <Green@Beta.ARPA>

Recipient: 550 No such user here

Sender: RCPT TO: <Brown@Beta.ARPA>

Recipient: 250 OK

Sender: DATA

Recipient: 354 Start mail input; end with <CRLF> . <CRLF>

Sender: Blah blah blah...

Sender: ...etc. etc. etc.

Sender: <CRLF>.<CRLF>

Recpient: 250 OK

Once this stage is complete, the mail has been sent and the connection must be closed. The mail exchange above is accomplished using the PowerTCP Mail Tool with the Send method.

SMTP Closing the Connection Described

Now the mail has been sent and all that remains is to close the connection. This transaction occurs by the sender using the QUIT command. The recipient will reply with 221 verifying the connection is closed. This transaction may look like this:

Sender: QUIT

Recipient: 221 closing channel

< TCP connection ended >

Once this command had been given, the sending mail process is complete. The example above is accomplished using the PowerTCP Mail Tool with the Logout method.

By default, commands and replies are composed of characters from the US-ASCII (7-bit) character set. If the server supports the extended protocol for an 8-bit byte (octet) transmission channel, it responds with this extension at greeting time if the EHLO command is used. More information about this topic can be found here. PowerTCP supports 8-bit binary transmissions. When the server accepts and forwards a message containing 8-bit data, any 7-bit only intermediate network segments that detect the impending message may refuse to receive the message. This generally results in the message being returned-to-sender.

SMTP supports other commands in addition to the authentication and sending commands including:

  • RSET- This command resets all data that has been entered into the SMTP server.

  • HELP command-name- This command provides syntactical and other information about SMTP commands.

  • VRFY recipient email address- Verifies an address as being acceptable by the system.

  • EXPN alias-name- This command expands an alias and returns a list of recipients the alias will send to.


Mail Primer SMTP Sample Session

SMTP Sample Dialog

The following example demonstrates a dialog that could occur between two mail transfer agents transferring mail using SMTP. For a description of how to replicate this behavior using the PowerTCP Mail Tool, please refer to either the SMTP blocking or non-blocking sample.

Recipient < wait for connection on port 25 >

Sender: < make TCP connection >

Sender: EHLO

Recipient: 250 server1.dart.com
250-HELP
250-EXPN
250-XREMOTEQUEUE
250-ETRN
250-PIPELINING
250-SIZE

Sender: MAIL FROM: <Smith@Alpha.ARPA>

Recipient: 250 OK

Sender: RCPT TO: <Jones@Beta.ARPA>

Recipient: 250 OK

Sender: RCPT TO: <Green@Beta.ARPA>

Recipient: 550 No such user here

Sender: RCPT TO: <Brown@Beta.ARPA>

Recipient: 250 OK

Sender: DATA

Recipient: 354 Start mail input; end with <CRLF> . <CRLF>

Sender: Blah blah blah...

Sender: ...etc. etc. etc.

Sender: <CRLF>.<CRLF>

Recipient: 250 OK

Sender: QUIT

Recipient: 221 closing channel

< TCP connection ended >


Mail Primer SMTP Verifying User Names

SMTP Other Commands

The SMTP protocol supports commands other than those directly related to the sending and receiving of mail. Two of these are the VRFY command and the EXPN command.

VRFY Command

The VRFY command is used to verify a user name. The format of the command is VRFY <user-name>. The response from the server may include the full name of the user and must include the mailbox of the user. The following examples illustrate the use of these commands and possible responses.

Either

S: VRFY Smith

R: 250 Fred Smith <Smith@USC-ISIF.ARPA>

Or

S: VRFY Smith

R: 251 User not local; will forward to <Smith@USC-ISIQ.ARPA>

Or

S: VRFY Jones

R: 550 String does not match anything.

Or

S: VRFY Jones

R: 551 User not local; please try <Jones@USC-ISIQ.ARPA>

Or

S: VRFY Gourzenkyinplatz

R: 553 User ambiguous.

EXPN Command

The EXPN command is used to expand a mailing list. The format of the command is EXPN <mailing list>. The response from the server will be multiline and may include the full name of the users and must give the mailboxes on the mailing list. The following example illustrates the use of this command and the mulitline server response.

S: EXPN Example-People

R: 250-Jon Postel <Postel@USC-ISIF.ARPA>

R: 250-Fred Fonebone <Fonebone@USC-ISIQ.ARPA>

R: 250-Sam Q. Smith <SQSmith@USC-ISIQ.ARPA>

R: 250-Quincy Smith <@USC-ISIF.ARPA:Q-Smith@ISI-VAXA.ARPA>

R: 250-<joe@foo-unix.ARPA>

R: 250 <xyz@bar-unix.ARPA>

These commands, although not often used, can be issued with the SMTP control Command method.


Mail Primer SMTP Service Extensions

SMTP Protocol Extensions (ESMTP)

Since being implemented in the mid 1980's SMTP has proven to be a resilient protocol. However, along with the passing of time came the realization that this protocol may need to be made more flexible. Enhancements were developed to make SMTP a more powerful, useful, and efficient protocol. These enhancements to SMTP came to be known as Enhanced SMTP or ESMTP. ESMTP is a means whereby the receiving mail transfer agent can inform the sending mail transfer agent as to what protocol extensions (enhancements) it supports.

At the heart of the extensions is a new login command. The original HELO command is replaced by the new EHLO command. The EHLO command differs from HELO by announcing to the mail server the desire to use service extensions. The server reports back to the client a list of supported service extensions with parameters.

The following service extensions are supported:

SIZE

The SIZE protocol extension allows a client to declare the size of a particular message to a server as a parameter to the MAIL FROM command, after which the server may indicate to the client that it is or is not willing to accept the message based on the declared message size. The SIZE protocol extension also allows the server to declare the maximum message size it is willing to accept from a client in the SIZE response to the client's EHLO command.

PIPELINING

Normally communication between sender and receiver is synchronized, lock-step. In other words, the sender issues a command and waits for the receiver's response. This can be an inefficient system. If a server announces it can support PIPELINING, this means that it can process multiple SMTP commands without acknowledging every command. This can significantly reduce processing overhead.

8BITMIME

The 8BITMIME protocol extension lets the sender know that the server will accept messages with 8-bit bytes, allowing data to be sent without encoding. See the encoding topic for more information about this.

DSN

DSN, or Delivery Status Notification, is a method for the recipient to return additional information about the success or failure of the delivery. Ordinarily, when a server accepts mail from a client, it either accepts responsibility for the further transmission of the mail or it sends back an error, indicating delivery failure. Using DSN gives the server an opportunity to specify under what conditions and how to notify the client of the status of the delivery. DNS is implemented by using two additional parameters of both the RCPT and MAIL commands.

Optional Parameters of the RCPT command:

  • The keyword "NOTIFY" specifies the conditions under which a delivery status notification should be generated.

  • The keyword "ORCPT" specifies the "original" (sender-specified) recipient address.

Optional Parameters of the MAIL command:

  • The keyword "RET" requests that DSNs containing an indication of delivery failure either return the entire contents of a message or only the message headers.

  • The keyword "ENVID" specifies an identifier for this message transmission envelope, that is returned in any DSNs issued for this transmission.

DSN is implemented using the PowerTCP Mail Tool using the DSN method.

ENHANCEDSTATUSCODES

The ENHANCEDSTATUSCODES protocol extension allows the server to augment its responses with enhanced mail system status codes. These codes can then be used to provide more informative explanations of error conditions, especially in the context of the DSN (delivery status notification) format.

When active, the server prefaces the text part of most replies with status information in the form "class.subject.detail". The class field illustrates the success of the delivery attempt with a 2, 4, or 5.

  • 2.X.X Success. (DSN is reporting a positive delivery action).

  • 4.X.X Persistent Transient Failure (The message was valid but is prevented by a temporary event.)

  • 5.X.X Permanent Failure (A change in the message or the destination is required for successful delivery.)

The subject sub-code classifies the status. This value applies to each of the three classifications. The enumerated values for the subject sub-codes are:

X.1.0 Other address status
X.1.1 Bad destination mailbox address
X.1.2 Bad destination system address
X.1.3 Bad destination mailbox address syntax
X.1.5 Destination mailbox address valid
X.1.6 Mailbox has moved
X.1.7 Bad sender's mailbox address syntax
X.1.8 Bad sender's system address
X.2.0 Other or undefined mailbox status
X.2.1 Mailbox disabled, not accepting messages
X.2.2 Mailbox full
X.2.3 Message length exceeds administrative limit
X.2.4 Mailing list expansion problem
X.3.0 Other or undefined mail system status
X.3.1 Mail system full
X.3.2 System not accepting network messages
X.3.3 System not capable of selected features
X.3.4 Message too big for system
X.4.0 Other or undefined network or routing status
X.4.1 No answer from host
X.4.2 Bad connection
X.4.3 Routing server failure
X.4.4 Unable to route
X.4.5 Network congestion
X.4.6 Routing loop detected
X.4.7 Delivery time expired
X.5.0 Other or undefined protocol status
X.5.1 Invalid command
X.5.2 Syntax error
X.5.3 Too many recipients
X.5.4 Invalid command arguments
X.5.5 Wrong protocol version
X.6.0 Other or undefined media error
X.6.1 Media not supported
X.6.2 Conversion required and prohibited
X.6.3 Conversion required but not supported
X.6.4 Conversion with loss performed
X.6.5 Conversion failed
X.7.0 Other or undefined security status
X.7.1 Delivery not authorized, message refused
X.7.2 Mailing list expansion prohibited
X.7.3 Security conversion required but not possible
X.7.4 Security features not supported
X.7.5 Cryptographic failure
X.7.6 Cryptographic algorithm not supported
X.7.7 Message integrity failure

The following example illustrates the use of these codes.

C: MAIL FROM: <ned@ymir.claremont.edu>

S: 250 2.1.0 Originator <ned@ymir.claremont.edu> OK

C: RCPT TO: <mrose@dbc.mtview.ca.us>

S: 250 2.1.5 Recipient <mrose@dbc.mtview.ca.us> OK

C: RCPT TO: <nosuchuser@dbc.mtview.ca.us>

S: 550 5.1.1 Mailbox "nosuchuser" does not exist

C: RCPT TO: <remoteuser@isi.edu>

S: 551-5.7.1 Forwarding to remote hosts disabled

The use of the ENHANCEDSTATUSCODE protocol extension makes it clear exactly the mailing status of each of the three recipients. The first, mrose@dbc.mtview.ca.us, received a 2.1.5 status code, indicating a valid recipient. The second, nosuchuser@dbc.mtview.ca.us, received a 5.1.1 status code, indicating failure due to a bad destination mailbox address. The third, remoteuser@isi.edu, received a 5.7.1, indicating failure due to an unauthorized delivery.


Mail Primer SMTP RFCs Supported

SMTP RFCs Supported

The PowerTCP Mail Tool supports the following RFCs:

RFC 821 – Simple Mail Transfer Protocol (SMTP)

RFC 1123 – Requirements for Internet Hosts

RFC 1869 – SMTP Service Extensions

RFC 1870 – SMTP Service Extension for Message Size Declaration

RFC 1652 – SMTP Service Extension for 8bit-MIME Transport

RFC 2197 – SMTP Service Extension for Command Pipelining

RFC 2034 – SMTP Service Extension for Returning Enhanced Error Codes

RFC 1894 – An Extensible Message Format for Delivery Status Notifications (DSNs)

RFC 1893 – Enhanced Mail System Status Codes

RFC 1891 – SMTP Service Extension for Delivery Status Notifications

RFC 2442 – The Batch SMTP Media Type


Mail Primer A Comparison of POP3 and IMAP

A Comparison of POP3 and IMAP4

The SMTP protocol is very adept at sending mail, unfortunately it lacks a means of queuing messages at the receiving end (See the Email Short History for more information) As a result, the message's final journey from mail server to client involves the use of one of two protocols, POP3 (Post Office Protocol) or IMAP4 (Internet Message Access Protocol), whose job it is to queue and deliver the messages to the recipeint. POP3 and IMAP4 differ in the location in which messages are managed.

POP3

With the POP3 protocol, mail is delivered by SMTP to the client's mail server. The client then periodically logs into the mail server, downloads or deletes all messages, and logs out. All message management takes place on the local machine, and all mail that has been downloaded is removed permanently from the mail server, so the only copy exists on the local machine. A more detailed explanation of this interaction can be found in the POP3 Overview.

IMAP4

With the IMAP4 protocol, messages are manipulated remotely on the mail server as if they were local. IMAP4 allows for the creation of remote message folders, called mailboxes, which are functionally equivalent to local folders. A more detailed explanation of this interaction can be found in the IMAP4 Overview.

Advantages of IMAP4 over POP3

IMAP4 is a much more sophisticated protocol than POP3 and has several advantages over this protocol including:

  • The already mentioned ability to manipulate folders on the server.

  • The ability to have multiple folders in comparison to POP3's single folder, INBOX.

  • Optimized performance as the messages can be manipulated using the power of the server, and can be managed without downloading them.

  • The provision for negotiated extensions, allowing its capabilities to grow.

  • The ability to access the same mail on multiple machines, as the messages are not deleted from the mail server as in POP3.

  • The ability to parse MIME.


Mail Primer POP Overview

POP3 Overview

POP3 Described

POP3 (the current version of POP in use today) is a mail protocol used by a client to access and download messages that are held temporarily by the server. You might recall from the Email Short History that POP was developed because SMTP lacked a method of queuing messages on the recipient's mail server. POP provided a system for queuing messages and allowing the user to periodically log in to the mail server, download messages, and log out, thereby greatly reducing the strain on both mail servers and user machines to maintain a constant and resident connection.

A POP session is made up of the client and server exchanging commands and responses, lock-step. The client and mail server continue to exchange commands and responses until the session is terminated. This session can be broken down into three states: authorization state, transaction state, and update state.

POP3 Authorization State

A POP3 session begins with the server listening for connections on port 110. The authorization state begins when a client makes a TCP connection on port 110 and the server issues a greeting. The client must issue the USER command followed by its user identification. If the server responds with a positive success indicator ("+OK"), the user may issue the PASS command followed by its password. If the server again issues a positive success indicator ("+OK") the server acquires the client's associated maildrop located on the server and the session moves into the transaction state. An example of this follows:

Server: <wait for connection on TCP port 110>

Client: <open connection>

Server: +OK dewey POP3 server ready

Client: USER mrose

Server: +OK mrose

Client: PASS secret

Server: +OK mrose's maildrop has 2 messages (320 octets)

At this point the user is logged into the mail server and the mail server has acquired the user's associated maildrop. The session has now entered the transaction state. Using the PowerTCP POP control, the Login method accomplishes all of this.

POP3 Transaction State

The transaction state consists of the client issuing one of several commands and the server responding either positively or negatively. These commands are mainly used to acquire information about the mail located on the mail server, or to retrieve mail from the mail server. Some possible commands are:

  • STAT- The server will return the total messages and total size.

  • LIST [msg]- If no argument is given, the server will return a multiline response enumerating each message and its statistics. If an argument is given, the server will simply return the statistics for the message specified by msg or an error message if the message does not exist.

  • RETR msg- The server will return with a multiline response of the content of the message specified by msg or an error if the message does not exist.

  • DELE msg- If the message specified by the argument msg is valid, the POP3 server will mark the message for deletion and return a positive response. If the message does not exist or has already been marked for deletion, the server will return an error.

  • NOOP- The server will simply respond to this command with a positive response.

  • LAST- The server will return the number of the highest accessed message.

  • RSET- Any messages marked for deletion are unmarked.

  • QUIT- Ends the POP3 session, the server will enter the update state.

The transaction state can take many forms but the following shows a possible dialogue between client and server in the this state.

Client: STAT

Server: +OK 2 320

Client: LIST

Server: +OK 2 messages (320 octets)

Server: 1 120

Server: 2 200

Server: .

Client: RETR 1

Server: +OK 120 octets

Server: <the POP3 server sends message 1>

Server: .

Client: DELE 1

Server: +OK message 1 deleted

Client: RETR 2

Server: +OK 200 octets

Server: <the POP3 server sends message 2>

Server: .

Client: DELE 2

Server: +OK message 2 deleted

Client: QUIT

Once the QUIT command has been issued, the transaction state is over and the session now moves into the update state.

POP3 Update State

In the update state the server will delete all messages marked for deletion, release the resources associated with the client's maildrop, and closes the TCP connection. This is accomplished using the PowerTCP POP control by using the Logout method.

For more detailed information about the POP3 protocol refer to RFC 1939.


Mail Primer POP Sample Session

POP3 Sample Dialog

The following example demonstrates a dialog that could occur between a client downloading messages from a server using the POP protocol. For a description of how to replicate this behavior using the PowerTCP POP control, please refer to either the POP control non-blocking or blocking sample.

Server: <wait for connection on TCP port 110>

Client: <open connection>

Server: +OK dewey POP3 server ready

Client: USER mrose

Server: +OK mrose

Client: PASS secret

Server: +OK mrose's maildrop has 2 messages (320 octets)

Client: STAT

Server: +OK 2 320

Client: LIST

Server: +OK 2 messages (320 octets)

Server: 1 120

Server: 2 200

Server: .

Client: RETR 1

Server: +OK 120 octets

Server: <the POP3 server sends message 1>

Server: .

Client: DELE 1

Server: +OK message 1 deleted

Client: RETR 2

Server: +OK 200 octets

Server: <the POP3 server sends message 2>

Server: .

Client: DELE 2

Server: +OK message 2 deleted

Client: QUIT

Server: +OK dewey POP3 server signing off (maildrop empty)

Client: <close connection>

Server: <Delete marked messages, release maildrop, close connection>

Server: <wait for next connection>


Mail Primer IMAP Overview

IMAP4 Overview

Imap4 Described

IMAP4 (Internet Message Access Protocol) allows remote manipulation of messages on the server as if they were on the local machine. IMAP was implemented in response to the shortcomings of POP, most notably the lack of sophisticated mail manipulation on the server and the inability to access mail from more than one computer.

The message manipulation described above occurs through commands issued by the client, and responses issued by the server. Every command issued by the client must be preceded by a unique, client-defined identifier (for example, A0001), which must increment with each successive command. These commands allow a client to create and manipulate folders called "mailboxes" on the server in a way that is functionally equivalent to manipulating local folders. The commands also allow the ability to "resynchronize" the server. As commands are issued an IMAP4 session progresses through four states, non-authenticated, authenticated, selected, and logout.

IMAP4 Non-Authenticated State

A client makes a TCP connection with the server on port 143, at which point the session enters the non-authenticated state. In this state the client has access to four commands, CAPABILITY (displays special capabilities of the server), NOOP (causes the server to give a positive response), LOGIN (authenticates the client), and LOGOUT (ends the session). In order for the session to continue, the client must supply authentication credentials with the LOGIN command. Once proper credentials have been supplied, the session moves into the authenticated state.

IMAP4 Authenticated State

Once in the authenticated state, the client must select a valid mailbox before it is able to progress to the next state. This selection is accomplished by use of either the SELECT or the EXAMINE command followed by a valid mailbox name. The only difference between these commands is with SELECT, the mailbox is opened with read/write privileges, where EXAMINE will open the mailbox with read-only privileges. Once one of these commands is executed successfully, the session moves into the selected state. In the authenticated state, the client has access to all commands from the non-authenticated state (except for LOGIN) The client can also CREATE a mailbox, get the STATUS of a mailbox, RENAME a mailbox, and perform other commands involving the manipulation of mailboxes.

IMAP4 Selected State

The selected state is the state in which the actual message access happens. The client can issue any of the commands from the authenticated state, plus CLOSE (closes to mailbox and returns to authenticated state), EXPUNGE (removes all messages flagged for deletion), SEARCH (allows the client to find messages using certain criteria), FETCH (returns all or a part of a message), STORE (allows updating of flags stored with each message), COPY (allows copying of a message set to a mailbox). From the selected state, the client can issue the CLOSE command to return to the authenticated state or LOGOUT to cause the server to go to the logout state.

IMAP4 Logout State

In the logout state the server simply terminating the connection.

The graphic below illustrates this progression through the four states.


Mail Primer IMAP4 Sample Session

IMAP4 Sample Dialog

The following example demonstrates a dialog that could occur between a client downloading messages from a server using the IMAP protocol. For a description of how to replicate this behavior using the PowerTCP Mail Tool, please refer to our IMAP control usage topic.

<connection>

Client: A0001 LOGIN username password

Server: A0001 OK LOGIN completed

Client: A0002 CREATE mailbox1

Server: A0002 OK CREATE completed

Client: A0003 SELECT mailbox1

Server: A0003 OK SELECT completed

<note: since this is a newly created mailbox, no mail exists>

Client: A0004 FETCH 1:3

Server: A0004 BAD FETCH

Client: A0005 Quit

Server: A0005 OK QUIT completed

<connection closed>


Mail Primer Basic Message Structure

Basic Message Structure

Now that the process of message delivery has been illustrated it may be helpful to look at what actually is being sent. Email messages are viewed as having two entities, an envelope and contents. The envelope is viewed as the data that is needed to accomplish delivery, the contents compose the object to be delivered to the recipient. When this standard was first proposed, the content was assumed to be text. Of course, the advent of multimedia required the ability to send non-ASCII files. This was later implemented with the use of MIME (Multipurpose Internet Mail Extensions). This topic will be addressed shortly, for this example we will look at the message structure as illustrated in RFC 822 for transporting ASCII text only messages.

Email message structure was defined to use a "memo" framework. That is to say that the message would begin with data that must be structured in a specific way followed by data that would not be structured in any specific way. This rigidly defined area of the message is the envelope, or headers, the less rigid part of the message is the content, or message body. Often, you will hear the term envelope and header used interchangeably. There is a distinction. The envelope is derived from the SMTP MAIL FROM: ad RCPT TO: commands, while the header includes these fields as well as many other fields.

The Headers

The headers of a message contain data pertaining to the content of the message. It is made up of ASCII text lines consisting of a header field, a colon, and a header field value. There are two types of header fields, structured and unstructured. Structured header fields are those that must follow a specific syntax, such as From: and Date: so the data can be parsed as needed. Unstructured header fields are those that are not required to follow a set syntax, such as Subject: and Comments: and are just considered to be strings. Header fields are not required to be in any specific order, but they are required to appear before the message content.

Here are some commonly used email header fields.

Bcc: | Blind carbon copy. Used like Cc:
Cc: | Carbon copy. It is a place to specify additional recipients.
Comments: | A nonstandard header used by some e-mail clients to specify more information about the sender.
Content-Description:* | Human-readable string about the content of the message.
Content-Id:* | A unique MIME identifier that works in a similar fashion to Message-ID:
Content-Transfer-Encoding:* | Shows what MIME encoding was used.
Content-Type:* | Tells MIME-compliant mail programs what type of data is in the cargo.
Date: | Specifies date the mail was sent.
Errors-To: | A place for mail generated errors.
From: | Specifies the user defined sender of the mail.
Message-ID: | A unique identifier assigned to the message.
MIME-Version:* | Specifies the MIME version that was used by the sender.
Organization: | A free form header that usually contains the name of the organization.
Priority: | Assigns a priority to the message (ex: Urgent!)
Received: | Provides a log of the message's history. This field is added to by every mail transport agent that relays the message.
Reply-To: | Specifies the reply address.
Return-Path: | This field, added by the final transport system to the user's machine, contains information about the address back to the mail's originator.
Sender: | Autheniticated identity of the agent that sent the message.
Subject: | Specifies the user defined subject of the e-mail.
To: | The recipient of the e-mail.

* = These are MIME headers which will be addressed in more detail in the MIME topic.

In addition to these fields, RFC 822 defined the ability to create user defined fields, called extension fields or X-headers. These are created and given values by the sending client and are only useful if the receiver's client has a method of handling the X-header.

The Message Body.

The body is simply the portion of the email that the sender wishes the receiver to receive. It is merely the cargo and does not otherwise have any use to the TCP/IP mail protocols. The body is usually made up of the actual text of the e-mail and/or any attachments.

Both the body and the header are typically made up of 7-bit data, which is compatible with all mail servers, and are less than 1000 characters in line length.


Mail Primer Example: A Basic Text E-mail

A Basic Text Email

As an example, let's look at the composition of a basic text email. In this example, the sender simply opens their email client, specifies the receiver and the subject, writes a quick note,

To: jeff@dart.com
Subject: email test
Message:

This is a test message
to see the headers.

and sends the mail. When the receiver gets the message it would look something like this:

Return-Path: <test@test.com>

Received: from JEFF ([192.168.0.71]) by server1.dart.com

(Post.Office MTA v3.5 release 215 ID# 0-

54045U100L2S100V35)

with ESMTP id com for <jeff@dart.com>;

Thu, 1 Feb 2001 16:46:38 -0500

To: jeff@dart.com

From: test@test.com

Subject: email test

Message-ID: <0000c93a04003b07d1@[192.168.0.71]>

Date: Thu, 01 Feb 2001 16:47:39 -0500

This is a test message

to see the headers.

The first 11 lines are the email headers. In this example the only headers that were user-defined are the "From:" header and the "Subject:" header. The others were added by the email clients and mail servers during the message's journey. Since no MIME headers are present in the message, the content is assumed to be ASCII text which, as we can see from our message at the bottom, it is. What happens if we send an email with an attachment? This is where MIME comes into play. MIME (Multipurpose Internet Mail Extensions) is a specification of how to format non-ASCII messages.

Using the PowerTCP Mail Tool, simple messages such as this are represented by the Text property of the Message Object.


Mail Primer MIME Overview

MIME Overview

MIME (Multipurpose Internet Mail Extensions) is necessary because the text-only format described by RFC 822 is extremely limiting. MIME allows an email message to contain data other than text, and still be backwards compatible with non-MIME compatible mail servers. When MIME was implemented, it caused some changes to the original message structure specified in RFC 822. Additional MIME-specific header fields were required to specify the MIME content. The structuring of the message body was changed to allow multiple types of files. Finally, encoding rules were specified for those attachments which were not ASCII. By implementing MIME this way, it allowed mail transfer agents to remain the same, only the sending and receiving client needed to be changed to handle the MIME attachments.

The message header fields that were added to the RFC 822 mail structure are:

  • MIME-Version (specifies the version of the MIME formatting, and distinguishes a message as being MIME structured)

  • Content-Description (provides additional information about the contents of the message)

  • Content-ID (provides additional information about the contents of the message)

  • Content-Transfer-Encoding (indicates the type of encoding applied to the message part. Base64 and Quoted-Printable and the two most common forms of encoding that turn 8-bit data into 7-bit data)

  • Content-Type (describes the media type and subtype)

Of these headers, the two most useful in this discussion are the Content-Transfer-Encoding header field and the Content-Type header field. Let's discuss beginning with the latter.

Content-Type

Content-Type specifies the nature of the message body (the type of file). RFC 1521 defined seven types (which are still under revision):

  • Text (unformatted or formatted in a simple manner)

  • Image

  • Audio

  • Video

  • Application

  • Message (For example, an RFC 822 message)

  • Multipart (allows a message to contain more than one part)

The purpose of this field is to let the receiving client know the content of the part to allow it to handle the part appropriately. Each of these types has a subtype to define a specific format for the type of data. To see this work, let's examine these fields for a ASCII text message sent with a MIME compliant user agent.

< RFC 822 header fields omitted >

Content-Transfer-Encoding: Quoted-Printable

Content-Type: text/plain; charset=ISO-8859-1

MIME-Version: 1.0

< message content (ASCII text omitted) >

Here we can see that MIME version 1.0 and Quoted-Printable encoding (more on this later) was used. The Content-Type type is "text", the subtype is "plain", meaning it is simply made up of ASCII without any other formatting applied.

As another example, let's examine the MIME header fields for a message containing only a single image.

< RFC 822 header fields omitted >

MIME-Version: 1.0

Content-Type: image/gif;

name="Dart.GIF"

Content-Transfer-Encoding: base64

Content-Disposition: attachment;

filename="Dart.GIF"

< encoded message omitted >

Again the MIME-Version is 1.0, but the encoding used was Base64. The Content-Type is "image" and the subtype is "gif", telling the receiving user agent that the file "Dart.GIF" is indeed a "gif" type of image.

Next we address the header field Content-Transfer-Encoding


Mail Primer MIME Encoding

MIME Encoding

Content-Transfer-Encoding

As mentioned earlier, the header field Content-Transfer-Encoding tells what type of MIME-encoding was used so the receiving client can properly decode it using the same scheme. Why do MIME messages need to be encoded? Most file formats, in their natural state, are 8-bit files. Unfortunately, the SMTP protocol restricts messages to 7-bits because it was originally implemented to only transfer 7-bit ASCII text. Encoding takes an 8-bit file and, using an encoding algorithm, creates a 7-bit file from it to allow it to compatible with all SMTP agents.

How does this happen? RFC 2045 defines the use of two algorithms, Quoted-Printable and Base64. There is no definable relationship between these schemes and the Content-Type header field (in other words, the same file type is not always encoded with the same scheme).

Quoted-Printable

The Quoted-Printable encoding system works like this. An 8-bit character has 256 possible combinations (2^8). Of these 128 (2^7) are printable ASCII characters (7-bit characters). These 7-bit characters are not a problem for transfer. We need a way to deal with the characters 128-256 (the characters that are represented by 8-bits). This is done by using the characters hexadecimal value and quoting them. For example, a character with the value of 200 would be encoded as "=C8".

Quoted-Printable encoded data is assumed to be line oriented. In fact, since the ASCII characters are kept in their original form, often a file encoded with Quoted-Printable is highly readable. Using this encoding system lines are transmitted in lengths no longer than 76 characters.

To see this algorithm illustrated, examine this data encoded with Quoted-Printable encoding.

<!doctype HTML public "-//W3C//DTD HTML 4.0 Frameset//EN">

<html>

<!--(=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=

=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=

=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D)-->

<!--(Document created with RoboEditor. )=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=

=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D-->

<!--(=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=

=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=

=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D)-->

<head>

<title>Tutorial</title>

This document is apparently a portion of an HTML page, as some tags made up of ASCII characters have been preserved. There are quite a few encoded characters as well, clearly identifiable by the "=" preceding it.

Base64

The encoding in Base64 is entirely different from Quoted-Printable encoding. Base64 makes no attempt for the encoded data to be human-readable. Also, this form on encoding results in the encoded data being 33% larger than the original data. The scheme works in this way. Groups of 24-bits are broken off. In the data's native form this would represent 3, 8-bit segments. However we are restricted to the use of 7-bits, so this data is encoded as 4, 6-bit segments.

To see this algorithm illustrated, examine this data encoded with Base64 encoding.

pcEATSAJBAAA8BK/AAAAAAAAEAAAAAAABAAAnRsAAA4AYmpiauI94j0AAAAAAAAAAAAAAAAAAAAA

AAAJBBYAIjgAAIBXAACAVwAAnRcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAA

AAAAAAD//w8AAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAGwAAAAAACABAAAAAAAAIAEAACAB

AAAAAAAAIAEAAAAAAAAgAQAAAAAAACABAAAAAAAAIAEAABQAAAAAAAAAAAAAADQBAAAAAAAAeAkA

AAAAAAB4CQAAAAAAAHgJAAAAAAAAeAkAAAwAAACECQAAJAAAADQBAAAAAAAAA1UAAGgBAAC0CQAA

AAAAALQJAAAAAAAAtAkAAAAAAAC0CQAAAAAAALQJAAAAAAAAtAkAAAAAAAC0CQAAAAAAALQJAAAA

AAAAglQAAAIAAACEVAAAAAAAAIRUAAAAAAAAhFQAAAAAAACEVAAAAAAAAIRUAAAAAAAAhFQAACQA

AABrVgAAIAIAAItYAAB8AAAAqFQAABUAAAAAAAAAAAAAAAAAAAAAAAAAIAEAAAAAAAC0CQAAAAAA

Because the structure of the data is completely changed, the result is unreadable. Now we will address what happens when more than one part exists, by looking at the Mulitpart type of the Content-Type header field.


Mail Primer MIME With Multiple Parts

MIME With Multiple Parts

MIME allows the use of multiple parts. It may be necessary at this point to distinguish between a part and an attachment. An attachment is always a part but a part is not always an attachment. For example, if a person sent a text email and attaches a file, this would create two parts, the text and the attached file.

When any file is attached to a message, this causes the Content-Type in the main header to become multipart, identifying that there are more parts than the message text. These parts will be enumerated after the main header, separated by an automatically generated divider. Each of these parts may be encoded with a different encoding scheme. To see this illustrated lets examine a message made up of text, a gif file, and a word doc.

At the beginning of the message will be the header.

Return-Path: <test@test.com>

Received: from JEFF ([192.168.0.71]) by server1.dart.com

(Post.Office MTA v3.5 release 215 ID# 0-54045U100L2S100V35)

with ESMTP id com for <jeff@dart.com>;

Fri, 2 Feb 2001 11:09:42 -0500

To: jeff@dart.com

From: test@test.com

Subject: multipart email

MIME-Version: 1.0

Content-Type: multipart/mixed; Boundary="--PTCP_00011cb405020407d1"

Message-ID: <00011cb505020507d1@[192.168.0.71]>

Date: Fri, 02 Feb 2001 11:10:35 -0500

Of course, all the fields from the original RFC 822 specifications are present but for this example, let's focus on the Content-Type. The type is described as multipart/mixed, which tells us to expect several independent parts after the main header. The Boundary tells us that these parts will be separated by the character string "--PTCP_00011cb405020407d1". This is easily seen in the remainder of the message.

----PTCP_00011cb405020407d1

Content-Type: text/plain; charset=ISO-8859-1

Content-Transfer-Encoding: Quoted-Printable

This message is a multipart MIME test.

----PTCP_00011cb405020407d1

Content-Transfer-Encoding: base64

Content-Disposition: attachment; filename="Dart.GIF"

Content-Type: application/octet-stream; name="Dart.GIF"

R0lGODlhbwAmAPf/AP///xAQECEhISkpKTExMTk5OUJCQkpKSlJSUlpaWmNjY2tra3Nzc3t7e4SE

hIyMjJSUlJycnKWlpa2trbW1tb29vcbGxs7OztbW1t7e3ufn5+/v7/f39+fe3tbGxrWcnGMxMVIA

< other Base64 encoding omitted >

----PTCP_00011cb405020407d1

Content-Transfer-Encoding: base64

Content-Disposition: attachment; filename="dart site report.doc"

Content-Type: application/msword; name="dart site report.doc"

0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQAGAAAAAAAAAAAAAAAKAAAAhwQAAAAAAAAA

EAAAiQQAAAEAAAD+////AAAAAH0EAAB+BAAAfwQAAIAEAACBBAAAggQAAIMEAACEBAAAhQQAAIYE

< other Base64 coding omitted >

----PTCP_00011cb405020407d1--

It is easy to see the three MIME parts, each delimited by the aforementioned Boundary string. The first part is our plain text message, which was encoded with Quoted-Printable but since it is made up of ASCII characters, the message is intact, "This message is a multipart MIME test."

The second part is identified as being the image Dart.GIF. Not surprisingly it was encoded with the Base64 scheme, resulting in a human-unreadable jumble.

The third part is identified as a Microsoft Word document called "dart site report.doc". Again Base64 was used to encode the message. The message ends with a final Boundary string.

Multiple parts are easy to implement using the PowerTCP Mail Tool. Each of these elements is called a Part and is stored in the Parts property of the Message Object. The first part, the text message, could be created with the AddText method. The second and third parts (the files Dart.gif and Dart Site Report.doc) could be created with the AddAttachment method.

PowerTCP manages composition with the AddText, AddAttachment, and AddMessage methods. If one on these methods doesn't fit your needs, you may create more complex messages, such as alternative message representations, by directly manipulating the message objects.


HeaderFields Object

Properties Methods Constants Example

Use the HeaderFields Object to manage message header fields. This collection is similar to the DartStrings Collection, with additional methods for processing header fields.

Header fields may be added individually, or as a block to be automatically unwrapped and parsed through the Add method. This collection also provides an Item method to support access by position, symbolic field name, or matching string.

The Message Object implements the To, Cc, and Bcc properties with the DartStrings Object. Use those properties for recipient storage instead of the HeaderFields Object.

Test.


All Property

Concatenation of all strings in the collection with separating CR/LF pairs.

Syntax

Object.All

Part | Description
Object | Evaluates to a HeaderFields Object.

Data Type

String

Remarks

Read-only.

Use this property to return the header fields as a single string. This property does not return a string that is "transport-ready." The Content property of the Message Object returns an encoded header that can be safely sent.


Add Method

Add one or more header fields to the collection. If multiple header fields are provided they must be separated by CR/LF pairs.

Syntax

Count = Object.Add Label, Value [ , Unique ]

Part | Description
Object | Evaluates to a HeaderFields Object.
Label | LabelConstants. Specifies the symbolic name for the header label being added. Use msgNull if Value includes the label.
Value | String. Value to be added to the collection.
Unique | Optional Boolean. Indicates the header field should replace any existing header fields with the same label. Defaults to False.
Count | Long. Number of strings added to the collection.

Remarks

A header field is a label, followed by a colon, followed by a space, followed by one or more values separated by semicolons.

This method allows you to add header fields in the following two ways:

  • If Label is not msgNull, then Value will be prepended with the string representation of the specified Label and a space before adding it to the collection.

  • If Label is msgNull, then Value must contain a complete header field, including the label.

Error Codes

The Add method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1

  • ptNoMemory


Clear Method

Remove all the objects from the collection.

Syntax

Object.Clear

Part | Description
Object | Evaluates to a PowerTCP collection.

Remarks

This method takes linear (O(n)) time, where n is the number of items stored.


Find Method

Find a header field in the collection.

Syntax

Value = Object.Find Label [ , LabelString ] [ , StartAfter ]

Part | Description
Object | Evaluates to a HeaderFields Object.
Label | LabelConstants. Specifies the symbolic name for the label to find. If msgNull, the LabelString parameter will be used as the search string.
LabelString | Optional String. Specifies the label to find. Use this parameter to find a non-standard label (not available in LabelConstants). When using this parameter, Label should be msgNull.
StartAfter | Optional Long. Indicates the index to start the search after. StartAfter is updated to reflect the index of the header field found.
Value | String. Value that contains the requested header field.

Remarks

This method searches the collection for a label. On return, StartAfter is updated to reflect the index of the label found; this allows you to find multiple header fields that have the same label.

StartAfter cannot be a constant because the method updates its value. Providing a constant value for StartAfter generates a run-time error. Specifying StartAfter with a value of zero starts the search at the head of the collection. StartAfter is set to 0 and "" is returned if the item is not found.

Error Codes

The Find method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1

  • ptInvalidParam3

  • ptNoBufferSpace


Item Method

Provide array subscript access to the collection.

Syntax

Value = Object.Item Index

Part | Description
Object | Evaluates to a HeaderFields Object.
Index | Long. Specifies a header field by position in the collection.
Value | String. Value that contains the requested header field.

Error Codes

The Item method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1

  • ptNoBufferSpace


Remove Method

Remove a header field from the collection.

Syntax

Value = Object.Remove Label [ , Index ]

Part | Description
Object | Evaluates to a HeaderFields Object.
Label | LabelConstants specifies the symbolic name for the header field to be removed. If msgNull, the Index parameter will be used to specify the header field to be removed.
Index | Optional Long. Identifies a header field by position in the collection. When using this parameter Label must be set to msgNull.
Value | String. Contains the removed header field.

Remarks

This method removes the first header field matching Label or the header field at Index in the collection.

Errors

The Remove method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1

  • ptInvalidParam2

  • ptNoBufferSpace


LabelConstants

Some HeaderFields Object methods use a symbolic name for the Label parameter. The following labels are specified as the Common Internet Message Headers (these headers are explained in RFC 2076):

Value | Constant | Description
0 | msgNull | N/A
1 | msgAlsoControl | "Also-Control:"
2 | msgAlternateRecipient | "Alternate-Recipient:"
3 | msgApparentlyTo | "Apparently-To:"
4 | msgApproved | "Approved:"
5 | msgArticleNames | "Article-Names:"
6 | msgArticleUpdates | "Article-Updates:"
7 | msgAutoForwarded | "Auto-Forwarded:"
8 | msgComments | "Comments:"
9 | msgContentBase | "Content-Base:"
10 | msgContentConversion | "Content-Conversion:"
11 | msgContentDescription | "Content-Description:"
12 | msgContentDisposition | "Content-Disposition:"
13 | msgContentID | "Content-ID:"
14 | msgContentIdentifier | "Content-Identifier:"
15 | msgContentLanguage | "Content-Language:"
16 | msgContentLength | "Content-Length:"
17 | msgContentLocation | "Content-Location:"
18 | msgContentMD5 | "Content-MD5:"
19 | msgContentReturn | "Content-Return:"
20 | msgContentSGMLEntity | "Content-SGML-Entity:"
21 | msgContentTransferEncoding | "Content-Transfer-Encoding:"
22 | msgContentType | "Content-Type:"
23 | msgControl | "Control:"
24 | msgConversion | "Conversion:"
25 | msgConversionWithLoss | "Conversion-With-Loss:"
26 | msgDate | "Date:"
27 | msgDeliveryDate | "Delivery-Date:"
28 | msgDeliveryReport | "Delivery-Report:"
29 | msgDiscardedX400IPMSExtensions | "Discarded-X400-IPMS-Extensions:"
30 | msgDiscardedX400MTSExtensions | "Discarded-X400-MTS-Extensions:"
31 | msgDiscloseRecipients | "Disclose-Recipients:"
32 | msgDistribution | "Distribution:"
33 | msgDLExpansionHistoryIndication | "DL-Expansion-History-Indication:"
34 | msgEncoding | "Encoding:"
35 | msgErrorsTo | "Errors-To:"
36 | msgExpires | "Expires:"
37 | msgFax | "Fax:"
38 | msgFcc | "Fcc:"
39 | msgFollowupTo | "Followup-To:"
40 | msgForComment | "For-Comment:"
41 | msgForHandling | "For-Handling:"
42 | msgFrom | "From:"
43 | msgGenerateDeliveryReport | "Generate-Delivery-Report:"
44 | msgImportance | "Importance:"
46 | msgInReplyTo | "In-Reply-To:"
47 | msgIncompleteCopy | "Incomplete-Copy:"
48 | msgKeywords | "Keywords:"
49 | msgLanguage | "Language:"
50 | msgLines | "Lines:"
51 | msgMailSystemVersion | "Mail-System-Version:"
52 | msgMailer | "Mailer:"
53 | msgMessageID | "Message-ID"
54 | msgMessageType | "Message-Type:"
55 | msgMIMEVersion | "MIME-Version:"
56 | msgNewsgroups | "Newsgroups:"
57 | msgObsoletes | "Obsoletes:"
58 | msgOrganisation | "Organisation:"
59 | msgOrganization | "Organization:"
60 | msgOriginalEncodedInformationTypes | "Original-Encoded-Information-Types:"
61 | msgOriginatingClient | "Originating-Client:"
62 | msgPath | "Path:"
63 | msgPhone | "Phone:"
64 | msgPrecedence | "Precedence:"
65 | msgPreventNonDeliveryReport | "Prevent-NonDelivery-Report:"
66 | msgPriority | "Priority:"
67 | msgReceived | "Received:"
68 | msgReferences | "References:"
69 | msgReplyBy | "Reply-By:"
70 | msgReplyTo | "Reply-To:"
72 | msgReturnPath | "Return-Path:"
73 | msgReturnReceiptTo | "Return-Receipt-To:"
74 | msgSeeAlso | "See-Also:"
75 | msgSender | "Sender:"
76 | msgSensitivity | "Sensitivity:"
77 | msgStatus | "Status:"
78 | msgSubject | "Subject:"
79 | msgSummary | "Summary:"
80 | msgSupersedes | "Supersedes:"
81 | msgTelefax | "Telefax:"
82 | msgX400ContentReturn | "X400-Content-Return:"
84 | msgXMailer | "X-Mailer:"
85 | msgXNewsreader | "X-Newsreader:"
86 | msgXref | "Xref:"


IMAP Control

Properties Methods Events Constants Example

Use the IMAP Control to retrieve mail from or store mail to any IMAP server. Mailboxes on the server are exposed as a collection of Mailbox Objects. Each Mailbox Object contains messages that can be retrieved and stored in its Messages property.

Powerful default operations are provided, including iteration through a message set to populate the Messages property.

Miscellaneous

Product | PowerTCP Mail Tool
Prog ID | Dart.Imap.1
File | DartMail.dll
Dependencies | DartSock.dll, DartUtil.dll
Threading | Apartment Model
Licensed | Yes


IMAP Control Usage

The IMAP Control can:

  • Operate transparently in the background while the user of your application is doing other tasks.

  • Function interactively with the user.

Simple methods are provided to perform the following tasks:

  • Authentication. Login method connects to a server and authenticates in one easy step.

  • Mailbox creation, deletion, and enumeration are accomplished with the Add, Remove, and Refresh methods.

  • Get Mail. Get method retrieves all or part of a message set.

  • Delete Mail. Delete and Purge methods delete messages from mailboxes.

  • Session termination. Logout method gracefully terminates a session.

  • Other Functions. Supports all the functionality of RFC 2060 while maximizing ease-of-use and flexibility.

Transparent Use

You want your mail transfer to operate in the background with minimal system impact. We recommend you program the mail transfer using non-blocking operation, so the user interface is not affected in any way. The following VB example shows how to retrieve a message when the user clicks a button:

Private Sub Command1_Click()

' use non-blocking operation

Imap1.Timeout = 0

' login to our server

Imap1.Login "imap.test.com", "user", "pass"

' pick this operation up in the Progress event

End Sub

Private Sub Imap1_Progress(ByVal Method As DartMailCtl.ImapMethodConstants, ByVal Status As DartMailCtl.ImapStatusConstants, ByVal Reply As String, ByVal MessageNumber As Long, ByVal Count As Long, ByVal Size As Long)

If Status = imapOk Then

Select Case Method

Case imapLogin

' logged in, get mailboxes

Imap1.Refresh

Case imapMailboxesRefresh

' mailbox listing complete, get INBOX messages

Imap1.Mailboxes("INBOX").Get

Case imapGet

' mail retrieve is complete for INBOX, log out

Imap1.Logout

Case imapLogout

' operation complete

End Select

End If

End Sub

Interactive Use

For interactive applications, transparency is not as important and blocking operation may be acceptable as shown in the following VB example:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Use the Timeout property to establish blocking operation

Imap1.Timeout = 1000

' Specify the address of the server to connect to

Imap1.Login "imap.test.com", "user", "pass"

'Get Mailbox listing

Imap1.Refresh

' get all the messages from INBOX and put them in the messages property

Imap1.Mailboxes("INBOX").Get

' all done, close connection!!

Imap1.Logout

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


AttachmentDirectory Property

Decoded message attachments are created in this directory.

Syntax

Object.AttachmentDirectory

Part | Description
Object | Evaluates to a POP Control, a SecurePop Control, or a Message Object.

Data Type

String

Remarks

The default value is ".\" (the default directory). This property can only be set at run time.

A message can include attached files. When these messages are decoded, the filename from the message is combined with this property to produce the file path used to recreate the attached file.

Note This property may be set at anytime for subsequent decoding operations.

If set to "" (an empty string) or the 'Content-Type' header does not include a name for the file, then the file is not created, and the Data property contains the decoded file.


Capabilities Property

Collection of strings that contains the protocol extensions supported by the server. Values are initialized during login.

Syntax

Object.Capabilities

Part | Description
Object | Evaluates to an IMAP Control.

Data Type

DartStrings Object

Remarks

Read-only (but you can remove Strings in the collection).

As part of the Login process, every IMAP server announces the capabilities of that server implementation. For example, the following strings may be added to the Imap.Capabilities string collection during login:

  • IMAP4

  • IMAP4REV1

  • NAMESPACE

  • IDLE

  • SCAN

  • SORT

  • MAILBOX-REFERRALS

  • LOGIN-REFERRALS

  • X-NOOP-DUPLICATE-SELECT

  • AUTH=LOGIN

  • THREAD=ORDEREDSUBJECT

Unlike the SMTP Control (which uses the Capabilities property to optimize the transmission of mail), the IMAP Control provides these values for informational purposes only.


Mailboxes Property

Collection of Mailbox Objects.

Syntax

Object.Mailboxes

Part | Description
Object | Evaluates to an IMAP Control.

Data Type

Mailboxes Object

Remarks

Read-only.

The Refresh method populates this property.


Command Method

Example

Send any command to the server.

Syntax

Object.Command Command, Reply

Part | Description
Object | Evaluates to an IMAP Control.
Command | String. Specifies the command to send.
Reply | Undimensioned String or Byte Array. Where the reply from the server will be put. Any contents will be replaced. A message would not be returned for this parameter when the Progress event fires, as that information would be available elsewhere.

Remarks

This method allows standard and non-standard commands to be sent. The reply from the server is copied to Reply; you determine success or failure. Reply must not go out of scope while the command completes (it must have file or global scope)

The control appends a CR/LF pair to the end of all commands so you should not send commands with a trailing CR/LF.

All commands must begin with a unique command identifier. The control generates and adds this to the beginning of a command you should not send commands with preceding command identifiers.

Error Codes

The Command method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol

  • ptTimeout


Login Method

Connect to a server and authenticate in one step.

Syntax

Object.Login Server [ , Username ] [ , Password ] [ , RemotePort ]

Part | Description
Object | Evaluates to an IMAP Control.
Server | String. Specifies the IMAP server host name (host.dart.com) or dot address (nnn.nnn.nnn.nnn).
Username | Optional String. Specifies the server account.
Password | Optional String. Specifies the password for the server account.
RemotePort | Optional Long. Specifies the desired port number. Defaults to the "well-known" port 143.

Remarks

Most IMAP servers require a Username and a Password.

Error Codes

The Login method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAbort

  • ptAddressInUse

  • ptAddressNotAvailable

  • ptAuthentication (An Invalid Username or Password was specified)

  • ptBlocked

  • ptConnected

  • ptConnectionAborted

  • ptConnectionRefused

  • ptConnectionReset

  • ptHostNotFound

  • ptNetworkDown

  • ptNetworkReset

  • ptNetworkUnreachable

  • ptNotInitialized

  • ptNoBufferSpace

  • ptNoData

  • ptProtocol (A protocol error was encountered)

  • ptTimeout

  • ptTryAgain


Logout Method

Gracefully end a session.

Syntax

Object.Logout

Part | Description
Object | Evaluates to an IMAP Control

Remarks

Unlike the POP Control, the IMAP Control does not delete all messages marked for deletion upon logout. The Purge method must be called to delete these messages.

Error Codes

The Logout method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol (A protocol error was encountered)

  • ptTimeout


Refresh Method

Get a listing of mailboxes.

Syntax

Object.Refresh [ Name ] [ , Reference ]

Part | Description
Object | Evaluates to an IMAP Control.
Name | Optional String. Specifies the name of the mailbox; may include wildcards. Defaults to all mailboxes (*).
Reference | Optional String. Specifies the reference point to start the listing. Defaults to the current path.

Remarks

The Mailboxes property is emptied and repopulated each time this method is called. Each Mailbox Object and the messages they hold are destroyed unless stored to another object.

Error Codes

The Refresh method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol

  • ptTimeout


Alert Event

Example

Fires when an alert message is received from the server.

Syntax

Private Sub Object_Alert ( Message As String )

Part | Description
Object | Evaluates to an IMAP Control.
Message | String. Specifies the human readable alert message received from the server.

Remarks

The message may be immediately displayed to the user.


Progress Event

Fires when a method has completed, the server has sent a reply, or progress information is available.

Syntax

Private Sub Object_Progress ( Method As ImapMethodConstants, Status As ImapStatusConstants, Reply As String, MessageNumber As Long, Count As Long, Size As Long )

Part | Description
Object | Evaluates to an IMAP Control.
Method | ImapMethodConstants. Indicates the method that the event pertains to.
Status | ImapStatusConstants. Indicates the status of the method.
Reply | String. Specifies the server reply related to the status.
MessageNumber | Long. Specifies the server-side message the event pertains to. This value corresponds to the message's Attribute(msgNumber) property.
Count | Long. Specifies the number of bytes that have been received (so far) for the transfer that is currently in progress. The value normally falls between 0 and Size. Only valid when Status is imapContent, and is 0 at other times.
Size | Long. Specifies the total number of bytes in the message transfer currently in progress. This value is constant during any single transfer. Only valid when Status is imapContent, and is 0 at other times.

Remarks

Use the Trace method to gather protocol-level data if Reply is inadequate.


ImapMethodConstants

Enumerates values of the Method parameter of the Progress event:

Value | Constant | Description
0 | imapUnknown | Unknown
1 | imapCommand | Command method
2 | imapLogin | Login method
3 | imapLogout | Logout method
4 | imapMailboxesAdd | Mailboxes Add method
5 | imapRemove | Remove method
6 | imapRefresh | Refresh method
7 | imapSubscribe | Subscribe method
8 | imapUnsubscribe | Unsubscribe method
9 | imapMailboxAdd | Mailbox Add method
10 | imapCopy | Copy method
11 | imapDelete | Delete method
12 | imapGet | Get method
13 | imapPurge | Purge method
14 | imapPut | Put method
15 | imapSearch | Search method
16 | imapUndelete | Undelete method
17 | imapMailboxRefresh | Refresh method
18 | imapRename | Name method


ImapStatusConstants

Enumerates values of the Status parameter of the Progress event:

Value | Constant | Description
0 | imapOk | Method has completed with a positive status.
1 | imapBad | Server has responded with a status indicating bad syntax.
2 | imapNo | Server has responded with a negative status.
3 | imapBye | Server has indicated that it is about to close the connection.
4 | imapContent | Indicates intermediate events during the receipt of a mail message. Useful for percentage indication on a status display.
5 | imapInfo | Server has supplied information.


Mailbox Object

The Mailbox Object transforms an IMAP mailbox on a server into a local object that you can easily manipulate. Most properties manipulate the object model and the mailbox on the server.


Count Property

Number of messages in the server mailbox. The Refresh method is used to initialize the value of this property.

Syntax

Object.Count

Part | Description
Object | Evaluates to a Mailbox Object.

Data Type

Long

Remarks

Read-only.

This property is updated whenever an action is performed on the mailbox. Use the Refresh method to update this property without performing an action on the mailbox.


Delimiter Property

Parses the Name into a hierarchical structure.

Syntax

Object.Delimiter

Part | Description
Object | Evaluates to a Mailbox Object.

Data Type

String

Remarks

Read-only.

The Name property may contain a name that is to be parsed into a hierarchy. Use this property as a separator for parsing. For example the name /home/testuser/mailbox1 may be the value for the name. The name should be parsed using the "/" delimiter into a hierarchy of:


Flags Property

Collection of flags set for the mailbox.

Syntax

Object.Flags

Part | Description
Object | Evaluates to a Mailbox Object.

Data Type

DartStrings Object

Remarks

Read-only. The following are examples and definitions of flags that the server may set for the mailbox:

  • \Marked Mailbox has been marked "interesting" by the server; commonly means the mailbox contains new messages.

  • \Unmarked Mailbox does not contain any additional messages since the last time it was accessed.

  • \Noinferiors Mailbox cannot contain any sub-mailboxes.

  • \Noselect Mailbox may not contain messages. Typically used for storing sub-mailboxes.


Messages Property

Collection of Message Objects that is the default destination for downloaded messages when using Get.

Syntax

Object.Messages

Part | Description
Object | Evaluates to a POP Control or a SecurePop Control.

Data Type

Messages Object

Remarks

This property provides the default destination for Get operations. Initially, this collection is empty. If Get is then used to request header information for messages 1, 3, and 5, three Message Objects are created and added to this collection to hold the data provided by the server.

The index for the message reflects the position in the collection, not the message number on the server. The message's Attribute property can be used to correlate downloaded messages with messages on the server.


Name Property

Mailbox name.

Syntax

Object.Name

Part | Description
Object | Evaluates to a Mailbox Object.

Data Type

String

Remarks

The Refresh method is used to initialize the value of this property. Change this property to rename the mailbox on the server. If the new value is the same as the current value or the Mailbox Object is not part of a Mailboxes collection, then no operation is performed.

Error Codes

The Name property may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol

  • ptTimeout


ReadOnly Property

Mailbox is read-only or read-write.

Syntax

Object.ReadOnly

Part | Description
Object | Evaluates to a Mailbox Object.

Data Type

Boolean

Remarks

Set to False to attempt to reopen the mailbox as read-write during the next operation on the mailbox. Set to True to attempt to reopen the mailbox as read-only during the next operation on the mailbox.

If the mailbox cannot be reopened to its new state then the property is set to its original value. Setting this property to the current value has no effect.

Error Codes

The ReadOnly property may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol

  • ptTimeout


Recent Property

Number of messages in the mailbox with a "Recent" flag.

Syntax

Object.Recent

Part | Description
Object | Evaluates to a Mailbox Object.

Data Type

Long

Remarks

Read-only.

This property is updated whenever an action is performed on the mailbox. Use the Refresh method to update this property without performing an action on the mailbox.


Uid Property

Unique identifier of the mailbox. The Refresh method is used to initialize the value of this property.

Syntax

Object.Uid

Part | Description
Object | Evaluates to a Mailbox Object.

Data Type

String

Remarks

Read-only.


Add Method

Add a message to the mailbox.

Syntax

Object.Add Message

Part | Description
Object | Evaluates to a Mailbox Object.
Message | String or Byte Array containing an encoded message, or a String containing the file name of a file containing the message.

Error Codes

The Add method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol

  • ptTimeout


Copy Method

Copy one or more messages to another mailbox.

Syntax

Object.Copy Destination [ , MsgSet ]

Part | Description
Object | Evaluates to a Mailbox Object.
Destination | String. Specifies the name of the destination mailbox.
MsgSet | Optional String. Specifies the message numbers to copy. The default is all messages.

Remarks

If provided, MsgSet specifies one or more message numbers in the range from 1 to Count. Each number should be separated with a comma. A range of numbers may be indicated with a lower and upper number separated with a colon. For example, a message set of "1, 5:7, 12" will retrieve 5 messages: 1, 5, 6, 7, and 12.

Error Codes

The Copy method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol

  • ptTimeout


Delete Method

Mark one or more messages for deletion.

Syntax

Object.Delete [ MsgSet ]

Part | Description
Object | Evaluates to a Mailbox Object.
MsgSet | Optional String. Specifies the message numbers to mark for deletion. The default is all messages.

Remarks

This method only marks a message for deletion. The message is not permanently removed until the Purge method is used.

If provided, MsgSet specifies one or more message numbers in the range from 1 to Count. Each number should be separated with a comma. A range of numbers may be indicated with a lower and upper number separated with a colon. For example, a message set of "1, 5:7, 12" retrieves the following five messages: 1, 5, 6, 7, and 12.

Error Codes

The Delete method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol

  • ptTimeout


Get Method

Get one or more messages.

Syntax

Object.Get [ Part ] [ , MsgSet ] [ , Msg ]

Part | Description
Object | Evaluates to a Mailbox Object.
Part | Optional GetConstants. Specifies the message part to be retrieved. The default value is imapContent.
MsgSet | Optional String. Specifies the message numbers to get. The default is all messages.
Msg | Optional String that specifies the (local) destination file name, or an undimensioned String or Byte array that will be dynamically expanded and filled with a single message. If not specified or NULL, the Messages property is used as the destination.

Remarks

This method makes it easy to download any or all parts of a set of messages. The default destination for messages is the Messages property.

If provided, MsgSet specifies one or more message numbers in the range from 1 to Count. Each number should be separated with a comma. A range of numbers may be indicated with a lower and upper number separated with a colon. For example, a message set of "1, 5:7, 12" will retrieve 5 messages: 1, 5, 6, 7, and 12.

If the destination is the Messages Collection, this method creates all required Message Objects. If a Message Object exists with the same Attribute property, it is reused. Therefore, you can first get the Size of messages causing creation of a Message Object for each message. Getting the imapGetContent will reuse the Message Objects previously created.

If Msg is specified, MsgSet must reference a single message. If Msg is a buffer and Timeout is 0 (non-blocking), Msg must not go out of scope while the operation completes (the Msg String or Byte array must be global in scope).

Error Codes

The Get method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol

  • ptTimeout


Purge Method

Permanently remove all messages marked for deletion.

Syntax

Object.Purge

Part | Description
Object | Evaluates to a Mailbox Object.

Error Codes

The Purge method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol

  • ptTimeout


Put Method

Set message attributes.

Syntax

Object.Put Value [ , Part ] [ , MsgSet ]

Part | Description
Object | Evaluates to a Mailbox Object.
Value | String. Specifies the value to set for the Part.
Part | Optional PutConstants. Specifies the message part to be set. The default value is imapPutFlagsAdd.
MsgSet | Optional String. Specifies the message numbers to set. The default is all messages.

Remarks

This method makes it easy to alter parts of a message or messages on the server. According to RFC 2060, you can only set the flags message part.

If provided, MsgSet specifies one or more message numbers in the range from 1 to Count. Each number should be separated with a comma. A range of numbers may be indicated with a lower and upper number separated with a colon. For example, a message set of "1, 5:7, 12" will retrieve 5 messages: 1, 5, 6, 7, and 12.

See RFC 2060 for a list of predefined flags that can be set for a message. Other server implementations may have additional flags that can be set.

Error Codes

The Put method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol

  • ptTimeout


Refresh Method

Update the mailbox Count, Recent, and Uid properties.

Syntax

Object.Refresh

Part | Description
Object | Evaluates to a Mailbox Object.

Remarks

Use this method to get information about a mailbox without performing any operations on it. Normally the Count, Recent, and Uid properties are updated after an operation is performed on the mailbox.

Error Codes

The Refresh method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol

  • ptTimeout


Search Method

Search for a specific message or set of messages.

Syntax

Object.Search Criteria, MsgSet [ , CharacterSet ]

Part | Description
Object | Evaluates to a Mailbox Object.
Criteria | String. Specifies the criteria used for searching. This string must be in the format specified by RFC 2060 Section 6.4.4.
MsgSet | Undimensioned string. Where the reply from the search will be put. Any contents will be replaced.
CharacterSet | Optional String. Specifies the character set used for the search.

Remarks

MsgSet will be empty or will contain numbers separated by a space. These numbers specify the message numbers on the server that meet the search criteria. MsgSet must not go out of scope while the command completes (it must have file or global scope).

Error Codes

The Search method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol

  • ptTimeout


Undelete Method

Unmark one or more messages previously marked for deletion.

Syntax

Object.Undelete [ MsgSet ]

Part | Description
Object | Evaluates to a Mailbox Object.
MsgSet | Optional String. Specifies the message numbers to unmark for deletion. The default is all messages.

Remarks

An unmarked message is not deleted when the Purge method is called.

If provided, MsgSet specifies one or more message numbers in the range from 1 to Count. Each number should be separated with a comma. A range of numbers may be indicated with a lower and upper number separated with a colon. For example, a message set of "1, 5:7, 12" will retrieve 5 messages: 1, 5, 6, 7, and 12.

Error Codes

The Undelete method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol

  • ptTimeout


GetConstants

Enumerates values of the Part parameter of the Get method:

Value | Constant | Description
0 | imapGetContent | Requests the retrieval of the complete message for each message in MsgSet.
1 | imapGetSize | Requests the size for each message specified in MsgSet.
2 | imapGetUid | Requests the message UID label for each message in MsgSet.
3 | imapGetFlags | Requests the flags for each message specified in MsgSet.
4 | imapGetHeaders | Requests the retrieval of the header fields for each message in the MsgSet.


PutConstants

Enumerates values of the Part parameter of Put method:

Value | Constant | Description
0 | imapPutFlags | Replaces the flags for each message in the MsgSet.
1 | imapPutFlagsAdd | Adds flags for each message in the MsgSet.
2 | imapPutFlagsRemove | Removes flags for each message in the MsgSet.


Mailboxes Object

The Mailboxes Object represents a collection of Mailbox Objects returned from an IMAP server.


Add Method

Create a mailbox.

Syntax

Object.Add Mailbox

Part | Description
Object | Evaluates to a Mailboxes Object.
Mailbox | Mailbox Object to add to the collection and create on the server. The mailbox Name property is used when creating on the server.

Remarks

This method adds a Mailbox object to the local collection and creates the mailbox on the server. If the mailbox already exists, a runtime error is generated. The mailbox is added to the local collection if the command succeeds; otherwise, the mailbox is not added.

Error Codes

The Add method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol (if mailbox already exists)

  • ptTimeout


Item Method

Provide array access to the collection.

Syntax

Mailbox = Object.Item Index

Part | Description
Object | Evaluates to a Mailboxes Object.
Index | Long index or String. Contains the mailbox name to return.
Mailbox | Returned Mailbox Object found at Index position in the collection.

Remarks

The Item method may be used to access a mailbox by index in the collection or by the name of the mailbox.

Error Codes

The Item method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptInvalidParam1


Remove Method

Remove a mailbox.

Syntax

Object.Remove Index

Part | Description
Object | Evaluates to a Mailboxes Object.
Index | Long index or String. Specifies the mailbox name to remove.

Remarks

This method removes the corresponding Mailbox Object from the collection and deletes the mailbox from the server. The mailbox is removed from the local collection if the command succeeds; otherwise, it is not removed from the collection.

Error Codes

The Remove method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptInvalidParam1 (if mailbox does not exist in collection)

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol (A protocol error was encountered)

  • ptTimeout


Subscribe Method

Subscribe to a public mailbox.

Syntax

Object.Subscribe Name

Part | Description
Object | Evaluates to a Mailboxes Object.
Name | String. Specifies the name of the public mailbox to subscribe to.

Remarks

A public mailbox is a mailbox that anyone can access. Messages usually cannot be deleted from public mailboxes unless special privileges are given.

Error Codes

The Subscribe method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol (Mailbox does not exist)

  • ptTimeout


Unsubscribe Method

Unsubscribe from a public mailbox.

Syntax

Object.Unsubscribe Name

Part | Description
Object | Evaluates to a Mailboxes Object.
Name | String. Specifies the name of the public mailbox to unsubscribe from.

Remarks

A public mailbox is a mailbox that everyone can access. Messages usually cannot be deleted from public mailboxes unless special privileges are given.

Error Codes

The Unsubscribe method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol (Not subscribed to mailbox)

  • ptTimeout


Message Object

Properties Methods Constants Example

The Message Object transforms any Internet mail message into an object that you can easily manipulate within your program. Alternatively, any message that you build or modify can be quickly encoded and sent.

Most of the properties manipulate the object model, with the exception of Content. which when set, dynamically creates a new object. When read, Content encodes the object model and returns it as a String or Byte array.

The Message Object provides complete support for MIME structures. High level methods (AddAttachment, Reply, Forward, AddMessage, AddText, and AddDigest) streamline the composition of sophisticated messages.

Additional features include persistence to disk in two formats: transport ready (encoded) message format and a quick loading (decoded) object format.

Miscellaneous

Product | PowerTCP Mail Tool
Prog ID | Dart.Message.1
File | DartMail.dll
Dependencies | DartSock.dll
Threading | Apartment Model
Licensed | Yes


AttachmentDefaults Property

When an attachment is added to a message, header fields are included that describe the attachment. This property provides default header fields for common attachment file types. These strings may be modified or more added so subsequent calls to the AddAttachment method use the header fields you provide.

Syntax

Object.AttachmentDefaults

Part | Description
Object | Evaluates to a Message Object.

Data Type

DartStrings Object

Remarks

Each string contains a single header field for an attachment type. Defaults are supplied by the control. Multiple strings may apply to the same file type. Typical strings may be:

  • "TXT:Content-Type: text/plain;charset=us-ascii"

  • "TXT:Content-dispositon: inline"

The text preceding the first colon always indicates the suffix of the file type to which the header field pertains.


AttachmentOverwrite Property

AttachmentOverwrite

Specifies whether decoded message attachments are overwritten if the filename is the same.

Syntax

Object.AttachmentOverwrite

Part | Description
Object | Evaluates to a POP Control or a Message Object.

Data Type

Boolean

Remarks

The default value of this property is False. If the value is set to True, pre-existing files that are in the directory specified by the AttachmentDirectory property will be overwritten. Otherwise, files will be added with a number appended based on the format used by Microsoft (ex: File.txt, File(1).txt, File(2).txt).


Attribute Property

Server-related attributes of the message.

Syntax

Value = Object.Attribute ( Index )

Object.Attribute ( Index ) = Value

Part | Description
Object | Evaluates to a Message Object.
Index | AttributeConstants.

Data Type

String or Long

Remarks

Read-only.

This value sets and returns the server-related attributes of a message.


Bcc Property

Collection of recipient address strings that are not disclosed to other recipients (Blind Carbon Copy).

Syntax

Object.Bcc

Part | Description
Object | Evaluates to a Message Object.

Data Type

DartStrings Object

Remarks

The message is sent to these recipients, but the Bcc header field is removed from the message before it is sent. See the Address Formats topic for more information.


Cc Property

Collection of address strings for the secondary recipients (Carbon Copy).

Syntax

Object.Cc

Part | Description
Object | Evaluates to a Message Object.

Data Type

DartStrings Object

Remarks

See the Address Formats topic for more information.


Content Property

Read from this property to encode the message or write to this property to initialize the object.

Syntax

EncodedMessage = Object.Content ( [ Segment ] [ , ReturnType ] )

Object.Content = EncodedMessage

Part | Description
Object | Evaluates to a Message Object.
Segment | SegmentConstants. Specifies either the header or the complete message.
ReturnType | ReturnTypeConstants. Specifies the return value is a String or a Byte array.

Data Type

String or Byte array

Remarks

The Message Object represents a message as properties and collections of properties. The header is comprised of the To, Cc, Bcc, and Header properties. These elements are formatted to produce the encoded header. The message text and attachments are stored in Part Objects objects and are managed by the PartList Object and Parts Collection.

When setting this property, the Segment and ReturnType parameters are ignored if provided. Setting this property causes a re-initialization of the object. By setting this property to "" (an empty string), the object is cleared of all content.

When reading this property, Segment defaults to msgMessage and ReturnType defaults to msgString. Alternative parameters can be used to return only the encoded header and/or a Byte array. The message is dynamically encoded when this property is read. When Segment is msgHeader, the returned value includes a trailing CRLFCRLF sequence so that a message body can be easily appended.

This property is commonly used to populate a Message Object or to get an encoded message that may be saved or sent to a mail server.

Error Codes

The Content property may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptFile

  • ptInvalidParam1

  • ptInvalidParam2

  • ptNoBufferSpace


From Property

Specifies the author of the message.

Syntax

Object.From

Part | Description
Object | Evaluates to a Message Object.

Data Type

String

Remarks

Sets and returns the From header value in the Header property. See Address Formats for more information.


Header Property

Collection of header fields contained in a Message Object or a Part Object.

Syntax

Object.Header

Part | Description
Object | Evaluates to a Message Object or a Part Object.

Data Type

HeaderFields Object

Remarks

The difference between the Header property associated with the Message Object and Part Object is the treatment of the To, Cc, and Bcc labels. The Message Object has separate properties for these labels, and therefore excludes these labels from the Header property. Part Objects include these labels within this property.

Refer to the HeaderFields Object for more information.


PartList Property

Collection of all Part Objects in a multipart message.

Syntax

Object.PartList

Part | Description
Object | Evaluates to a Message Object.

Data Type

PartList Object

Remarks

Read-only.

The Message Object provides two means of accessing body parts in a multipart message. The Parts Object contains "sibling" Part Objects at a single level in the message and the PartList Object includes all (possibly nested) parts in the message.


Parts Property

Collection of "sibling" Part Objects existing at a single level in the message.

Syntax

Object.Parts

Part | Description
Object | Evaluates to a Message Object or a Part Object.

Data Type

Parts Object

Remarks

Messages may include body parts that contain body parts that contain body parts, etc. This property contains only the "sibling" parts that exist at the level of the referenced Message Object or Part Object.


QuotedPrintable Property

When set to True, Quoted-Printable encoding is applied to textual parts of the message when it is encoded. When set to False, textual parts of the message are sent "as-is".

Syntax

Object.QuotedPrintable

Part | Description
Object | Evaluates to a Message Object.

Data Type

Boolean

Remarks

The default value is True. You can set this property at design time.

Quoted-Printable encoding ensures the correct transmission of primarily textual information, while making is possible for the recipient to understand the message by inspection if it cannot be decoded. When set to False and the textual information being sent includes special characters (such as an "end of message" sequence), it is possible for your user to include text that cannot be sent.


Size Property

Returns the size of the encoded message.

Syntax

Object.Size

Part | Description
Object | Evaluates to a Message Object.

Data Type

Long

Remarks

Read-only.

When large messages are sent it is sometimes desirable to display a progress indication. This property provides an estimate of the size of the encoded message. When the POP Control Get method is used to get the size of a message, this property is initialized to the value provided by the server.


Subject Property

Subject of the message.

Syntax

Object.Subject

Part | Description
Object | Evaluates to a Message Object.

Data Type

String

Remarks

This value sets and returns the Subject header value in the Header property.


Text Property

Text contained in a non-multipart message.

Syntax

Object.Text

Part | Description
Object | Evaluates to a Message Object.

Data Type

String

Remarks

This property contains message text associated with a non-multipart message (Message.Parts.Count = 0). If the message is a multipart message (Message.Parts.Count > 0), then this property has no meaning.

Error Codes

The Text property may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptFile

  • ptNoBufferSpace


To Property

Collection of recipient address strings.

Syntax

Object.To

Part | Description
Object | Evaluates to a Message Object.

Data Type

DartStrings Object

Remarks

See Address Formats for more information.


AddAttachment Method

Attach a file to the message.

Syntax

Part = Object.AddAttachment FileName

Part | Description
Object | Evaluates to a Message Object.
FileName | String. Fully qualified path of the file to attach.
Part | Part Object created and added to the message's Parts property.

Remarks

This method provides a simple way to attach a file to a message. The attributes of the file are determined by the file extension and AttachmentDefaults, which are used to correctly label and encode the file. Any number of attachments may be added.

The file does not have to exist yet, because the file is not read until encoding is performed. An error is generated if the file cannot be accessed.

Error Codes

The AddAttachment method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptFile

  • ptNoBufferSpace


AddDigest Method

Create a digest message such as that used to archive newsgroup or mailing list correspondence.

Syntax

Part = Object.AddDigest Message [ , Intro ]

Part | Description
Object | Evaluates to a Message Object.
Message | String or Byte array providing the encoded message to be added to the digest, or a String containing the name of a file containing the message.
Intro | Optional String or Byte Array. If provided on the first call, this parameter specifies introductory text for the digest.
Part | Part Object object created and added to the message's Parts property.

Remarks

A mail digest is a collection of complete mail messages including the To/From/Subject/Date and message body, for a series of related messages. The messages may be related to a topic, or related by a period of time (for example, the month of January). The digest generally includes introductory text explaining the relationship of the messages that follow (for example, "Wall-Paper Appreciation Mailing list Archive for January, 1999").

Error Codes

The AddDigest method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptFile

  • ptNoBufferSpace


AddMessage Method

Attach an existing message to the message.

Syntax

Part = Object.AddMessage Message

Part | Description
Object | Evaluates to a Message Object.
Message | String or Byte array providing the encoded message to be added to the new message part, or a String containing the name of the file containing the encoded message.
Part | Part Object object created and added to the message's Parts property.

Remarks

This method provides a simple way to attach an existing message. Any number of existing messages can be added to a Message object. Although this method may be used to "Forward" a message, the Forward method is even easier to use.

Error Codes

The AddMessage method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptFile

  • ptNoBufferSpace


AddText Method

Example

Add a text body part, optionally specifying a character set.

Syntax

Part = Object.AddText Text [ , Charset ]

Part | Description
Object | Evaluates to a Message Object.
Text | String or Byte array with text to use for the part, or a String containing the name of the file containing the text to use for the part.
Charset | Optional String. Specifies the character set. Any registered character set may be specified. Default is "us-ascii".
Part | Part Object created and added to the message's Parts property.

Remarks

This method allows text parts to be added to multipart messages. Together with the AddAttachment, AddMessage, and AddDigest methods, many common message formats may be created.

This method is used to add text if the message is multipart (Message.Parts.Count > 0). If a non-multipart message is being composed, the Text property can be used instead.

Error Codes

The AddText method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptFile

  • ptNoBufferSpace


Browse Method

Activate the edit window. This is a debugging feature that supports run-time access for message browsing and editing.

Syntax

Object.Browse

Part | Description
Object | Evaluates to a Message Object.

Remarks

This method creates a modal edit dialog window allowing browsing and modification of the Message Object. You may load/save messages, as well as browse and edit the message structure and contents.

This method can be invoked from the Visual Basic Immediate window at any breakpoint to support your development.


Decode Method

Decode a message from consecutive buffers of encoded data.

Syntax

Object.Decode Segment

Part | Description
Object | Evaluates to a Message Object.
Segment | String or Byte array. Provides the encoded message stream.

Remarks

This method decodes a data stream of consecutive buffer segments. It is useful for decoding very large messages, where a large buffer assignment to the Content property would negatively impact the operating system or user interface.

The AttachmentDirectory property indicates if and where attachments will be stored.

The Content property can be set to an empty String to clear the contents of the Message Object between messages.

Error Codes

The Decode method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptFile

  • ptInvalidParam1

  • ptNoBufferSpace


DecodeBuf Method

Decode a single buffer.

Syntax

Object.DecodeBuf SourceBuf, DestBuf, CodingType

Part | Description
Object | Evaluates to a Message Object.
SourceBuf | String or Byte array. String to be decoded.
DestBuf | String or Byte array. Buffer to receive the decoded result.
CodingType | CodingConstants. The type of decoding to apply.

Remarks

This function supports isolated decoding requirements such as header field interpretation. DecodeBuf does not affect the Message.

If DestBuf specifies a dimensioned Byte array or a non-empty String, it is redimensioned and filled with decoded data that may contain embedded nulls. If DestBuf specifies an undimensioned Byte array or empty String, it is dynamically expanded and filled. DestBuf must not be a fixed length String (String*100 will not work).

Error Codes

The DecodeBuf method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidArg1

  • ptInvalidArg2

  • ptInvalidArg3

  • ptNoBufferSpace


Encode Method

Generate consecutive segments of the encoded message stream.

Syntax

Count = Object.Encode Segment

Part | Description
Object | Evaluates to a Message Object.
Segment | String or Byte Array. Provides the buffer to receive the next encoded message segment. A Long value of 0 will reset encoding to the start of the message.
Count | Long. Returns the number of bytes stored in Segment.

Remarks

Each use of this method generates another consecutive segment of the encoded message stream. Each segment can then be streamed by the SMTP Control (for example) for transmission.

Segment may be arbitrarily redimensioned as necessary. Count is the only indicator of the number of bytes encoded.

When the entire message is encoded, Segment returns a length of 0 indicating the end. The cycle of segments may be reset at any time by setting Segment to 0; the next call to the Encode method returns the first segment.

The SMTP Control uses this method to encode and send all messages from its Message property.

Error Codes

The Encode method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptFile

  • ptInvalidParam1

  • ptNoBufferSpace


EncodeBuf Method

Encode a buffer.

Syntax

Object.EncodeBuf SourceBuf, DestBuf, CodingType

Part | Description
Object | Evaluates to a Message Object.
SourceBuf | String or Byte array. Data to be encoded
DestBuf | String or Byte array. Buffer to receive the encoded result.
CodingType | CodingConstants. Type of encoding to apply.

Remarks

This function is provided to support isolated encoding requirements such as header label generation. This method does not affect the Message Object.

If DestBuf specifies a dimensioned Byte array or a non-empty String, it is redimensioned and filled with encoded data that may contain embedded nulls. If DestBuf specifies an undimensioned Byte array or empty String, it is dynamically expanded and filled. DestBuf must not be a fixed length String (String*100 will not work).

Error Codes

The EncodeBuf method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptNoBufferSpace

  • ptInvalidArg1

  • ptInvalidArg2

  • ptInvalidArg3


Forward Method

Create a "forwarded" message to the specified recipient.

Syntax

Message = Object.Forward To [ , Text ]

Part | Description
Object | Evaluates to a Message Object.
To | String containing addresses that the message is to be forwarded to. See the Address Formats topic.
Text | Optional String or Byte array with introductory text for the forwarded message.
Message | New "forwarded" Message.

Remarks

This method returns a new message that contains the specified text and the original message. The new message contains the original message including attachments.

Error Codes

The Forward method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptNoBufferSpace

  • ptFile


Load Method

Load a message file.

Syntax

Object.Load File [ , Segment ]

Part | Description
Object | Evaluates to a Message Object.
File | String. Contains the fully qualified filename to be loaded.
Segment | Optional SegmentConstants. Determines how much of the message is to be read from the file. Defaults to msgMessage.

Remarks

This method senses the format of the file (encoded message or object) and initializes the Message Object as the file contents are read. See the Store method.

Error Codes

The Load method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptNoBufferSpace

  • ptFile


Reply Method

Create a "reply" message to sender or all recipients.

Syntax

Message = Object.Reply Text [ , Leader ] [ , All ]

Part | Description
Object | Evaluates to a Message Object.
Text | String or Byte array. Provides the new text for the reply message.
Leader | Optional String. Provides the indent character string for the old message text. The default is ">".
All | Optional Boolean. Defaults to False. False addresses the reply to the sender of the original message; True addresses the reply to all recipients listed in the original message (To and Cc).
Message | Returns the created Message.

Remarks

When responding to one or all recipients of a mail message, this method can be used to create the new message.

The original text is indented with the specified Leader and prepended with Text. Any attachments are removed from the Reply.

Error Codes

The Reply method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptNoBufferSpace

  • ptInvalidParam1


Store Method

Store a message in a file.

Syntax

Object.Store File [ , Format ]

Part | Description
Object | Evaluates to a Message Object.
File | String. Contains the fully qualified filename to be created.
Format | Optional FormatConstants. Determines the format of the saved message. Defaults to msgEncoded.

Remarks

If the Format parameter is msgEncoded or unspecified, the message will be stored as a transport ready file containing the encoded message.

If the Format parameter is msgDecoded the message will be stored in an object format. These files are smaller and quicker to read and write then an encoded file. Decoded files store attached files externally. In addition, data is stored as 8-bit data instead of the 7-bit data used in msgEncoded format. This results in smaller files and there is no decoding required when the file is loaded (see the Load method).

Error Codes

The Store method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptFile

  • ptInvalidParam2

  • ptNoBufferSpace


AttributeConstants

Enumerates the values of the Index parameter of the Attribute property.

Value | Constant | Description
0 | msgNumber | Message number assigned by a POP3 or IMAP server.
1 | msgUid | Message unique id assigned by a POP3 or IMAP server.
2 | msgSeen | Message has been read (IMAP only).
3 | msgAnswered | Message has been answered (IMAP only).
4 | msgFlagged | Message is marked for urgent attention (IMAP only).
5 | msgDeleted | Message is marked for removal (POP3 and IMAP).
6 | msgDraft | Composition of message not complete (IMAP only).
7 | msgRecent | Message is new this session (IMAP only).


CodingConstants

Enumerates encoding/decoding algorithms.

Value | Constant | Description
0 | msgBase64 | Base 64
1 | msgQuotedPrintable | Quoted Printable
2 | msgUTF7 | UTF 7
3 | msgUTF8 | UTF 8
4 | msgUUEncode | UUENCODE


FormatConstants

Enumerates the values of the Format parameter of the Store method.

Value | Constant | Description
0 | msgEncoded | Store the encoded "transport-ready" version of the message.
1 | msgDecoded | Store the decoded object model version of the message.


ReturnTypeConstants

Enumerates the type of buffer to be returned from a property that returns either a String and Byte array.

Value | Constant | Description
0 | msgString | Return the value as a String.
1 | msgByteArray | Return the value as a Byte array.


SegmentConstants

Enumerates the message segments.

Value | Constant | Description
0 | msgHeader | Perform the operation on the header of the message.
1 | msgMessage | Perform the operation on the complete message.


Messages Object

Collection of Message Objects.


Add Method

Add a message to the collection.

Syntax

Object.Add Message [ , Index ]

Part | Description
Object | Evaluates to a Messages Object.
Message | Message Object to add to the collection.
Index | Optional Long. Defaults to the end of the collection. Specifies where in the collection the Message should be inserted.

Remarks

An object may be explicitly inserted at any point in the collection through use of the Index parameter. If the Index parameter is not specified, then Message will be added to the end of the collection.

Error Codes

The Add method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptNoBufferSpace

  • ptFile

  • ptInvalidParam1

  • ptInvalidParam2


Clear Method

Remove all objects from the collection.

Syntax

Object.Clear

Part | Description
Object | Evaluates to a Messages Object.

Remarks

Use of this method results in an empty collection (the Count property returns zero).


Item Method

Provides array access to the collection.

Syntax

Message = Object.Item Index

Part | Description
Object | Evaluates to a Messages Object.
Index | Long. Provides array access to the collection.
Message | Message found at Index position in the collection.

Error Codes

The Item method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptInvalidParam1


Remove Method

Remove an object from the collection.

Syntax

Object.Remove Index

Part | Description
Object | Evaluates to a Messages Object or a Parts Object.
Index | Long. Indicates the object to remove.

Remarks

Index is a ones-based numeric value indicating the position of the object in the collection.

Error Codes

The Remove method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptInvalidParam1


Part Object

Use the Part Object to perform complex manipulation of message parts.


Data Property

Message data contained in the Part Object.

Syntax

Object.Data = Data

Data = Object.Data ( ReturnType )

Part | Description
Object | Evaluates to a Part Object.
ReturnType | ReturnTypeConstants. Specifies the return value as a String or a Byte array. Defaults to String.

Data Type

String or Byte array

Remarks

This property contains data associated with the part.

If the part references an attached file, and the AttachmentDirectory property is "" (empty string), this property contains the file contents when the message is decoded. Otherwise, the property is empty.

If the part contains text, this property is used to set or read the text. When this property is set, ReturnType is ignored. The Data and File properties are mutually exclusive.

Error Codes

The Data property may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptFile

  • ptInvalidParam1

  • ptNoBufferSpace


Error Property

Indicates that an MD5 digest string was included and the digest has been checked and found invalid. This suggests that the received message part does not match the authored message part.

Syntax

Object.Error

Part | Description
Object | Evaluates to a Part Object.

Data Type

Boolean

Remarks

Read-only.

The integrity of individual body parts is reflected in this property. MD5 digest checking is always performed when a Content-MD5 label is detected. You can test for the existence of the MD5 label using the following code:

If Msg.Parts(1).Header( msgContentMD5 ) <> "" then label exists.


File Property

The attached (decoded) file for this Part.

Syntax

Object.File

Part | Description
Object | Evaluates to a Part Object.

Data Type

String

Remarks

When a message containing an attachment is received, the filename is stripped of path information and the AttachmentDirectory property is prepended to the received name to produce this property. When composing, you may set the File property to the fully qualified name of the file to be attached.

The Data and File properties are mutually exclusive.


Index Property

Identifier for a body part. This value is recalculated whenever changes to the message structure occur.

Syntax

Object. Index

Part | Description
Object | Evaluates to a Part Object.

Data Type

String

Remarks

Read-only.

This property is defined by the relative position of the Part Object within the structure of a message. If the structure of the message is altered, then this property changes.

This property is returned in the form Level1.Level2&ldots;Levelx. For example, "2.3.1" identifies this part as Message.Parts(2).Parts(3).Parts(1).


PartList Object

Collection of all Part Objects in the message. Parts are ordered numerically by the Index property.


Item Method

Provides array subscript access to the PartList and Parts collections.

Syntax

Part = Object.Item Index

Part | Description
Object | Evaluates to a Parts Object or a PartList Object.
Index | Long. Identifies a Part in the collection by one's based position.
Part | Returned Part Object located at Index in the collection.

Error Codes

The Item method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptInvalidParam1


Parts Object

This is an advanced topic and may be skipped until higher-level access methods are found inadequate. See the Message Object AddText, AddAttachment, AddMessage, and AddDigest methods for more information.

The Parts Object is normally referenced as the Parts property of the Message Object and the Part Object.


Add Method

Add a Part Object to the collection.

Syntax

Object.Add Part [ , Index ]

Part | Description
Object | Evaluates to a Parts Object.
Part | Part Object to add to the collection.
Index | Optional Long. Indicates the Part Object is to be added at this index value.

Remarks

The optional parameter Index indicates that Part is to be inserted at the specified index. This index is a ones based number up to the collection's Count property plus 1.

If Index is not specified, the Part object is added to the end of the collection.

Error Codes

The Add method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptInvalidParam2


POP Control

Properties Methods Events Constants Example

Use the POP Control to retrieve mail from any POP3 server. Retrieve and store sets of messages in the Messages property.

Powerful default operations are provided, including iteration through a message set to populate the Messages property.

Miscellaneous

Product | PowerTCP Mail Tool
Prog ID | Dart.Pop.1
File | DartMail.dll
Dependencies | DartSock.dll, DartUtil.dll
Threading | Apartment Model
Licensed | Yes


POP Control Usage

The POP Control provides the most functionality in the fewest programming steps. It can operate transparently in the background while the user of your application is doing other tasks, or it can function interactively with the user.

Simple methods are provided to perform the following tasks:

  1. Authentication. Login connects to a server and authenticate in one easy step.

  2. Get Mail. Get retrieves all or part of a message set.

  3. Delete Mail. Delete sets one or more messages as "marked-for-delete".

  4. Session termination. Logout gracefully terminates a session.

  5. Other Functions. The control supports all the functionality of RFC 1939 to maximize ease-of-use and flexibility.

Transparent Use

You want your mail transfer to operate in the background with minimal system impact. We recommend you program the mail transfer using non-blocking operation, so the user interface is not affected in any way. The following VB example shows how to retrieve a message when the user clicks a button:

Private Sub Command1_Click()

' use non-blocking operation

Pop1.Timeout = 0

' log in to server

Pop1.Login "pop1.server.com", "username", "password"

' pick this operation up in the Progress event

End Sub

Private Sub Pop1_Progress(ByVal Method As DartMailCtl.PopMethodConstants, ByVal Status As DartMailCtl.PopStatusConstants, ByVal Reply As String, ByVal MessageNumber As Long, ByVal Count As Long, ByVal Size As Long)

If Status = popOk Then

Select Case Method

Case popLogin

' logged in, get messages

Pop1.Get

Case popGet

' mail retrieve is complete, log out

Pop1.Logout

Case popLogout

' operation complete

End Select

End If

End Sub

Interactive Use

For interactive applications, transparency is not as important and blocking operation may be acceptable as shown in the following VB example:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Use the Timeout property to establish blocking behavior

Pop1.Timeout = 1000

' Specify the address of the server to connect to

Pop1.Login "pop1.server.com", "username", "password"

' get all the messages and put them in the messages property

Pop1.Get

' all done, close connection

Pop1.Logout

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Refer to POP Control Blocking Sample and POP Control Non-Blocking Sample for more information on blocking and non-blocking operation.


POP Control Event Sequencing

Events are generated as the server responds to commands. They can be ignored if Timeout is greater than 0 (See Non-Blocking Use of POP ) , or used to determine the progress of a request. The following table describes the event sequence produced by each POP Control method:

POP Method

Event Sequence Produces

Abort

State() signals new value of State property "tcpClosed"

Command

Progress(Method = popCommand, Status = popOk, Reply...) indicates that the command is complete.

Delete

Progress(Method = popDelete, Status = popInfo, "Message 1 has been..."...) indicates that the server has marked message 1 for delete. Multiple events to occur for multiple messages.

Progress(Method = popDelete, Status = popOk...) indicates that the Delete method is complete.

Get

(message size)

Progress(Method = popGet, Status = popSize, Reply, MessageNumber...) indicates that the server has returned a SIZE value. Multiple events occur for multiple messages.

Progress(Method = popGet, Status = popOk...) indicates that the Get method is complete.

(message preview)

Progress(Method = popGet, Status = popPreview, Reply, MessageNumber...) indicates that the server has returned a preview value. Multiple events occur for multiple messages.

Progress(Method = popGet, Status = popOk...) indicates that the Get method is complete.

(entire message)

Progress(Method = popGet, Status = popContent, Reply, MessageNumber, Count = 1000, Size = 3000 ) indicates that the server has returned 1000 bytes from a total of 3000 for the message.

Progress(Method = popGet, Status = popContent, Reply, MessageNumber, Count = 2000, Size = 3000 ) indicates that the server has returned 2000 bytes from a total of 3000 for the message.

Progress(Method = popGet, Status = popContent, Reply, MessageNumber, Count = 3000, Size = 3000) indicates that the server has returned 3000 bytes of from a total of 3000 for the message.

<Sequence may be repeated if multiple message are requested.>

Progress(Method = popGet, Status = popOk...) indicates that the Get method is complete.

Login

State() signals new value of State property "tcpConnecting"

State() signals new value of State property "tcpConnected"

Progress(Method = popLogin, Status = popInfo, , "UCB Pop server&ldots;") echoes the server connection greeting.

Progress(Method = popLogin, Status = popInfo, "Password Required" ) indicates that the server has accepted the USER command.

Progress(Method = popLogin, Status = popInfo, "Login Success" ) indicates that the server authentication is complete.

Progress(Method = popLogin, Status = popCount, &ldots;) indicates that the Count property has been updated.

Progress(Method = popLogin, Status = popOk, &ldots;) indicates that the Login command sequence is complete.

Logout

Progress(Method = popLogout, Status = popOk...) indicates that the Logout command sequence is complete.

State() signals new value of State property "tcpClosed"

Reset

Progress(Method = popReset, Status = popOk...) indicates that the Reset command is complete.

Trace

No events fire.


POP Control Non-Blocking Sample

If you structure the code so that sequencing is controlled by event code, then you can accomplish message transfer without blocking. This allows PowerTCP to operate relatively independent of your application.

Private Sub Command1_Click()

' Set Timeout to indicate non-blocking operation

Pop1.Timeout = 0

' Specify the address of the server, your username, and your password

Pop1.Login "pop.test.com", "user", "pass"

' the Login process will notify us when it is complete via the Progress event

End Sub

Private Sub Pop1_Progress(ByVal Method As DartMailCtl.PopMethodConstants, ByVal Status As DartMailCtl.PopStatusConstants, ByVal Reply As String, ByVal MessageNumber As Long, ByVal Count As Long, ByVal Size As Long)

If Status = popOk Then

Select Case Method

Case popLogin

' logged in, get all the messages from the server

Pop1.Get

Case popGet

' mail retrieve is complete, log out

Pop1.Logout

Case popLogout

' operation complete

End Select

ElseIf Status = popContent Then

' update the progress for the user

Label1.Caption = Str(Count) & " of " & Str(Size) & "Received"

End If

End Sub


POP Control Blocking Sample

By default, Timeout is a positive value that indicates all methods should wait until completion before returning. This is called blocking and greatly simplifies the sequencing of operations and error recovery. Consider the following VB example:

Private Sub Command1_Click()

' Use the Timeout property to establish blocking operation

Pop1.Timeout = 10000

' Specify the address of the server, your username, and your password

Pop1.Login "pop.test.com", "user", "pass"

' retrieves all messages on the server, and then log out

Pop1.Get

Pop1.Logout

End Sub

Now, add error handling so the application does not terminate if you experience a communications failure, as shown below:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Use the Timeout property to establish blocking operation

Pop1.Timeout = 10000

' Specify the address of the server, your username, and your password

Pop1.Login "pop.test.com", "user", "pass"

' retrieves all messages on the server, and then log out

Pop1.Get

Pop1.Logout

Exit Sub

OnError: ' Any error jumps here

' Don't use MsgBox because that interrupts event notification

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Now, display progress for your user. To do this, you need event notification during the message download. Insert code in the Progress event as shown below:

Private Sub Pop1_Progress(ByVal Method As DartMailCtl.PopMethodConstants, ByVal Status As DartMailCtl.PopStatusConstants, ByVal Reply As String, ByVal MessageNumber As Long, ByVal Count As Long, ByVal Size As Long)

If Status = popContent Then

Label1.Caption = Str(Count) & " of " & Str(Size) & " Received"

End If

End Sub

Progress information is displayed, but issues remain:

  • During message download, for single-thread applications, no other work can be done because the thread is trapped in the Get method.

  • You must prevent the user from exiting the application because you cannot allow the user to unload the application while blocked.

  • If the user initiates another activity through the user interface, make sure the user does not affect the mail transfer (by calling another method or capturing the thread for any length of time).


Count Property

Returns the number of messages on the server.

Syntax

Object.Count

Part | Description
Object | Evaluates to a POP Control or a SecurePop Control.

Data Type

Long

Remarks

Read-only.

When Login is used to connect to a server and authenticate, this property is set to the number of messages in the user's mailbox. This property is valid during the session and returns –1 at other times.

Numbers between 1 and Count are used to reference messages on the server. Do not attempt to reference messages outside this range. The Count of messages remains constant for the session. Even when messages are "marked-for-delete" using the Delete method, Count does not change, because messages are not actually deleted until the session ends.


Preview Property

Number of lines of message body desired when using Get with msgPreview specified as a parameter.

Syntax

Object.Preview

Part | Description
Object | Evaluates to a POP Control or SecurePop Control.

Data Type

Long

Remarks

The default value is 0.

When Get retrieves a preview of a message, the response includes the message header plus a number of lines from the beginning of the message body. The default value of 0 indicates that only the header is requested.

There is no guarantee that the preview lines returned are printable, or even intelligible. Commonly, however, they include some part of the text portion of the message.


Command Method

Example

Send any protocol command to the server.

Syntax

Object.Command Command, Reply, Multiline

Part | Description
Object | Evaluates to a POP Control or a SecurePop Control.
Command | String. Contains the command to send.
Reply | String. Where the reply from the server will be stored. A message would not be returned for this parameter when the Progress event fires, as that information would be available elsewhere.
Multiline | Boolean. True if a multiline reply is expected, otherwise False.

Remarks

Allows execution of standard and non-standard extension. The response from the server is copied to the Reply parameter, and you determine success or failure of the command.

You must correctly set Multiline for the command being sent. If a multiline response is specified, but not returned from the server, this method times out looking for a response termination sequence. If a Multiline reply is received but not specified, only the first line of the response returns.

Command should not include a trailing CR/LF.

Error Codes

The Command method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol

  • ptTimeout


Delete Method

Mark one or more messages for removal upon normal completion of the session.

Syntax

Object.Delete [ MsgSet ]

Part | Description
Object | Evaluates to a POP Control or a SecurePop Control.
MsgSet | Optional String. Specifies the message numbers to remove. The default is all messages. If provided, this string must indicate one or more values in the range from 1 to Count (for example, "1:12, 15, 18").

Remarks

The messages specified by MsgSet are "marked-for-delete". Message removal occurs when the session is gracefully ended using Logout. If Logout is not used all messages marked for deletion are "unmarked".

Call the Reset method to unmark messages "marked-for-delete" .

Error Codes

The Delete method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptInvalidParam1

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotInitialized

  • ptNotConnected

  • ptProtocol (A protocol error was encountered)

  • ptTimeout


Get Method

Get all or part of one or more messages.

Syntax

Object.Get [ Part ] [ , MsgSet ] [ , Msg ]

Part | Description
Object | Evaluates to a POP Control or a SecurePop Control.
Part | Optional PartConstants. Specifies the message part or attribute to be retrieved. Defaults to msgContent.
MsgSet | Optional String. Specifies the message numbers to get. The default is all messages.
Msg | Optional String specifying the (local) destination file name, or an undimensioned String or Byte array that will be dynamically expanded and filled with a single message. If not specified or NULL, the Messages property will be used as the destination. This parameter is ignored unless Part is msgContent and MsgSet designates a single message.

Remarks

This method makes it easy to download any or all parts of a set of messages. The default destination for messages is the Messages property.

If provided, MsgSet specifies one or more message numbers in the range from 1 to Count. Each number should be separated with a comma. A range of numbers may be indicated with a lower and upper number separated with a colon. For example, a message set of "1, 5:7, 12" will retrieve 5 messages: 1, 5, 6, 7, and 12. The POP protocol does support any other criteria for downloading messages. See the IMAP Control for sophisticated searching operations.

If the destination is the Messages Collection, this method creates all required Message Objects. If a Message Object exists with the same Attribute(msgNumber) property, it is reused. Therefore, you can first get the Size of messages causing creation of a Message object for each message. Getting the msgContent reuses the Message Objects previously created.

To discover what messages have arrived since the last download, save the number of messages in the mailbox at the end of each session. When you return, the mailbox may have more messages that you can reference by number. Alternatively, use Part=msgUidl. This creates a collection of Message Objects with the Attribute(msgNumber) property initialized to the UID of each message. Then set MsgSet to all the message numbers with UIDs that you have not yet downloaded.

If Msg is specified, MsgSet must reference a single message. If Msg is a buffer and Timeout is 0 (non-blocking), Msg must not go out of scope while the operation completes (the Msg String or Byte array should be global in scope).

If you use the Delete method to mark a message for deletion, and you subsequently include this message in MsgSet, then the ptInvalidParam2 error is generated. If a message is "marked for delete", and MsgSet is not specified (all messages are to be retrieved), then messages "marked for delete" are skipped, protecting you from a server error.

Error Codes

The Get method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptInvalidParam1

  • ptInvalidParam2

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptNotInitialized

  • ptProtocol (A protocol error was encountered)

  • ptTimeout


Login Method

Connect to a POP3 server and authenticate in one easy step.

Syntax

Object.Login Server [ , Username ] [ , Password ] [ , RemotePort ]

Part | Description
Object | Evaluates to a POP Control or a SecurePop Control.
Server | String. May either be a host name (host.dart.com) or dot address (nnn.nnn.nnn.nnn).
Username | Optional String. Specifies the server account to access.
Password | Optional String. Specifies the password for the server account.
RemotePort | Optional Long. Specifies the desired port number. Defaults to the "well-known" port 110.

Remarks

Most POP servers require a Username and Password; you should specify both. After a successful login the Count property is set to the number of messages on the server.

Error Codes

The Login method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAbort

  • ptAddressNotAvailable

  • ptAddressInUse

  • ptAuthentication (An Invalid Username or Password was specified)

  • ptBlocked

  • ptConnected

  • ptConnectionAborted

  • ptConnectionRefused

  • ptConnectionReset

  • ptHostNotFound

  • ptNetworkDown

  • ptNetworkReset

  • ptNetworkUnreachable

  • ptNoBufferSpace

  • ptNoData

  • ptNotInitialized

  • ptProtocol (A protocol error was encountered)

  • ptTimeout

  • ptTryAgain


Logout Method

End a session.

Syntax

Object.Logout

Part | Description
Object | Evaluates to a POP Control or a SecurePop Control.

Remarks

Call this method to end a session. Successful execution of this method permanently removes any "marked-for-delete" messages from the server, ends the session, and causes the server to terminate the connection. Failure to use this method causes the server to clear any pending "marked-for-delete" message flags.

The Attribute(msgNumber) property of each message in the Messages property is set to 0.

Error Codes

The Logout method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol (A protocol error was encountered)

  • ptTimeout


Reset Method

Remove the "mark-for-delete" flag from all messages on the server.

Syntax

Object.Reset

Part | Description
Object | Evaluates to a POP Control or a SecurePop Control.

Remarks

After calling this method, unless messages are again "marked-for-delete" with Delete, no messages are deleted from the server when Logout is called.

Error Codes

The Reset method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptNotInitialized

  • ptProtocol (A protocol error was encountered)

  • ptTimeout


Progress Event

Fires when a method has completed, the server has sent a reply, or progress information is available.

Syntax

Private Sub Object_Progress ( Method As PopMethodConstants, Status As PopStatusConstants, Reply As String, MessageNumber As Long, Count As Long, Size As Long )

Part | Description
Object | Evaluates to a POP Control.
Method | PopMethodConstants. Indicates the method that the event pertains to.
Status | PopStatusConstants. Indicates the Status of the method.
Reply | String. Contains the server reply related to the status.
MessageNumber | Long. Indicates the server-side message the event pertains to. Matches the message's Attribute(msgNumber) property.
Count | Long. Indicates the number of bytes that have transferred (so far) for the transfer that is currently in progress. The value normally falls between 0 and Size. Only valid when Status is popContent, and is 0 at other times.
Size | Long. Indicates the total number of bytes for the message transfer currently in progress. Value is constant during any single transfer. Only valid when Status is popContent, and is 0 at other times.

Remarks

Use the Trace method to gather protocol-level data if the Reply parameter is inadequate.


PartConstants

Enumerates the values of the Part parameter of the Get method:

Value | Constant | Description
0 | msgContent | Requests the retrieval of the complete message for each message in MsgSet.
1 | msgSize | Requests the size for each message specified in MsgSet.
2 | msgUidl | Requests the message UID label for each message in MsgSet.
3 | msgPreview | Requests the message header followed by 'n' lines, where 'n' is the value of the Preview property.


PopMethodConstants

Enumerates the values of the Method parameter of the Progress event:

Value | Constant | Description
0 | popLogin | Login Method
1 | popLogout | Logout Method
2 | popDelete | Delete Method
3 | popReset | Reset_Method
4 | popGet | Get Method
5 | popCommand | Command Method


PopStatusConstants

Enumerates the values of the Status parameter of the Progress event:

Value | Constant | Description
0 | popOk | Method has completed with a positive status.
1 | popBad | Server has responded with a negative status.
2 | popInfo | Server has supplied information.
3 | popCount | Count property has been updated.
4 | popSize | Message Size property has been updated.
5 | popContent | Indicates intermediate events during the receipt of a mail message. Useful for percentage indication on a status display.
6 | popPreview | Retrieval of a complete message header plus preview lines.
7 | popUid | Retrieval of a message UID label.
8 | popDeleting | A message Delete has been acknowledged.


SMTP Control

Properties Methods Events Constants Example

Use the SMTP Control to send mail to any SMTP server. This control supports popular protocol extensions (ESMTP), provides both Blocking and high performance event-based non-blocking operation, and can be statically placed on a form or dynamically created in virtually any development environment.

Miscellaneous

Product | PowerTCP Mail Tool
Prog ID | Dart.Smtp.1
File | DartMail.dll
Dependencies | DartSock.dll, DartUtil.dll
Threading | Apartment Model
Licensed | Yes


SMTP Control Usage

The SMTP Control provides you with the most functionality in the fewest number of programming steps. This control can operate transparently in the background while the user of your application is doing other tasks, or can be controlled interactively by the user of your application.

Methods perform the following tasks:

  1. Session initiation. Login connects to and determines server capabilities in one step.

  2. Send Mail. Send mails a Message Object, a message file, or a memory resident message to a server.

  3. Session teardown. Logout gracefully terminates a session.

  4. Other Functions. This control supports all the functionality of RFC 821 and several extension RFCs to maximize ease-of-use and flexibility.

Note You can use the convenient QuickSend method to compose and send mail in one step.

Transparent Use

You want your mail transfer to operate in the background with minimal system impact. We recommend you program the mail transfer using non-blocking operation, so the user interface is not affected in any way. The following VB code sample shows how to send a message when the user clicks a button:

Private Sub Command1_Click()

' use non-blocking operation

Smtp1.Timeout = 0

' log in to server

Smtp1.Login "smtp.test.com"

' pick this operation up in the Progress event

End Sub

Private Sub Smtp1_Progress(ByVal Method As DartMailCtl.SmtpMethodConstants, ByVal Status As DartMailCtl.SmtpStatusConstants, ByVal Reply As String, ByVal Count As Long, ByVal Size As Long)

If Status = smtpOk Then

Select Case Method

Case smtpLogin

' logged in, mail message from disk

Smtp1.Send "c:\temp\Test.msg"

Case smtpSend

' mail send is complete, log out

Smtp1.Logout

Case smtpLogout

' operation complete

End Select

End If

End Sub

Interactive Use

For interactive applications, transparency is not as important and blocking operation may be acceptable as shown in the following VB code sample:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Use the Timeout property to establish blocking behavior

Smtp1.Timeout = 1000

' Specify the address of the server to connect to

Smtp1.Login "smtp.test.com"

' Send a message from a file

Smtp1.Send "c:\temp\Test.msg"

' all done, close connection with server

Smtp1.Logout

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Refer to SMTP Control Blocking Sample and SMTP Control Non-Blocking Sample for more information on blocking and non-blocking operation.


SMTP Control Event Sequencing

Events are generated as the server responds to commands. They can be ignored if Timeout is greater than 0 (see Non-Blocking Use of SMTP ), or used to determine the progress of a request. The following table describes the event sequence produced by each SMTP Control method.

Method

Event Sequence Description

Abort

State() signals new value of the State property "tcpClosed"

Command

Progress(Method = smtpCommand, Status = smtpOk, Reply... ) indicates the Command method has successfully completed.

DSN

No event activity.

Login

State() signals new value of State property "tcpConnecting"

State() signals new value of State property "tcpConnected"

Progress(Method = smtpLogin, Status = smtpCapabilities...) indicates that the Capabilities property has been updated.

Progress(Method = smtpLogin, Status = smtpOk...)

Logout

State() signals new value of State property "tcpClosed"

Progress(Method = smtpLogout, Status = smtpOk...) indicates acknowledgment that the Logout method has successfully completed.

QuickSend

State() signals new value of State property "tcpConnecting"

State() signals new value of State property "tcpCconnected"

Progress(Method = smtpQuickSend, Status = smtpCapabilities...) indicates that the Capabilities property has been updated.

Progress(Method = smtpQuickSend, Status = smtpFrom...) indicates sender was accepted by server

Progress(Method = smtpQuickSend, Status = smtpTo...) indicates the recipient was accepted by server.

Progress(Method = smtpQuickSend, Status = smtpSending, Count = Data sent to this point, Size = Message.Size ) indicates mail message data was accepted by server. This event will occur once for each message part.

State() signals new value of State property "tcpClosed"

Progress(Method = smtpQuickSend, Status = smtpOk...) indicates the QuickMail method has successfully completed.

Reset

Progress(Method = smtpReset, Status = smtpOk...) indicates the Reset method has successfully completed.

Send

Progress(Method = smtpSend, Status = smtpFrom...) indicates sender was accepted by server

Progress(Method = smtpSend, Status = smtpTo...) indicates a recipient was accepted by server. This event will occur once for each recipient.

Progress(Method = smtpSend, Status = smtpSending, Count = Data sent to this point, Size = Message.Size) indicating mail message data was accepted by server.

Progress(Method = smtpSend, Status = smtpOk...) indicates the successful completion of the Send method.

Trace

No event activity.


SMTP Control Non-Blocking Sample

If you structure the code so that sequencing is controlled by event code, then you can accomplish message transfer without blocking. This allows PowerTCP to operate relatively independent of your application.

Private Sub Command1_Click()

' Set Timeout to indicate non-blocking operation

Smtp1.Timeout = 0

' Specify the address of the server to connect to

Smtp1.Login "smtp.test.com"

' the Login process will notify us when it is complete via the Progress event

End Sub

Private Sub Smtp1_Progress(ByVal Method As DartMailCtl.SmtpMethodConstants, ByVal Status As DartMailCtl.SmtpStatusConstants, ByVal Reply As String, ByVal Count As Long, ByVal Size As Long)

If Status = smtpOk Then

Select Case Method

Case smtpLogin

' logged in, mail a message from disk

Smtp1.Send "C:\temp\Test.msg"

Case smtpSend

' mail send is complete, log out

Smtp1.Logout

Case smtpLogout

' operation complete

End Select

ElseIf Status = smtpSending Then

' update the progress for the user

Label1.Caption = 100 * Count / Size

End If

End Sub


SMTP Control Blocking Sample

By default, Timeout is a positive value that indicates all methods should wait until completion before returning. This is called blocking and greatly simplifies the sequencing of operations and error recovery. Consider the following VB example:

Private Sub Command1_Click()

' Use the Timeout property to establish blocking operation

Smtp1.Timeout = 1000

' Specify the address of the server to connect to

Smtp1.Login "smtp.test.com"

' Send a message stored in a file

Smtp1.Send "C:\test\Test.msg"

Smtp1.Logout

End Sub

Now, add error handling so the application does not terminate if you experience a communications failure, as shown below:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Use the Timeout property to establish blocking operation

Smtp1.Timeout = 1000

' Specify the address of the server to connect to

Smtp1.Login "smtp.test.com"

' Send a message stored in a file

Smtp1.Send "c:\test\Test.msg"

Smtp1.Logout

Exit Sub

OnError: ' Any error jumps here

' Don't use MsgBox because that interrupts event notification

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Now, display progress for your user. To do this, you need event notification during the message upload. Insert code in the Progress event as shown below:

Private Sub Smtp1_Progress(ByVal Method As DartMailCtl.SmtpMethodConstants, ByVal Status As DartMailCtl.SmtpStatusConstants, ByVal Reply As String, ByVal Count As Long, ByVal Size As Long)

If Status = smtpSending Then

Label1.Caption = 100 * Count / Size

End If

End Sub

Progress information is displayed, but issues remain:

  • During the sending of a message, for single-thread applications, no other work can be done because the thread is trapped in the Send method.

  • You must prevent the user from exiting the application because you cannot allow the user to unload the application while blocked.

  • If the user initiates another activity through the user interface, make sure the user does not affect the mail transfer (by calling another method or capturing the thread for any length of time).


Capabilities Property

Collection of strings that contains the protocol extensions supported by the server. Values are initialized during login.

Syntax

Object.Capabilities

Part | Description
Object | Evaluates to an SMTP Control.

Data Type

DartStrings Object

Remarks

Read-only (but you can remove Strings in the collection).

By default, capabilities supported by the server and the control are automatically used. Removing a capability from the collection disables use of the associated extension. Reactivate the use of the capability by restoring the capability to the collection or restarting the session. The following statement disables use of the "PIPELINING" extension:

Smtp1.Capabilities.Remove("PIPELINING") ' "PIPELINING" is disabled.

DSNTYPE, 8BITMIME, ENHSTATUSCODES, PIPELINING, and SIZE are automatically used if they are advertised by the server. See SMTP Protocol Overview for more information on these extensions.


From Property

If provided, this return address is used for the SMTP envelope instead of the address found in the From header label of the message.

Syntax

Object.From

Part | Description
Object | Evaluates to an SMTP Control.

Data Type

String

Remarks

An envelope identifying the sender and recipients is sent as part of the mail transfer. By default, the sender is extracted from the From header label of the message. This property overrides this default behavior. See Address Formats for more information.


Message Property

Default Message Object to send.

Syntax

Object.Message

Part | Description
Object | Evaluates to an SMTP Control.

Data Type

Message Object

Remarks

The Send method normally encodes this message and sends it.


To Property

If provided, these addresses will be used for the SMTP envelope instead of those found in the To, Cc, and Bcc header labels of the message.

Syntax

Object.To

Part | Description
Object | Evaluates to an SMTP Control.

Data Type

DartStrings

Remarks

An envelope identifying the sender and recipients is sent as part of the mail transfer. By default, the recipients of the message are extracted from the message header labels To, Cc, and Bcc. This property will override this default behavior. Refer to Address Formats for more information.


Command Method

Example

Send any protocol command to the server.

Syntax

Object.Command Command, Reply

Part | Description
Object | Evaluates to an SMTP Control.
Command | String. Contains the command to send.
Reply | String. Location where the reply from the server will be stored. A message would not be returned for this parameter when the Progress event fires, as that information would be available elsewhere.

Remarks

This command allows standard as well as non-standard extension commands to be executed. The reply from the server is copied to the Reply parameter. It is up to you to determine success or failure of the command.

Do not include a trailing CR/LF pair.

Error Codes

The Command method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptProtocol

  • ptTimeout


DSN Method

Set parameters that define the type of Delivery Status Notification that will be requested for subsequent messages.

Syntax

Object.DSN Notify [ , Segment ] [ , EnvelopeId ]

Part | Description
Object | Evaluates to an SMTP Control.
Notify | DsnConstants
Segment | Optional SegmentConstants. Defaults to msgHeader to return the header. If msgMessage, DSN will return the entire message.
EnvelopeId | Optional String. To be included in the return message header. The default is an empty string.

Remarks

If EnvelopeId is provided, the value will be included in any returned messages by the addition of a header to the notification message of the form:

Original-Envelope-ID: <EnvelopeId>

Reserved characters contained in the EnvelopeId string are encoded before transmittal.

Refer to RFC 1891 for additional information about return notifications.

The following example code requests DSN for message delivery success and failure, requests return of the message, and provides an identifying label to aid in processing the return receipt:

Smtp1.DSN dsnSuccessFailure, msgMessage, "bounce-2118"

Error Codes

The DSN method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1

  • ptInvalidParam2


Login Method

Example

Establish a session.

Syntax

Object.Login Server [ , RemotePort ] [ , Username ] [ , Password ]

Part | Description
Object | Evaluates to an SMTP Control.
Server | String. May either be a host name (host.dart.com) or dot address (nnn.nnn.nnn.nnn).
RemotePort | Optional Long. Specifies the port number you wish to connect to. Defaults to the "well-known" port 25.
Username | Optional String. Specifies the server account.
Password | Optional String. Specifies the Password.

Remarks

In most cases, all parameters but Server may be defaulted.

After a successful Login, the supported server extensions are listed in the Capabilities property and will be used when applicable. See the Capabilities property or the SMTP Protocol Overview section for more information regarding SMTP extensions.

See SMTP Control Event Sequencing for event information related to this method and SMTP Control Non-Blocking Sample for information on non-blocking operation.

Error Codes

The Login method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAbort

  • ptAddressInUse

  • ptAddressNotAvailable

  • ptAuthentication (An Invalid Username or Password was specified)

  • ptBlocked

  • ptConnected

  • ptConnectionAborted

  • ptConnectionReset

  • ptConnectionRefused

  • ptHostNotFound

  • ptNetworkDown

  • ptNetworkReset

  • ptNetworkUnreachable

  • ptNoBufferSpace

  • ptNoData

  • ptNotInitialized

  • ptProtocol (A protocol error was encountered)

  • ptTimeout

  • ptTryAgain


Logout Method

End a session.

Syntax

Object.Logout

Part | Description
Object | Evaluates to an SMTP Control.

Remarks

This method gracefully ends a session. If you fail to log out, the server cancels any incomplete mail activity, possibly causing a server fault.

Error Codes

The Logout method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNotConnected

  • ptNotInitialized

  • ptNoBufferSpace

  • ptProtocol (A protocol error was encountered)

  • ptTimeout


QuickSend Method

Build and send a message in one easy step.

Syntax

Object.QuickSend To, From [ , Subject ] [ , Text ] [ , Attachments ] [ , Server ]

Part | Description
Object | Evaluates to an SMTP Control.
To | String. Contains one or more recipient addresses separated by commas.
From | String. Contains the email address of the message originator.
Subject | Optional String. Specifies the Subject of the message.
Text | Optional String. Contains the message text.
Attachments | Optional String. Contains one or more attachment files (separated by semicolons) to be sent with the message.
Server | Optional String. Specifies the name of the server to connect to.

Remarks

If Server is specified, login is attempted before the message is sent, and the session terminates after the message is sent. A ptConnected error is thrown if already logged in.

If Server is not specified, there must an active session and the session persists after the message is sent. This allows multiple messages to be sent without the overhead of logging in and out for each message. A ptNotConnected error is thrown if not already logged in.

This method allows you to send complex messages with just one line of code.

Error Codes

The QuickSend method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAuthentication

  • ptBlocked

  • ptConnected

  • ptConnectionAborted

  • ptConnectionRefused

  • ptConnectionReset

  • ptFile

  • ptHostNotFound

  • ptInvalidParam1

  • ptInvalidParam2

  • ptNetworkDown

  • ptNetworkReset

  • ptNetworkUnreachable

  • ptNoBufferSpace

  • ptNoData

  • ptNotConnected

  • ptNotInitialized

  • ptProtocol

  • ptTimeout

  • ptTryAgain


Reset Method

Recover from an error condition.

Syntax

Object.Reset

Part | Description
Object | Evaluates to an SMTP Control.

Remarks

This method recovers from an error that has left the server unsynchronized with the client.

Error Codes

The Reset method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptNotInitialized

  • ptProtocol (A protocol error was encountered)

  • ptTimeout


Send Method

Send a mail message.

Syntax

Object.Send [ Msg ]

Part | Description
Object | Evaluates to an SMTP Control.
Msg | Optional String or Byte array containing an encoded message, or a String containing the filename of a file containing the message.

Remarks

If the Msg parameter is not specified, the message contained in the Message property is sent.

The recipients of the message are determined by the To, Cc, and Bcc labels in the message header, unless overridden by the To property. Bcc header fields are removed from the message header before sending (Bcc fields are used for the message envelope only).

The sender of the message is determined by the From label in the message header, unless overridden by the From property.

Error Codes

The Send method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptInvalidParam1

  • ptFile

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNoRecipients (A recipient for the message could not be determined)

  • ptNotConnected

  • ptNotInitialized

  • ptProtocol (A protocol error was encountered)

  • ptTimeout


Verify Method

Validate an email address.

Syntax

Value = Object.Verify DnsServers, Address

Part | Description
Object | Object expression that evaluates to a PowerTCP SMTP Control.
DnsServers | Dartstrings collection that specifies a list of DNS servers used to locate the address of the mail server for Address.
Address | String. The mail address to verify
Value | VerifyMethodConstants. The result of the email verification.

Remarks

This blocking method will verify if the domain of the specified address is valid, and that the user is a valid user within the domain.

If the email address is badly formed, the specified domain does not exist, the mail server does not respond, or the user does not exist, a VerifyMethodConstant will be returned designating the nature of the problem. If the address is valid, the VerifyMethodConstant returned will be verifyValid.

If there is no response from the first DNS server in the DnsServers collection after three attempts, the next server will be tried. This will continue until the list of servers is exhausted. If a connection has already been established using the Login method, the Verify method will return with error ptConnect, as this method makes its own connection. Also, if the current thread is blocking, a ptBlocked error will result.

Please note that the performance of this capability is dependent upon the responsiveness of the DNS Servers used and security of the SMTP server. Some servers accept invalid mail and return later. This will cause an address to be falsely evaluated as good. In addition, failure may occur if your machine does not allow incoming traffic on port 113, which is used by mail servers to check port identity of the requesting machine.


Progress Event

Fires when a method has completed, the server has sent a reply, or progress information is available.

Syntax

Private Sub Object_Progress ( Method As SmtpMethodConstants, Status As SmtpStatusConstants, Reply As String, Count As Long, Size As Long )

Part | Description
Object | Evaluates to an SMTP Control.
Method | SmtpMethodConstants. Method that the event pertains to.
Status | SmtpStatusConstants. Status of the method.
Reply | String. Reply associated with the command sent.
Count | Long. Number of bytes of the message sent so far when Status is smtpSending. The value is between 0 and Size.
Size | Long. Size of the message when Status is smtpSending. This value is constant during a transfer.

Remarks

When a method is called, it causes Progress to fire to indicate progress, status, or completion information, such that:

  • Method indicates the method used

  • Status provides success / failure information

  • Reply provides the server reply

  • Count and Size are used to update the progress of a Send or QuickSend operation when Status = smtpSending (at other times these parameters are 0).

Use the Trace method to gather protocol-level data if the Reply parameter is inadequate.

Reply normally begins with one of the following numbers:

Number | Meaning
211 | System status or help reply
214 | Help message (Information on how to use the receiver or the meaning of a particular non-standard command; this reply is useful only to the human user)
220 | <domain> Service ready
221 | <domain> Service closing transmission channel
250 | Requested mail action okay, completed
251 | User not local; will forward to <forward-path>
252 | Cannot VRFY user, but will accept message and attempt delivery
354 | Start mail input; end with <CRLF>.<CRLF>
421 | <domain> Service not available, closing transmission channel (This may be a reply to any command if the service knows it must shut down)
450 | Requested mail action not taken: mailbox unavailable (for example, mailbox busy)
451 | Requested action aborted: local error in processing
452 | Requested action not taken: insufficient system storage
500 | Syntax error, command unrecognized (This may include errors such as command line too long)
501 | Syntax error in parameters or arguments
502 | Command not implemented
503 | Bad sequence of commands
504 | Command parameter not implemented
550 | Requested action not taken: mailbox unavailable (for example, mailbox not found, no access, or command rejected for policy reasons)
551 | User not local; please try <forward-path>
552 | Requested mail action aborted: exceeded storage allocation
553 | Requested action not taken: mailbox name not allowed (for example, mailbox syntax incorrect)
554 | Transaction failed (Or, in the case of a connection-opening response, "No SMTP service here")


DsnConstants

Enumerates values of the Notify parameter of the DSN method:

Value | Constant | Description
0 | dsnNever | Directs the server not to send DSN under any circumstances.
1 | dsnDefault | Directs the server to follow its default policy for DSN.
2 | dsnFailure | Requests DSN for failure of delivery.
3 | dsnSuccess | Requests DSN for successful delivery.
4 | dsnDelay | Requests DSN for delayed delivery when success/failure information is not known.
5 | dsnFailureDelay | Requests DSN for failure or delay of delivery.
6 | dsnSuccessDelay | Requests DSN for success for delay of delivery.
7 | dsnSuccessFailure | Requests DSN for success or failure of delivery.
8 | dsnSuccessFailureDelay | Requests DSN for success, failure, or delay of delivery.


SmtpMethodConstants

Enumerates values of the Method parameter of the Progress event. Indicates the method that initiated the event.

Value | Constant | Description
0 | smtpLogin | Login method
1 | smtpLogout | Logout method
2 | smtpSend | Send method
3 | smtpQuickSend | QuickSend method
4 | smtpReset | Reset method
5 | smtpCommand | Command method


SmtpStatusConstants

Enumerates values of the Status parameter of the Progress event. Provides success / failure / progress information.

Value | Constant | Description
0 | smtpOk | Method has completed with a positive status indicating successful operation.
1 | smtpBad | Server has responded with a negative status indicating an error condition.
2 | smtpFrom | Server has responded positive to "MAIL FROM:" during the execution of the Send or QuickSend method.
3 | smtpTo | Server has responded positive to "RCPT TO:" during the execution of the Send or QuickSend method.
4 | smtpSending | Indicates progress during the transmission of a message. Useful for percentage indication on a status display.
5 | smtpCapabilities | Capabilities is updated.


VerifyMethodConstants

Enumerates the return value of the Verify method.

Value | Constant | Description
0 | verifyValid | No Error (default)
1 | verifyFormat | The format of the Email address was not valid.
2 | verifyDomain | The domain specified in the Email address was not valid.
3 | verifyConnectMailServer | A connection to the mail server specified in the Email address could not be made.
4 | verifyBadUser | The username of the Email address was not valid.


PowerTCP Server Tool

Support Licensing Distribution

Rapidly construct custom server applications. Active connections are maintained in a collection and all events include an object reference so your application can easily use the TCP object pertaining to the event.

Control | Description
FtpServer Control | Build into your application a fully-functioning standalone or custom FTP server
DnsServer Control | Use the DnsServer Control to respond to Domain Name Server requests.
Server Control | Combines a TCP Daemon Control with a collection of TCP Controls for superior "turn-key" server performance
Service Control | Turn your server application into an NT service
TCP Control | Stream management

Supporting Objects

Object | Description
Children Object | Provide a collection of TCP objects that have been dynamically created
DnsRequest Object | Provide access to request details found in the incoming (from the DNS client) datagram.
FtpVariable Object | Store and manage variables
FtpVariables Object | Collection of FtpVariable Objects
Request Object | Obtain information about the current request
Response Object | Manage information sent back to the client
Session Object | Manage information describing a client session
Sessions Object | Manage multiple Session Objects
User Object | Obtain information about the current user and to indicate that a client has been authenticated

Sample Projects

The following sample projects demonstrate how to use the Server Tool:

Sample Project | Description
Character Generator | Uses the Server Control and Service Control to generate a continuous stream of characters. Visual Basic 6.
Discard Server | Uses the Server Control and Service Control to receive data without doing anything else. Visual Basic 6.
Echo Server | Uses the Server Control and Service Control to demonstrate an Echo Server. Visual Basic 6 and Visual C++.
FTP Server | Uses the Server Control, Service Control, and TCP Control to implement an FTP Server. Visual Basic 6.
SMTP Server | Uses the Server Control and Service Control to implement a Mail Server. Visual Basic 6.


Scalability

Operating System

Most server applications should be installed on the "Server" version of NT 4.0 and NT 2000. "Workstation" versions limit the number of pending connections, which can cause "connection refused" errors on the browser side when heavy loads are experienced. This is the only known limitation; therefore, most Servers installed on these systems work well under low and medium loading conditions.

Multi-threaded Use

Like most controls, PowerTCP Server Controls are apartment model threaded. All events fire on the same thread that created the control. Consequently, any processing that takes place within the body of an event, such as the Get event, normally block processing of all other events fired on the same thread. Thus, any lengthy database query made within the body of an event could negatively impact other connections, because those additional connections would not be serviced until the first was completed. Consequently, the design is a single control with asynchronous support.

From within any HTTP event, a new thread can be spawned using MTS or some other mechanism that ultimately responds to the event, while the user thread returns to the WebServer Control to process other requests. The mechanism is accomplished by setting Response.Delay to True, creating an object on a new thread, passing it a reference to the Response Object, and calling Response.Send once the lengthy operation is complete.

Although this approach is less "pure" than having a dedicated thread for each TCP connection, it is useful for servers that anticipate high loading, while maintaining simplicity and speed of operation for developers anticipating medium to light loads.

Application Partitioning – Applies To WebServer Control Only

Besides the single application, multi-threaded approach discussed above, the compiled nature of your web application allows you to partition your application into multiple tasks, each listening on unique ports and operating independent of other applications. For example, suppose you have a number-crunching task that is not often exercised, but when it is it needs to be on it's own thread. You can write a second web application for this task, have it listen on port 81, and link to it whenever it needs to be run. Your main web application never notices because your second application is running in its own task space.


Children Object

The Children Object provides a collection of TCP objects that have been dynamically created. Each object routes events back to the using application via the Server Control event interface. This collection supports automatic iteration.


Item Method

Returns a TCP object from the collection given an index.

Syntax

Value = Object.Item Index

Part | Description
Object | Object expression that evaluates to a Children Object.
Index | Long.
Value | TCP Object (Control)

Remarks

When specifying Index as a Long, its value must be between one and the collection's Count property.

Error Codes

The Item method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptInvalidParam1 (Index is not a Long between 1 and Count or Index is a Name with no match)


FtpServer Control

Properties Methods Events Example

Use the FtpServer Control to build into your application a fully-functioning standalone or custom FTP server. This flexible control provides custom authentication and file system management capabilities yet functions as a powerful FTP server with minimal code.

Miscellaneous

Product | PowerTCP Server Tool
Prog ID | Dart.FtpServer.1
File | DartFtpServer.dll
Dependencies | DartSock.dll, DartServer.dll, DartFtpUtil.dll
Threading | Apartment Model
Licensed | Yes


Count Property

Number of nonsecure TCP connections currently open.

Syntax

Object.Count

Part | Description
Object | Evaluates to a FtpServer Control or SecureFtpServer Control.

Data Type

Long

Remarks

Read-only.

The number of nonsecure client connections currently open may be greater than the number of Session Objects, since a client may have more than one connection to the server at the same time.


LogDirectory Property

Directory for daily log files.

Syntax

Object.LogDirectory

Part | Description
Object | Evaluates to a FtpServer Control or a SecureFtpServer Control.

Data Type

String

Remarks

This design time property defaults to an empty string and controls if and where daily log files are created. If set to an empty string or the specified directory does not exist, logging of requests is disabled. If a valid directory is specified a new log file is created for each day in the specified directory. The file naming convention is as follows:

DARTDDMMYYYY.log

DD | Two digit day.
MM | Two digit month.
YYYY | Four digit year. Y2K-compliant.

An example filename of a log file created on February 13, 2001 would be:

DART13022001.log

The log file format is in the form outlined by the W3C Extended Log File Format. Each entry includes the time, requesting IP address, method, parameter, and response code of the transaction. For example:

19:23:41 192.52.109.240 USER joe 331

means at 7:23pm a client at 192.52.109.240 sent the USER command with a parameter of joe, and the response was 331.


MaxIdleTime Property

Maximum time in minutes a session can be idle before it terminates.

Syntax

Object.MaxIdleTime

Part | Description
Object | Evaluates to a FtpServer Control or a SecureFtpServer Control.

Data Type

Long

Remarks

Inactivity means no data or commands have been sent to the server and no response or data have been sent to the client. When set to 0, sessions never expire. Check the Session Object IdleTime property for the amount of time the session has been idle.


QuitMessage Property

Message sent to the client in response to a QUIT command (when the user logs out).

Syntax

Object.QuitMessage

Part | Description
Object | Evaluates to a FtpServer Control or a SecureFtpServer Control.

Data Type

String

Remarks

If you leave this property blank an empty 221 response is returned to the client.


RestartAllowed Property

Indicates whether users can restart file transfers.

Syntax

Object.RestartAllowed

Part | Description
Object | Evaluates to a FtpServer Control or a SecureFtpServer Control.

Data Type

Boolean

Remarks

When set to True, users can restart file transfers. When set to False, users cannot restart file transfers.


Sessions Property

Collection of active Session Objects.

Syntax

Object.Sessions

Part | Description
Object | Evaluates to a FtpServer Control or a SecureFtpServer Control.

Data Type

Sessions Object

Remarks

Read-only.

Use the MaxIdleTime property to control how long sessions remain active.


Status Property

Text description of the server status. This is the message returned to the client in response to a STAT command.

Syntax

Object.Status

Part | Description
Object | Evaluates to a FtpServer Control or a SecureFtpServer Control.

Data Type

String

Remarks

If you leave this property blank an empty 211 response is returned to the client. This text is general text that is sent to all users that issue the STAT command. The Status event fires when the STAT command is sent by the client also allowing for more user specific status information to be sent in addition to this text.


SystemName Property

System name and type. This is the message returned to the client in response to a SYST command.

Syntax

Object.SystemName

Part | Description
Object | Evaluates to a FtpServer Control or a SecureFtpServer Control.

Data Type

String

Remarks

If you leave this property blank, an empty 215 response is returned to the client.


WelcomeMessage Property

Message returned to the client when the client initially connects.

Syntax

Object.WelcomeMessage

Part | Description
Object | Evaluates to a FtpServer Control or a SecureFtpServer Control.

Data Type

String

Remarks

If you leave this property blank, an empty 220 response is returned to the client.


Pause Method

Stop the server from listening and accepting new connections, while allowing established connections and sessions to persist.

Syntax

Object.Pause

Part | Description
Object | Evaluates to a FtpServer Control or a SecureFtpServer Control.

Remarks

Existing connections can continue making requests. IdleTime continues to increase. Use the Start method to start allowing new connections again. Use the Stop method to stop the server from listening and close all open connections.


Start Method

Start processing FTP requests.

Syntax

Object.Start RootDirectory [ , LocalPort ] [ , LocalAddress ] [ , Backlog ]

Part | Description
Object | Evaluates to a FtpServer Control or a SecureFtpServer Control.
RootDirectory | String. Root directory for the ftp server.
LocalPort | Optional Long between -1 and 65535, inclusive. Specifies the port for accepting connections. Defaults to the well-known FTP Port 21.
LocalAddress | Optional String. The interface address to use in dot notation for communications. Not usually specified.
Backlog | Optional Long. The maximum length to which the queue of pending connections may grow. Defaults to the maximum number allowed.

Remarks

This method directs the server to start accepting and processing FTP requests. Only files contained in root directory for the ftp files system or its subdirectories may be viewed by ftp clients. Access to files above this directory is not allowed and will not be visible. LocalPort specifies the port on which the server should accept (FTP) requests, and defaults to 21 if unspecified.

Error Codes

The Start method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAddressInUse

  • ptFile (RootDirectory Property was not set or does not exist)

  • ptInvalidParam1 (LocalPort is not a valid port number)

  • ptNetworkDown

  • ptNoBufferSpace


Stop Method

Stop the server from accepting new connections and immediately close existing client connections.

Syntax

Object.Stop

Part | Description
Object | Evaluates to a FtpServer Control or a SecureFtpServer Control.

Remarks

This method stops the server from listening and accepting connections. In addition, all existing client connections will be immediately terminated. The LocalPort property is set to 0.

Calling this method does not remove sessions from the Sessions Object. The IdleTime property of existing sessions is not updated while the control is stopped. Use the Remove method or the Clear method to remove all or individual sessions.

Error Codes

The Stop method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptTimeout

  • ptAbort

  • ptNetworkDown

  • ptNotConnected


Append Event

Fires when the client attempts to append to a file (by sending an APPE command).

Syntax

Private Sub Object_Append ( Request As Request, Response As Response )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

Request.Session.User contains all information about the current user. If Request.Session.User is Nothing, then the client has not properly authenticated itself.

Request.Parameters contains a list of all the parameters sent with the command. Typically the first parameter is the file to be retrieved.

If Request.Session.User is set to:

  • Nothing

Response.Status defaults to 530 and Response.StatusText defaults to "Please login with USER and PASS." This indicates that the client has not been properly authorized.

  • A valid User Object and the client has not sent a previous PORT or PASV command

Response.Status will default to 425 and Response.StatusText will default to "Can't build data connection: Connection refused."

  • A valid User Object and the client has sent a previous PORT or PASV command

Response.Status defaults to 150 and Response.StatusText defaults to "Opening <transfermode type> mode data connection for file <filename>". Response.Data points to the local file to store the transferred data.

Response.Status, Response.StatusText, and Response.Data may be changed before returning from this event, and the new information will be returned to the client.

Response.Data may be set to a valid DartStream Object to indicate a file transfer is to be established. A file transfer can only be established if the client sent a PASV or PORT command since the last data transfer. If the client has not met these requirements then a "425 Can't build data connection: Connection refused." is sent to the client. The Response.TransferDown property is ignored in this event. The direction of transfer is always to the server.

The Request.Session property will contain session data for the session that is associated with the client making the request.


ChangeDirectoryUp Event

Fires when the client sends a CDUP command.

Syntax

Private Sub Object_ChangeDirectoryUp ( Request As Request, Response As Response )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

This event fires when the client is trying to move up in the directory structure.

By default the Request.Session.User.CurrentPath property is updated with the correct path. If the user is currently in the directory specified by the RootDirectory parameter of the Start method when this command is sent then the User.CurrentPath remains the same.

Request.Session.User contains all information about the current user. If Request.Session.User is Nothing then the client has not properly authenticated itself.

Request.Parameters contains a list of all the parameters sent with the command. Typically there are no parameters for this command and they will be ignored by default.

If Request.Session.User is set to:

  • Nothing

Response.Status defaults to 530 and Response.StatusText defaults to "Please login with USER and PASS." This indicates that the client has not been properly authorized.

  • A valid User Object

Response.Status will default to 250 and Response.StatusText will default to "CWD command successful."

Response.Status and Response.StatusText may be changed before returning from this event, and the new information will be returned to the client. In this event the Response.Data property is ignored and will not be used.

The Request.Session property will contain session data for the session that is associated with the client making the request.


ChangeWorkingDirectory Event

Fires when the client sends a CWD command.

Syntax

Private Sub Object_ChangeWorkingDirectory ( Request As Request, Response As Response )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

This event fires when the client is trying to move into a new directory.

By default the Request.Session.User.CurrentPath property will be updated with the correct path. If the path specified by the user does not exist, then User.CurrentPath will not change.

Request.Session.User contains all information about the current user. If Request.Session.User is Nothing then the client has not properly authenticated itself.

Request.Parameters contains a list of all the parameters sent with the command. Typically the first parameter is the directory name the client is trying to change to.

If Request.Session.User is set to:

  • Nothing

Response.Status defaults to 530 and Response.StatusText defaults to "Please login with USER and PASS." This indicates that the client has not been properly authorized.

  • A valid User Object and the requested directory does not exist

Response.Status will default to 550 and Response.StatusText will default to "<directory>: No such file or directory."

  • A valid User Object and the requested directory does exist

Response.Status defaults to 250 and Response.StatusText defaults to "CWD command successful."

Response.Status and Response.StatusText may be changed before returning from this event, and the new information will be returned to the client. In this event the Response.Data property is ignored and will not be used.

The Request.Session property will contain session data for the session that is associated with the client making the request.


Command Event

Fires when the client sends a custom command.

Syntax

Private Sub Object_Command ( Cmd As String, Request As Request, Response As Response )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Cmd | String. Contains the custom command.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

This event fires when a command other than the following supported list is sent from the client:

USER PASS CWD

CDUP SMNT QUIT

REIN PORT PASV

TYPE STRU MODE

RETR STOR STOU

APPE ALLO REST

RNFR RNTO ABOR

DELE RMD MKD

PWD LIST NLST

SITE SYST STAT

HELP NOOP SIZE

Command holds the custom command that was sent to the server.

Request.Session.User contains all information about the current user. If Request.Session.User is Nothing then the client has not properly authenticated itself.

Request.Parameters contains a list of all the parameters sent with the command.

If Request.Session.User is set to:

  • Nothing

Response.Status defaults to 530 and Response.StatusText defaults to "Please login with USER and PASS." This indicates that the client has not been properly authorized.

  • A valid User Object

Response.Status will default to 500 and Response.StatusText will default to "<Command>: command not understood" indicating that the command is not a valid command.

  • A valid User Object and the requested directory does exist

Response.Status defaults to 250 and Response.StatusText defaults to "CWD command successful."

In both cases Response.Data will default to Nothing.

Response.Status, Response.StatusText, and Response.Data may be changed before returning from this event, and the new information will be returned to the client.

Response.Data may be set to a valid DartStream Object to indicate a file transfer is to established. The Response.TransferDown property will determine the direction of the file transfer. A file transfer can only be established if the client sent a PASV or PORT command since the last data transfer. If the client has not met these requirements then a "425 Can't build data connection: Connection refused." will be sent to the client.

The Request.Session property will contain session data for the session that is associated with the client making the request.


Delete Event

Fires when the client sends a DELE command.

Syntax

Private Sub Object_Delete ( Request As Request, Response As Response )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

This event fires when the client attempts to delete a file from the server.

If the file exists the file is not deleted until returning from this event. To prevent the file from being automatically deleted change the Response.Status property to an error code.

Request.Session.User contains all information about the current user. If Request.Session.User is Nothing then the client has not properly authenticated itself.

Request.Parameters contains a list of all the parameters sent with the command. Typically the first parameter is the name of the file to be deleted.

If Request.Session.User is set to:

  • Nothing

No files are deleted and Response.Status defaults to 530 and Response.StatusText defaults to "Please login with USER and PASS." This indicates that the client has not been properly authorized.

  • A valid User Object and the requested file does not exist

Response.Status will default to 550 and Response.StatusText will default to "<filename>: No such file or directory" and no files will be deleted.

  • A valid User Object and the requested file does exist

Response.Status defaults to 250 and Response.StatusText defaults to "DELE command successful."

Response.Status and Response.StatusText may be changed before returning from this event, and the new information will be returned to the client. In this event Response.Data is ignored and will not be used.

The Request.Session property will contain session data for the session that is associated with the client making the request.


Error Event

Fires whenever an error condition occurs.

Syntax

Private Sub Object_Error ( [ Index As Integer , ] Session As Session, Number As ErrorConstants, Description As String )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Index | Integer. Array index if the object is part of an array.
Session | Session Object associated with the event.
Number | ErrorConstants value.
Description | String. ErrorConstants description.

Remarks

See the appropriate method and property description for a list of errors that may be generated by each.

It is possible for an error to occur that is not associated with a session. In this case, Session will not reference an existing object.


Help Event

Fires when the client sends the HELP command.

Syntax

Private Sub Object_Help ( Request As Request, Response As Response )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

This event fires when the client is requesting help.

Request.Session.User contains all information about the current user. If Request.Session.User is Nothing then the client has not properly authenticated itself.

Request.Parameters contains a list of all the parameters sent with the command. The default is to ignore all parameters.

If Request.Session.User is set to:

  • Nothing

Response.Status defaults to 530 and Response.StatusText defaults to "Please login with USER and PASS" indicating that the client has not been properly authorized.

  • A valid User Object

Response.Status will default to 214 and Response.StatusText will default to:

The following commands are recognized. |  |  |  |  |
USER | PASS | CWD | CDUP | SMNT | QUIT
REIN | PORT | PASV | TYPE | STRU | MODE
RETR | STOR | STOU | APPE | ALLO | REST
RNFR | RNTO | ABOR | DELE | RMD | MKD
PWD | LIST | NLST | SITE | SYST | STAT
HELP | NOOP | SIZE |  |  |
Help command successful. |  |  |  |  |

Response.Status and Response.StatusText may be changed before returning from this event, and the new information will be returned to the client. In this event Response.Data is ignored and will not be used.

The Request.Session property will contain session data for the session that is associated with the client making the request.


List Event

Fires when the client sends a LIST command.

Syntax

Private Sub Object_List ( Request As Request, Response As Response )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

This event fires when the client is requesting a directory listing.

Request.Session.User contains all information about the current user. If Request.Session.User is Nothing then the client has not properly authenticated itself.

Request.Parameters contains a list of all the parameters sent with the command. Typically there are no parameters or the first parameter is the file or directory to list.

If Request.Session.User is set to:

  • Nothing

Response.Status defaults to 530 and Response.StatusText defaults to "Please login with USER and PASS." This indicates that the client has not been properly authorized.

  • A valid User Object and the client has not sent a previous PORT or PASV command

Response.Status will default to 425 and Response.StatusText will default to "Can't build data connection: Connection refused"

  • A valid User Object and the client has sent a previous PORT or PASV command and the specified directory or file does not exist

Response.Status defaults to 550 and Response.StatusText defaults to "<file or directory>: No such file or directory."

  • A valid User Object and the client has sent a previous PORT or PASV command and the specified directory or file does exist

Response.Status defaults to 150 and Response.StatusText defaults to "Opening <transfermode type> mode data connection for file list" and Response.Data will be populated with a UNIX-style directory listing.

Response.Status, Response.StatusText, and Response.Data may be changed before returning from this event, and the new information will be returned to the client.

Response.Data may be set to a valid DartStream Object to indicate a file transfer is to established. The Response.TransferDown property will determine the direction of the file transfer. A file transfer can only be established if the client sent a PASV or PORT command since the last data transfer. If the client has not met these requirements then a "425 Can't build data connection: Connection refused." will be sent to the client.

The Request.Session property will contain session data for the session that is associated with the client making the request.


Login Event

Fires when the client attempts to log into the server.

Syntax

Private Sub Object_Login ( Request As Request, Response As Response )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

This event fires as a result of the client sending both a USER command and a PASS command in sequence.

Request.User.Name contains the username sent with the USER command and Request.User.Password contains the password sent with the PASS command.

Request.Parameters is empty for this event and should be ignored.

Response.Status defaults to 230 and Response.StatusText defaults to "User <username> logged in."

To reject a user from logging in set the Request.Session.User property to Nothing. Upon returning from the event the server will send the client a "530 Login incorrect" response unless another error code is indicated by the user by changing Response.Status.

Response.Status and Response.StatusText may be changed before returning from this event, and the new information will be returned to the client. In this event the Response.Data property is ignored and will not be used.

The Request.Session property will contain session data for the session that is associated with the client making the request.


Logout Event

Fires when the client sends the QUIT command.

Syntax

Private Sub Object_Logout ( Request As Request, Response As Response )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

This event fires when the client is attempting to logout.

Request.Session.User contains all information about the current user. If Request.Session.User is Nothing then the client has not properly authenticated itself.

Request.Parameters contains a list of all the parameters sent with the command. Typically there are no parameters and by default they are ignored.

If Request.Session.User is set to:

  • Nothing

Response.Status defaults to 530 and Response.StatusText defaults to "Please login with USER and PASS." This indicates that the client has not been properly authorized.

  • A valid User Object

Response.Status will default to 221 and Response.StatusText defaults to the text set in the QuitMessage property.

Upon returning from this event the response is sent and the connection is closed regardless of the response.

Response.Status and Response.StatusText may be changed before returning from this event, and the new information will be returned to the client. In this event Response.Data is ignored and will not be used.

The Request.Session property will contain session data for the session that is associated with the client making the request.


MakeDirectory Event

Fires when the client sends a MKD command.

Syntax

Private Sub Object_MakeDirectory ( Request As Request, Response As Response )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

This events fires when the client is attempting to create a new directory on the server. The directory is not actually created until this event returns. To prevent the directory from being created set Response.Status to an error code.

Request.Session.User contains all information about the current user. If Request.Session.User is Nothing then the client has not properly authenticated itself.

Request.Parameters contains a list of all the parameters sent with the command. Typically the first parameter is the name of the directory to create.

If Request.Session.User is set to:

  • Nothing

No files are deleted and Response.Status defaults to 530 and Response.StatusText defaults to "Please login with USER and PASS." This indicates that the client has not been properly authorized.

  • A valid User Object

Response.Status will default to 257 and Response.StatusText will default to "<dirname> new directory created."

Response.Status and Response.StatusText may be changed before returning from this event, and the new information will be returned to the client. In this event Response.Data is ignored and will not be used.

The Request.Session property will contain session data for the session that is associated with the client making the request.


NameList Event

Fires when the client sends a NLST command.

Syntax

Private Sub Object_NameList ( Request As Request, Response As Response )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

This event fires when the client is requesting a directory listing.

Request.Session.User contains all information about the current user. If Request.Session.User is Nothing then the client has not properly authenticated itself.

Request.Parameters contains a list of all the parameters sent with the command. Typically there are no parameters or the first parameter is the file or directory to list.

If Request.Session.User is set to:

  • Nothing

Response.Status defaults to 530 and Response.StatusText defaults to "Please login with USER and PASS." This indicates that the client has not been properly authorized.

  • A valid User Object and the client has not sent a previous PORT or PASV command

Response.Status will default to 425 and Response.StatusText will default to "Can't build data connection: Connection refused"

  • A valid User Object and the client has sent a previous PORT or PASV command and the specified directory or file does not exist

Response.Status defaults to 550 and Response.StatusText defaults to "<file or directory>: No such file or directory."

  • A valid User Object and the client has sent a previous PORT or PASV command and the specified directory or file does exist

Response.Status defaults to 150 and Response.StatusText defaults to "Opening <transfermode type> mode data connection for file list" and Response.Data will be populated with a non-detailed directory listing.

Response.Status, Response.StatusText, and Response.Data may be changed before returning from this event, and the new information will be returned to the client.

Response.Data may be set to a valid DartStream Object to indicate a file transfer is to established. The Response.TransferDown property will determine the direction of the file transfer. A file transfer can only be established if the client sent a PASV or PORT command since the last data transfer. If the client has not met these requirements then a "425 Can't build data connection: Connection refused." will be sent to the client.

The Request.Session property will contain session data for the session that is associated with the client making the request.


RemoveDirectory Event

Fires when the client sends a RMD command.

Syntax

Private Sub Object_RemoveDirectory ( Request As Request, Response As Response )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

This events fires when the client is attempting to remove a directory on the server. The directory is not actually removed until the event returns. To prevent the directory from being removed set Response.Status to an error code.

Request.Session.User contains all information about the current user. If Request.Session.User is Nothing then the client has not properly authenticated itself.

Request.Parameters contains a list of all the parameters sent with the command. Typically the first parameter is the name of the directory to remove.

If Request.Session.User is set to:

  • Nothing

No files are deleted and Response.Status defaults to 530 and Response.StatusText defaults to "Please login with USER and PASS." This indicates that the client has not been properly authorized.

  • A valid User Object and the directory does not exist

Response.Status will default to 550 and Response.StatusText will default to "<dirname>: No such file or directory"

  • A valid User Object and the directory does exist

Response.Status defaults to 250 and Response.StatusText defaults to "RMD command successful."

Response.Status and Response.StatusText may be changed before returning from this event, and the new information will be returned to the client. In this event Response.Data is ignored and will not be used.

The Request.Session property will contain session data for the session that is associated with the client making the request.


Rename Event

Fires when the client attempts to rename a file.

Syntax

Private Sub Object_Rename ( Request As Request, Response As Response )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

This event fires as a result of the client sending both a RNFR command and a RNTO command in sequence.

The file is not actually renamed until returning from this event. To prevent the file from being renamed set Response.Status to an error code.

Request.Session.User contains all information about the current user. If Request.Session.User is Nothing then the client has not properly authenticated itself.

Request.Parameters is empty for this event and should be ignored.

If Request.Session.User is set to:

  • Nothing

No files are deleted and Response.Status defaults to 530 and Response.StatusText defaults to "Please login with USER and PASS." This indicates that the client has not been properly authorized.

  • A valid User Object and the file does not exist

Response.Status will default to 550 and Response.StatusText will default to "<dirname>: No such file or directory"

  • A valid User Object and the file does exist

Response.Status defaults to 250 and Response.StatusText defaults to "RNTO command successful."

Response.Status and Response.StatusText may be changed before returning from this event, and the new information will be returned to the client. In this event Response.Data is ignored and will not be used.

The Request.Session property will contain session data for the session that is associated with the client making the request.


Retrieve Event

Fires when the client attempts to retrieve a file.

Syntax

Private Sub Object_Retrieve ( Request As Request, Response As Response )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

This event fires when the client sends a RETR command.

Request.Session.User contains all information about the current user. If Request.Session.User is Nothing then the client has not properly authenticated itself.

Request.Parameters contains a list of all the parameters sent with the command. Typically the first parameter is the file to be retrieved.

If Request.Session.User is set to:

  • Nothing

Response.Status defaults to 530 and Response.StatusText defaults to "Please login with USER and PASS." This indicates that the client has not been properly authorized.

  • A valid User object and the client has not sent a previous PORT or PASV command

Response.Status will default to 425 and Response.StatusText will default to "Can't build data connection: Connection refused"

  • A valid User object and the client has sent a previous PORT or PASV command and the specified file does not exist

Response.Status defaults to 550 and Response.StatusText defaults to "<file or directory>: No such file or directory."

  • A valid User object and the client has sent a previous PORT or PASV command and the specified directory or file does exist

Response.Status defaults to 150 and Response.StatusText defaults to "Opening <transfermode type> mode data connection for file <filename>" and Response.Data will be populated with the local file.

Response.Status, Response.StatusText, and Response.Data may be changed before returning from this event, and the new information will be returned to the client.

Response.Data may be set to a valid DartStream Object to indicate a file transfer is to established. A file transfer can only be established if the client sent a PASV or PORT command since the last data transfer. If the client has not met these requirements then a "425 Can't build data connection: Connection refused." will be sent to the client. The Response.TransferDown property is ignored in this event. The direction of transfer is always to the client.

The Request.Session property will contain session data for the session that is associated with the client making the request.


SessionEnd Event

Fires just before the session is terminated.

Syntax

Private Sub Object_SessionEnd ( Session As Session )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Session | Session Object about to be destroyed.

Remarks

This event fires when Session.IdleTime exceeds the MaxIdleTime property or when the client logs out or terminates the connection. The object will remain in the Sessions Collection until returning from this event. If the session is being terminated due to timeout this gives you the opportunity to reset Session.IdleTime to a new value, such as 0, to prevent destruction of the object.


SessionInit Event

Fires when the client first connects to the server.

Syntax

Private Sub Object_SessionInit ( Session As Session )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Session | Session Object associated with the client.

Remarks

A new session is created each time a client connects. Use this event to initialize session data.


Site Event

Fires when the client sends the SITE command.

Syntax

Private Sub Object_Site ( Request As Request, Response As Response )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

This event fires when the client is sending a site-specific command. This is another way to support custom commands.

Request.Session.User contains all information about the current user. If Request.Session.User is Nothing then the client has not properly authenticated itself.

Request.Parameters contains a list of all the parameters sent with the command. By default they are ignored.

If Request.Session.User is set to:

  • Nothing

Response.Status defaults to 530 and Response.StatusText defaults to "Please login with USER and PASS." This indicates that the client has not been properly authorized.

  • A valid User object

Response.Status will default to 500 and Response.StatusText will default to "SITE: command not understood."

Response.Status, Response.StatusText, and Response.Data may be changed before returning from this event, and the new information will be returned to the client.

Response.Data may be set to a valid DartStream Object to indicate a file transfer is to established. The Response.TransferDown property will determine the direction of the file transfer. A file transfer can only be established if the client sent a PASV or PORT command since the last data transfer. If the client has not met these requirements then a "425 Can't build data connection: Connection refused." will be sent to the client.

The Request.Session property will contain session data for the session that is associated with the client making the request.


Status Event

Fires when the client sends the STAT command.

Syntax

Private Sub Object_Status ( Request As Request, Response As Response )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

The event fires when the client is requesting status information.

Request.Session.User contains all information about the current user. If Request.Session.User is Nothing then the client has not properly authenticated itself.

Request.Parameters contains a list of all the parameters sent with the command. By default they are ignored.

If Request.Session.User is set to:

  • Nothing

Response.Status defaults to 530 and Response.StatusText defaults to "Please login with USER and PASS." This indicates that the client has not been properly authorized.

  • A valid User object

Response.Status will default to 211 and Response.StatusText will default the text specified by the Status Property.

Response.Status and Response.StatusText may be changed before returning from this event, and the new information will be returned to the client. In this event Response.Data is ignored and will not be used.

The Request.Session property will contain session data for the session that is associated with the client making the request.


Store Event

Fires when the client attempts to store a file.

Syntax

Private Sub Object_Store ( Request As Request, Response As Response, Unique As Boolean )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.
Unique | Boolean. Indicates a Store or a Unique Store.

Remarks

This event fires when the client sends a STOR or the STOU command.

Request.Session.User contains all information about the current user. If Request.Session.User is Nothing then the client has not properly authenticated itself.

Request.Parameters contains a list of all the parameters sent with the command. Typically the first parameter is the file to be retrieved.

If Unique is True then the STOU command was sent from the client. The client expects that the file being store will have a unique name, meaning that if a file exists with that name then the filename will be changed to be unique. If Unique is False then the STOR command was sent. The client doesn't care if a file already exists with that name and the file should be overwritten.

If Request.Session.User is set to:

  • Nothing

Response.Status defaults to 530 and Response.StatusText defaults to "Please login with USER and PASS." This indicates that the client has not been properly authorized.

  • A valid User object and the client has not sent a previous PORT or PASV command

Response.Status will default to 425 and Response.StatusText will default to "Can't build data connection: Connection refused"

  • A valid User object and the client has sent a previous PORT or PASV command

Response.Status defaults to 150 and Response.StatusText defaults to "Opening <transfermode type> mode data connection for file <filename>". Response.Data will point to the local file to store the transferred data.

Response.Status, Response.StatusText, and Response.Data may be changed before returning from this event, and the new information will be returned to the client.

Response.Data may be set to a valid DartStream Object to indicate a file transfer is to established. A file transfer can only be established if the client sent a PASV or PORT command since the last data transfer. If the client has not met these requirements then a "425 Can't build data connection: Connection refused." will be sent to the client. The Response.TransferDown property is ignored in this event. The direction of transfer is always to the server.

The Request.Session property will contain session data for the session that is associated with the client making the request.


StructureMount Event

Fires when the client sends the SMNT command.

Syntax

Private Sub Object_StructureMount ( Request As Request, Response As Response )

Part | Description
Object | Evaluates to an FtpServer Control or a SecureFtpServer Control.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

This event fires when the client is attempting mount a new file system. This is typically not supported.

Request.Session.User contains all information about the current user. If Request.Session.User is Nothing then the client has not properly authenticated itself.

Request.Parameters contains a list of all the parameters sent with the command. By default they are ignored.

If Request.Session.User is set to:

  • Nothing

Response.Status defaults to 530 and Response.StatusText defaults to "Please login with USER and PASS." This indicates that the client has not been properly authorized.

  • A valid User object

Response.Status will default to 500 and Response.StatusText will default to "SMNT: command not understood."

Response.Status and Response.StatusText may be changed before returning from this event, and the new information will be returned to the client. In this event Response.Data is ignored and will not be used.

The Request.Session property will contain session data for the session that is associated with the client making the request.


DnsServer Control

DnsServer Control (beta version)

Properties Methods Events Constants

Use the DnsServer Control to respond to Domain Name Server requests. The GetAddress event fires when a host name arrives and the dot address(es) is requested. The GetName event fires when a dot address arrives and the host name(s) is requested (reverse lookup). The GetMailServer event fires when an email address arrives and the host name and address is requested.

Miscellaneous

Product | PowerTCP Server Tool
Prog ID | Dart.DnsServer.1
File | DartDnsServer.dll
Dependencies | DartSock.dll
Threading | Apartment Model
Licensed | Yes


ClientException Property

ClientException is used only in the GetAddress, GetName, and GetMailServer events. After the event is fired, the DnsServer Control will expect this property to be set if you wish to return an error condition to the client. The default value is dnsOk.

Syntax

Object.ClientException

Part | Description
Object | Evaluates to a DnsServer Control.

Data Type

DnsClientExceptionConstants

Remarks

Write-only.

When a DNS client sends a query to request a response from the DnsServer Control, the server may want to respond with an exception condition. The ClientException is used in such a case. When a DNS server returns a DNS response message back to the client it sets a flag (often referred to as an RCODE) in the header of the message explaining the result of the query.

The property should be set if a DNS server error occurs while trying to receive names, addresses, or mail servers from either your local database or another DNS server. Since the default is dnsOk there is no need to set the ClientException if the response is normal.

After the event executes, the value of the ClientException property is checked. If the property equates to dnsOk, the DnsServer Control will supply the information requested back to the DNS client. If ClientException is not dnsOk, the DnsServer Control will send the DNS response message back with the appropriate error. If ClientException is dnsOk, and no input was supplied (i.e. the address(es) and/or name(s) are empty) to return to the DNS client, the DnsServer Control can not determine the intent of the application and will send a response message back to the client equating to dnsServerFailure.

Refer to RFC 1035 for more details on DNS.


LocalAddress Property

For the following controls (FTP Control, SecureFtp Control, SecureTcp Control, TCP Control, Telnet Control), when the State property is tcpConnected, LocalAddress returns the address of the local host in dot notation (for example, nnn.nnn.nnn.nnn). When not connected, it returns an empty string.

For the following controls (Daemon Control, FtpServer Control, SecureFtpServer Control, SecureServer Control, Server Control, WebServer Control), LocalAddress returns the address in use while the Daemon is active and an empty string when the Daemon socket is closed.

For the DnsServer Control, Agent Control, Manager Control, and UDP Control, LocalAddress returns the address in use while the socket is active and an empty string when the UDP socket is closed.

Syntax

Object.LocalAddress

Part | Description
Object | Evaluates to a PowerTCP control.

Data Type

String

Remarks

Read-only.

The LocalPort property identifies the corresponding local port in use. The LocalAddress, LocalPort, RemoteAddress, and RemotePort properties uniquely define every TCP connection on the Internet.


LocalPort Property

For the following controls (FTP Control, SecureFtp Control, SecureTcp Control, TCP Control, Telnet Control), when the State property is tcpConnected, LocalPort returns the port number that the socket is bound to. When not connected, it returns 0.

For the following controls (Daemon Control, FtpServer Control, SecureFtpServer Control, SecureServer Control, Server Control, WebServer Control), LocalPort returns the port number in use while the Daemon is active and 0 when the Daemon is closed.

For the DnsServer Control, Agent Control, Manager Control, and UDP Control, LocalPort returns the port number in use while the socket is active and 0 when the socket is closed. When the Protocol property of the UDP Control is not ptUdp, LocalPort returns 0.

Syntax

Object.LocalPort

Part | Description
Object | Evaluates to a PowerTCP control.

Data Type

Long

Remarks

Read-only.

When active, values are between 1 and 65,535. The LocalAddress, LocalPort, RemoteAddress, and RemotePort properties uniquely define every TCP connection on the Internet.


Timeout Property

Controls the blocking behavior of methods that can be used in blocking and non-blocking ways.

Syntax

Object.Timeout

Part | Description
Object | Evaluates to a PowerTCP Object.

Data Type

Long

Remarks

The default value is 30000 (30 seconds) for all controls except the Daemon Control, which defaults to 0 (non-blocking). This is a design-time property.

Most users will start using blocking operation. The developer's decision to use blocking (Timeout > 0) or non-blocking (Timeout = 0) operation is important; these controls were designed to consistently support both methods of operation.

When set to a positive number of milliseconds, methods block while waiting for the operation to complete. The Blocked property indicates this state. For example, if the Connect method is used with a Timeout of 30000, then the method only returns without error if the connection is established within 30 seconds. This is the easiest design to implement, but not the most robust. If the user attempts to initiate a different method while the Blocked property is True, an error is generated. Also, if the user attempts to close the application while the Blocked property is True, abnormal program termination may result.

When set to 0, no method blocks. It is up to the application to sense the success or failure of the operation by putting code in the related event. For example, if the Connect method is used with a Timeout of 0, then the application can test for the value of the State property from within the State event. This is the most efficient technique, as no idle loops are used to capture the thread of execution waiting for an event to occur. This is also the safest way to use PowerTCP because non-blocking use allows PowerTCP to unload gracefully under any condition.

The novice will probably use blocking operation first because this is the easiest way to immediately use the product. With no explicit error handling enabled (for example, the VB OnError statement), methods return errors into the environment and program execution stops. Once you add error-handling code, most applications will work satisfactorily. While the thread is captured in the method, an idle loop processes Windows messages and few side effects will ever be noted. There are some limits, however, that you should be aware of:

  • The only way to abort a blocking method is to call the Abort method off a Timer or some user interface event.

  • With the exception of the Abort method, the developer can only be in one method at a time (this protects your program from reentrancy problems).

  • If the user closes the application while PowerTCP is blocking, the blocking method attempts to return when this is sensed, but a general protection fault may still be experienced (because the application is being terminated while PowerTCP is in an idle loop).

Non-blocking operations are more fault-tolerant. Set the Timeout property to 0 (at design time or at run time), initiate methods as desired, and insert most of your code in the appropriate event. This eliminates problems associated with reentrancy, users performing unanticipated actions in your application, and error recovery.


Abort Method

Abort any blocking method and release all system resources.

Syntax

Object.Abort

Part | Description
Object | Evaluates to a PowerTCP control.

Remarks

Use this method at any time to abruptly release all resources. The State property is tcpClosed when this method returns.

Destruction of the control automatically uses this method to release all resources.

If a blocking method is executing, a ptAbort or httpAbort error is returned (which will throw an error exception).

Note: For TCP-based controls, the Abort method performs a "hard close", with a socket LINGER option time of 0.

CAUTION Use the Close method in most cases, as buffers are cleared and communications terminate gracefully. Use the Abort method only when the application in abruptly terminated while a blocking method is executing or under any other unusual circumstances.


Close Method

Release system resources.

Syntax

Object.Close

Part | Description
Object | Object expression that evaluates to a DnsServer Control, Agent Control, Manager Control, or UDP Control.

Remarks

If you specify a Timeout, this method blocks while attempting to send any queued packets. After all queued packets have been sent (or the Timeout period has expired), the socket and all system resources are released. If no Timeout is specified, then all queued packets and system resources are immediately released.

If Blocked and you wish to cancel the method and release resources, use the Abort method. Using Close when another method is blocking results in a ptBlocked error.

Error Codes

The Close method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked (the Blocked property is True)


Open Method

Allocate a socket for sending and receiving datagrams.

Syntax

Object.Open [ LocalPort ] [ , LocalAddress ]

Part | Description
Object | Object expression that evaluates to a PowerTCP control.
LocalPort | Optional Long. Specifies the port desired.
LocalAddress | Optional String. Specifies the address interface desired.

Remarks

LocalPort defaults to 0, which indicates to the system that it should assign an unused (ephemeral) port.

If Object is an SNMP Agent control, you will normally use the well-known port 161. If this port is not used, then managers must be configured to use the port you specify.

If Object is an SNMP Manager control, you can use the well-known port 162 (so a single port can be used for both normal messaging and traps). If 0 is used, then you will not be able to receive traps (because agent applications will not normally know what port to send them to).

If Object is a DnsServer Control, and a value is not specified, it will default to 53, the “well-known” DNS server port.

Upon success, the address used can be read from the LocalAddress property and the port used can be read from the LocalPort property.

Error Codes

The Open method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAddressInUse

  • ptInvalidParam1 (LocalPort is not between 0 and 65535, inclusive)

  • ptInvalidParam2 (LocalAddress is not a valid address string in dot notation, for example, "204.7.222.2")

  • ptNetworkDown

  • ptNoBufferSpace

  • ptNotInitialized


Trace Method

Start or stop the accumulation of trace or debug data. Once started, this method accumulates data until it is turned off.

This method provides a convenient mechanism for viewing all data being sent and received over the connection and can be used to troubleshoot host interoperability issues and expose protocol communications.

Syntax

Object.Trace [ Result ] [ , Send ] [ , Receive ] [ , SendPrompt ] [ , ReceivePrompt ]

Part | Description
Object | Object expression that evaluates to a PowerTCP control.
Result | Optional String. An undimensioned string dynamically expanded to contain trace data or a filename that is used to store all trace data. If not provided or a Null value, then trace data is no longer stored.
Send | Optional Boolean. Defaults to False. A True value indicates that sent data should be traced.
Receive | Optional Boolean. Defaults to False. A True value indicates that received data should be traced.
SendPrompt | Optional String. Prompt to precede sent data.
ReceivePrompt | Optional String. Prompt to precede received data.

Remarks

ReceivePrompt and SendPrompt allow the application to specify what delimiters separate and label data being captured.


Error Event

Fires when an error condition occurs.

Syntax

Private Sub Object_Error ( [ Index As Integer , ] Number As ErrorConstants, Description As String )

Private Sub Object_Error ( [ Index As Integer , ] Child As Tcp, Number As ErrorConstants, Description As String )

Private Sub Object_Error ( [ Index As Integer , ] Child As SecureTcp, Number As ErrorConstants, Description As String )

Part | Description
Object | Evaluates to one of the following controls: DnsServer Control, Agent Control, Daemon Control, DNS Control, FTP Control, IMAP Control, Manager Control, Ping Control, POP Control, SecureFtp Control, SecurePop Control, SecureServer Control, SecureTcp Control, Server Control, TCP Control, Telnet Control, UDP Control.
Index | Integer. Array index if the object is part of an array.
Child | Object reporting the error. Applies only to the Server Control and the SecureServer Control.
Number | ErrorConstants value.
Description | String. ErrorConstants description.

Remarks

Some environments, such as IIS Active Server Pages, do not support event handling. In this case the application must rely on blocking and the Error object that is returned to the container when an error condition occurs.

Note See the appropriate method and property description for a list of errors that may be generated.


GetAddress Event

Fires when a DNS type “A” request has been received.

Syntax

Private Sub Object_GetAddress ( [ Index As Integer , ] ByVal Name As String, Addresses As DartStrings , OwnerName As String, ByVal Request As DnsRequest)

Part | Description
Object | Evaluates to a DnsServer Control.
Index | Integer. Array index if the object is part of an array.
Name | String. Hostname received for which a dot address is being requested.
Addresses | DartStrings (by reference). Addresses.Count is 0 when this event fires. Add one or more IP addresses to a valid dot (of the form x.x.x.x : where 0 <= x <= 255), to this collection of Strings, and they will be formatted and sent to the client requesting the address look-up.
OwnerName | String. Provides the name of the DNS server that contains the database where the requested information originated.
Request | Object. Holds additional information.

Remarks

If no Addresess are specified, then , the ClientException property will be set by the DnsServer Control to dnsServerFailure.

If OwnerName is not set to a valid name the ClientException property will be set by the DnsServer Control to dnsServerFailure.

If the Address(es) specified does not evaluate to a valid IP dot address syntax, then the Error Event will fire with a ptFormatError specified as the error number and no response will be generated.

If a DNS error occurs, the ClientException property should be set to describe the error.


GetMailServer Event

Fires when a DNS type “MX” request has been received.

Syntax

Private Sub Object_GetMailServer ( [ Index As Integer , ] ByVal EmailAddress As String, Addresses As DartStrings, Names As DartStrings , OwnerName As String, Preference As Short, ByVal Request As DnsRequest)

Part | Description
Object | Evaluates to a DnsServer Control.
Index | Integer. Array index if the object is part of an array.
EmailAddress | String. The email address (of the form name@domain.com) for which the address and name of the email server(s) is requested.
Addresses | DartStrings (by reference). Addresses.Count is 0 when this event fires. Add one or more address (in dot notation) to this collection of Strings, and they will be formatted and sent to the client requesting the mail server look-up.
Names | DartStrings (by reference). Names.Count is 0 when this event fires. Add one or more hostnames to this collection of Strings, and they will be formatted and sent to the client requesting the mail server look-up.
OwnerName | String. Provides the name of the DNS server that contains the database where the requested information originated.
Request | Object. Holds additional information.

Remarks

If no address is added to the Addresses collection and no name is added to the Names collection, then the ClientException property will be set by the DnsServer Control to dnsServerFailure.

If OwnerName is not set to a valid name the ClientException property will be set by the DnsServer Control to dnsServerFailure.

For each address added, a matching hostname must be added, so that Address.Count = Names.Count. If this rule is not followed, then the Error Event will fire with a ptFormatError specified as the error number and no response will be sent.

If any address does not evaluate to a valid IP dot address syntax, then the Error event will fire with a ptFormatError specified as the error number and no response will be sent.

If a DNS error occurs, the ClientException property should be set describing the error.


GetName Event

Fires when a DNS type “PTR” request has been received.

Syntax

Private Sub Object_GetName ( [ Index As Integer , ] ByVal Address As String, Names As DartStrings , OwnerName As String, ByVal Request As DnsRequest)

Part | Description
Object | Evaluates to a DnsServer Control.
Index | Integer. Array index if the object is part of an array.
Name | String. Provides the dot address (of the form xx.xx.xx.xx) for which the name or names is being requested.
Addresses | DartStrings (by reference). Names.Count is 0 when this event fires. Add one or more hostnames to this collection of Strings, and they will be formatted and sent to the client requesting the name look-up.
OwnerName | String. Provides the name of the DNS server that contains the database where the requested information originated.
Request | Object. Holds additional information.

Remarks

If no name is added to the Names collection, then the ClientException property will be set by the DnsServer Control to dnsServerFailure.

If OwnerName is not set to a valid name the ClientException property will be set by the DnsServer Control to dnsServerFailure.

If a DNS error occurs, the ClientException property should be set to describe the error.


DnsClientException Constants

Enumerates values of the ClientException property

Value | Constant | Description
0 | dnsOk | No Error (default)
1 | dnsFormatError | The name server was unable to interpret the query.
2 | dnsServerFailure | The name server was unable to process this query due to a problem with the name server.
3 | dnsNameError | The domain name referenced in the query does not exist.
4 | dnsNotImplemented | The name server does not support this request.
5 | dnsRefused | The name server refuses to perform the specified operation for policy reasons.


DnsRequest Object

Properties

The DnsRequest Object is used in the DnsServer Control events to provide access to request details found in the incoming (from the DNS client) datagram.


RemoteAddress Property

Holds the requesting DNS client’s IP address.

Syntax

Object.RemoteAddress

Part | Description
Object | Evaluates to a DnsRequest Object

Data Type

String

Remarks

Read-only

The structure of an IP address is in the form of x.x.x.x, where x is greater than 0 and less than 255. For example, 127.0.0.0 is a valid structure.


RemotePort Property

Holds the requesting DNS client’s port number.

Syntax

Object.RemotePort

Part | Description
Object | Evaluates to a DnsRequest Object.

Data Type

Long

Remarks

Read-only


RecursiveFlag Property

A request from the client for a recursive search (True) or a local database search (False).

Syntax

Object.RecursiveFlag

Part | Description
Object | Evaluates to a DnsRequest Object.

Data Type

Boolean

Remarks

Read-only.

The RecursiveFlag (referred to as RDFlag in the RFC) is very important in complying with the DNS protocol. When a client requests a recursive search the DNS server (RecursiveFlag = True) should comply with that request by either executing the request or returning a “Not Implemented ” DNS server error. (see the ClientException property for more details). If the client is not requesting a recursive search (RecursiveFlag = False), then the DNS server should execute the query on its local database only. If the server does not have a local database, or can not find a match in its database, the server should return “Name Error”. (see the ClientException property for more details).


FtpVariable Object

Use the FtpVariable Object to store and manage variables. The value is a Variant type and may reference another object, data type, or value.


Name Property

Name of the variable.

Syntax

Object.Name

Part | Description
Object | Evaluates to a FtpVariable Object.

Data Type

String

Remarks

Variable names are case-insensitive, and may contain any combination of alphanumeric characters, including spaces.


Value Property

Value of the variable.

Syntax

Object.Value

Part | Description
Object | Evaluates to a FtpVariable Object.

Data Type

Variant

Remarks

You can use this property to associate the object with any Variant.


FtpVariables Object

Collection of FtpVariable Objects.


Item Property

Use this property to set or read the value of an FtpVariable Object in the collection.

Syntax

Object.Item (Index)

Part | Description
Object | Evaluates to an FtpVariables Object.
Index | String expression. Specifies the variable name to reference. If a variable of that name is set and does not exist, then a variable of that name will be automatically created.

Data Type

Variant

Remarks

Variable names are case-insensitive. If the variable name being set does not exist, then an FtpVariable Object with that name is created. If the variable name being read does not exist, then a ptInvalidParam1 runtime error is generated, so error handling should be used.

Error Codes

The Item property may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptInvalidParam1 (When read, variable does not exist or index is out of range.)


Add Method

Add an FtpVariable Object to the collection.

Syntax

Object.Add Variable

Part | Description
Object | Evaluates to an FtpVariables Object.
Variable | FtpVariable Object to add to the collection.

Error Codes

The Add method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptNoBufferSpace


Remove Method

Remove an FtpVariable Object from the collection.

Syntax

Value = Object.Remove Index

Part | Description
Object | Evaluates to a FtpVariables Object.
Index | Long or String. Specifies a FtpVariable Object by position in the collection or by name.
Value | FtpVariable Object removed from the collection.

Remarks

If Index is specified as a Long value, it must be between 1 and Count. If Index is specified as a String value, the first FtpVariable Object in the collection with the matching case-sensitive name is removed.

Error Codes

The Remove method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1 (Index out of range or name not found)

  • ptNoBufferSpace


Request Object

Use the Request Object to obtain information about the current request.


Parameters Property

Contains the parameters sent with each command.

Syntax

Object.Parameters

Part | Description
Object | Evaluates to a Request Object.

Data Type

DartStrings Object

Remarks

Read-only.

Some commands send parameters with the command. For example, the MKD command sends the name of the directory to create with the command. The following protocol example demonstrates this:

C - Client S - Server

C: MKD Folder1

S: 257 Folder1: new directory created.

In the above protocol example the parameter is Folder1. Multiple parameters are separated by spaces in the protocol. To access parameter 2 of the command the code would look similar to the following:

Dim Param2 As String

' Get Parameter 2 of the command.

Param2 = Request.Parameters(2)


Session Property

Session Object associated with the request.

Syntax

Object.Session

Part | Description
Object | Evaluates to a Request Object.

Data Type

Session Object

Remarks

Read-only.

A Session Object is assigned to a client each time the client connects to the server. A session spans from the time a client connects to the time the client logs out or is kicked off the server.


Response Object

Use the Response Object to manage information sent back to the client. It is automatically populated with information to fulfill the Request on entry to an event. The contents of this object may be changed before it is sent to the client.


Data Property

Data to be transferred or location to receive a data transfer.

Syntax

Object.Data

Part | Description
Object | Evaluates to a Response Object.

Data Type

DartStream Object

Remarks

When set to a DartStream Object, this indicates to the server that a transfer is to be established. The TransferDown property determines the direction of the transfer.

Note Some events ignore this property. See specific event help for more information.


Status Property

Status code of the response.

Syntax

Object.Status

Part | Description
Object | Evaluates to a Response Object.

Data Type

Long

Remarks

Use this property to create the status code returned to the client. RFC 959 explains these codes. See FTP Protocol Overview for more information.


StatusText Property

Human readable status message.

Syntax

Object.StatusText

Part | Description
Object | Evaluates to a Response Object.

Data Type

String

Remarks

RFC 959 explains these these status messages. See FTP Protocol Overview for more information.


TransferDown Property

Determines the direction of a transfer.

Syntax

Object.TransferDown

Part | Description
Object | Evaluates to a Response Object.

Data Type

Boolean

Remarks

When set to True, the transfer goes from the Server to the Client (Retrieving). When set to False, the transfer goes from the Client to the Server (Storing). Some events ignore this property. See specific event help for more information.


Server Control

Properties Methods Events Constants Examples

Use the Server Control to quickly build custom server applications. This control uses an internal Daemon object and dynamically creates internal TCP objects as each passive connection is automatically accepted.

The Server Control targets high-performance server-side use and consequently relies on non-blocking operation. Applications should only use this control in a non-blocking fashion, as blocking operations (where the TCP object's Timeout property is greater than 0) can cause reentrancy problems. All events include an object reference as the first parameter so the application can easily reference the TCP object pertaining to the event.

Miscellaneous

Product | PowerTCP Server Tool
Prog ID | Dart.Server.1
File | DartServer.dll
Dependencies | DartSock.dll
Threading | Apartment Model
Licensed | Yes


Children Property

Returns a collection of TCP child connections accepted by the server.

Syntax

Object.Children

Part | Description
Object | Evaluates to a Server Control.

Data Type

Children Object

Remarks

Read-only.


ReuseAddress Property

When True, the REUSEADDR socket option is set to accept duplicate use of the same LocalAddress / LocalPort pair (these are optional parameters of the Connect and Listen methods). If used, this property must be set prior to calling the Connect or Listen method and can be set at design time.

Syntax

Object.ReuseAddress

Part | Description
Object | Evaluates to a PowerTCP control.

Data Type

Boolean

Remarks

This feature is used to comply with some protocols that require the use of the same port number for multiple active connections (such as an FTP server using data port 20 when responding to multiple FTP clients).

It might also be used to allow a Daemon Control to listen on a local port number that was recently used by an active connection.


Close Method

Release system resources.

Syntax

Object.Close

Part | Description
Object | Object expression that evaluates to a Daemon Control, Server Control, or SecureServer Control.

Remarks

The "listening" socket is immediately closed. Any actives sessions managed by the Server Control or SecureServer Control are not affected.

If Blocked and you wish to cancel the method and release resources, use the Abort method. Using Close when another method is blocking results in a ptBlocked error.

Error Codes

The Close method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptBlocked


Listen Method

Start listening for passive connections.

Syntax

Object.Listen LocalPort [ , LocalAddress ] [ , Backlog ]

Part | Description
Object | Object expression that evaluates to a Daemon Control or a Server Control.
LocalPort | Long between 1 and 65535, inclusive.
LocalAddress | Optional String. Local interface address to use in dot notation. Not usually specified.
Backlog | Optional Long. Maximum length to which the queue of pending connections may grow. Defaults to the maximum number allowed.

Remarks

If this method fails with a ptAddressInUse error, an application is most likely using the LocalPort specified. You can override this error by setting ReuseAddress to True and calling this method again.

Note You should not use this technique to have two Daemon Controls listening on the same port.

If Object is a Daemon Control, its Accept event fires when a new connection is available to be accepted.

Error Codes

The Listen method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAddressInUse

  • ptInvalidParam1 (LocalPort is not a valid port number)

  • ptNetworkDown

  • ptNoBufferSpace


Count Event

Fires to indicate that the Children.Count property has changed.

Syntax

Private Sub Object_Count ( )

Part | Description
Object | Evaluates to a Server Control or a SecureServer Control.


Service Control

Properties Methods Events Constants Example

Use the Service Control to make your application into an NT Service. Applications built with the Service Control target server-side applications that always run in the background, even when a user is not logged into the system.

With the Service Control, you can respond to all service events, including Start, Stop, Pause, and Resume. The Message event is included to support user messages sent from external applications. The Log method is included for logging event messages.

In addition, convenient Install and Uninstall methods provide a way for your application to install and uninstall itself as a service. The Abort method allows your service to abort and stop itself while running.

Miscellaneous

Product | PowerTCP Server Tool, PowerTCP SNMP Tool, PowerTCP SSL Tool, PowerTCP WebServer Tool
Prog ID | Dart.Service.1
File | DartService.dll
Dependencies | DartSock.dll
Threading | Apartment Model
Licensed | Yes


Service Control Usage

You will need to install your service prior to running it. Use the Install method to make your service self-installing (likewise, the Uninstall method can be used to remove the service from SCM control). You can also install your service during development by using the instsrv.exe program included with the Windows NT Resource Kit by Microsoft. Once your service is installed on a machine, it is registered and the Connect method can be called at application startup time.

After you call the Connect method, the State event will usually fire with the State property set to serviceRunning. Place your code here to react to state changes as your service is run, paused, resumed, or stopped. You can log entries to the Windows NT/2000 event log by calling the Log method.

To develop and test your application, use the Services Window in the Windows NT Control Panel. Start your service from there. Debug your service by enabling the Allow Service to Interact with Desktop option. This allows your service to interact with a user logged into the system.

Services differ from normal applications in that they typically run in the security context of the local system account and not the security context of the logged-on user. This does not affect your use of PowerTCP for writing robust network applications. It may, however, affect your ability to use other operating system resources.


Development Tips

The simplest way to write a service is to first write an application. Make sure the application works correctly before attempting to turn it into a service. It's important to eliminate as many errors as possible before running the application in the non-visual world of services. Most of the debugging methods that you may be accustomed to will not be available.

This topic covers the following design considerations:

  • Running as an Application

  • Running as a Service

  • Allowing Configuration of the Service

  • Installing / Uninstalling the Service

  • Debugging the Service

  • Trial Period Usage

All included sample projects use the command line to determine what mode they will run in and contain numerous comments to let you know what is occurring.

Running as an Application

The samples use the /a parameter to facilitate this. You will either find a file called "app.bat" or a shortcut called "Application" that can be used to easily run the compiled sample. Don't attempt to run the executable without parameters as this method is reserved for the NT Service Control Manager (SCM).

Back to Top

Running as a Service

The samples use no parameters when they run as a service. When the application is started without parameters, it is assumed that the SCM started it.

Back to Top

Allowing Configuration of the Service

Using the /c parameter causes the samples to run only those parts of the program that relate to changing registry settings used by the service. If you implement this properly, you can use the same executable for the service as well as configuration of the service. Simply provide a shortcut in your program group to allow your users to access it.

Back to Top

Installing / Uninstalling the Service

Most installer programs provide a means for you to install a service. However, if you want to easily test your service, you can use the Install or Uninstall method of the Service Control. The samples use the /i and the /u command parameters to demonstrate this ability. Your sample directory will contain a batch file or shortcut that you can use after compiling the project.

WARNING Never use the /i or /u parameters from within your development environment. The Install method attempts to install the calling application as a service. If you are in VB6, the calling application is VB6.exe and that is what will be installed as a service. If this happens to you, use the SCM to change to manual the startup type of the service name that was passed to the Install method, reboot, and then uninstall the service after rebooting.

Back to Top

Debugging the Service

If you have a problem while running as a service, stop the service and run it as an application. If you are unable to reproduce or correct the problem, use the Log method of the Service Control in the appropriate places in your code. This way you can use the event log to determine where the program failed. The samples demonstrate the use of the Log method. Sometimes rebooting will be the only option if a service hangs up while debugging.

Back to Top

Trial Period Usage

If you compiled the application during the 30-day trial period, a message box appears in the service's workspace, informing you that the product is not licensed for distribution. Since you cannot see this message box, you cannot close it. The message box will close after ten seconds and the service will then start normally.

If the 30-day trial period has expired, the Service Control Manager (SCM) times out while attempting to start the service and never completely starts. Also, you cannot call the Uninstall method of the Service Control. To remedy this problem, set your clock back to a time within the trial period, and then uninstall the service.

Back to Top


Params Property

Contains the parameters passed to your service. This property may be read when the State property is serviceRunning.

Syntax

Object.Params

Part | Description
Object | Evaluates to a Service Control.

Data Type

String

Remarks

Read-only. Params always begin with the service name, and each parameter is separated by CR/LF pairs.


State Property

Determine what state the service is in. The State event fires to signal that this property has changed.

Syntax

Object.State

Part | Description
Object | Evaluates to a Service Control.

Data Type

StateConstants

Remarks

Read-only.


Abort Method

Abort and stop a running service.

Syntax

Object.Abort

Part | Description
Object | Evaluates to a Service Control.

Remarks

Use this method to stop your service from running. You may call this method when the State property is serviceRunning. Once called, the service stops, and the State event fires when the State property changes to serviceStopped.


Connect Method

Connect the service to the operating system’s Service Control Manager (SCM). Call this method as soon as possible after your application starts.

Syntax

Object.Connect

Part | Description
Object | Evaluates to a Service Control.

Remarks

The Service Control creates a separate thread dedicated to managing the service, returning control back to your program immediately. You must rely on the State event and Error event to determine success or failure.

If no error is generated, the SCM starts the service, and the State event fires with State property set to serviceRunning. You must rely on this event to acknowledge successful startup of the service.

If this method is called on a Windows NT or Windows 2000 system from a normal application (not a registered service started by the system), the method fails and the serviceFailedConnect error is generated.

If this method is called on a Windows 95 or 98 system from a normal application (not a registered service started by the system), the method fails and the serviceUnsupported error is generated.

Note You must call this method within the first 30 seconds of application startup or the Service Control Manager will terminate the application.

Error Codes

The Connect method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • serviceFailedConnect (cannot connect to the service controller)

  • serviceUnknownError (an unknown error occurred)

  • serviceUnsupported (method is unsupported on this operating system)


Install Method

Example

Install the application as a service.

Syntax

Object.Install Name [ , AutoStart ] [ , Interact ] [ , Account ] [ , Password ]

Part | Description
Object | Evaluates to a Service Control.
Name | String. Specifies the name given to the service for registering with the Service Control Manager.
AutoStart | Optional Long defaults to 0. When 1, sets the service to automatically start at system boot. When 0, sets the service to start on demand.
Interact | Optional Long defaults to 0. When 1, specifies desktop interaction with the User desktop.
Account | Optional String. Specifies an account name for login. Use the format DomainName\UserName. To specify the built-in domain, set the Domain Name to a period. Defaults to a zero-length string that indicates the LocalSystem Account.
Password | Optional String. Specifies a password for login. Defaults to zero-length string to signify no password.

Remarks

WARNING: Your application must be run as a compiled executable for this method to work correctly. If you run your application from within some development environments (such as Visual Basic) and call this method, the IDE itself will be erroneously installed.

Note The Connect and Install methods cannot be called during the same running instance. You will need to split your code at startup time between running as an application installing itself as a service using the Install method, and running as a service connecting to the service control manager using the Connect method. The Example VB code sample shows how to accomplish this.

This method installs the application as a service. Once installed, connect the service to the service control manager with the Connect method.

This method creates a service object and installs it in the service control manager database by creating a key with the same name as the service under the following registry key:

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services

To install a service, you must be running from an account with administrator access rights. Otherwise, the Install Method fails with the runtime error serviceAccessDenied.

The Install method gives the service the ability to log service entries to the Windows NT event log by creating a key with the same name as the service under the following registry key:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\Application

Underneath this key is written two subkeys: EventMessageFile and TypesSupported. These subkeys give your service the ability to log entries into the event log with the Log method.

Set the AutoStart parameter to True to set the service to always start upon boot. Your service will run without any user logged onto the machine.

Set the Interact parameter to True to let your service display a graphical user interface. This is great for debugging the service. Setting AutoStart and Interact to True is not recommended.

If the service is not run from the LocalSystem account, perhaps because it needs security permissions for accessing certain resources, set the Account and Password parameters.

If called when running on Windows 95 or Windows 98, the method fails with the run-time error serviceUnsupported.

One way to self-install a service is via a command line switch.

Error Codes

The Install method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • serviceAccessDenied (requested access was denied due to insufficient security privileges)

  • serviceAlreadyExists (service name specified already exists as a service)

  • serviceBadAccount (account name specified is invalid)

  • serviceInvalidName (specified service name is invalid)

  • serviceUnknownError (an unknown error occurred)

  • serviceUnsupported (method is unsupported on this operating system)


Log Method

Enter an event in the Windows Event Log.

Syntax

Object.Log Type, Event [ , Message ]

Part | Description
Object | Evaluates to a Service Control.
Type | TypeConstants. Identifies the type of log entry.
Event | EventConstants. Identifies the event to log.
Message | Optional String. Message for the log entry when Event is serviceDebug, serviceError or serviceInfo.

Remarks

Services should log important events in the operating system event log. You can take advantage of this method to log events while debugging also.

Set the Event parameter to serviceStarted, serviceStopped, servicePaused, or serviceResume with the Message parameter left blank to log a start, stop, pause, or resume event respectively. Set the Event parameter to other values and utilize the Message parameter for more descriptive messages.

Error Codes

The Log method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • serviceAccessDenied (the requested access was denied due to insufficient security privileges),

  • serviceUnknownError (an unknown error occurred)


Uninstall Method

Uninstall a service.

Syntax

Object.Uninstall Name

Part | Description
Object | Evaluates to a Service Control.
Name | String. Identifies the name given to a service as registered with the service control manager.

Remarks

This method marks a service for deletion from the service control manager database. The service is not actually removed from the operating system until all applications currently accessing the service have closed their access, and the service is stopped. If the service cannot be stopped, the database entry is removed when the system is restarted. The preferred way to uninstall a service is to make sure it is stopped first.

The service control manager deletes the service by deleting the service key and its subkeys from the registry.

Error Codes

The Uninstall method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • serviceAccessDenied (requested access was denied due to insufficient security privileges)

  • serviceInvalidServiceName (Name is invalid)

  • serviceUnknownError (unknown error occurred)

  • serviceUnsupported (method is unsupported on this operating system)


Error Event

Fires when an error occurs. This event fires before the error is reported back to the container's error object.

The Connect method and Log method can generate an error. This event is included for environments that do not properly support the error object.

Syntax

Private Sub Object_Error ( [ Index As Integer , ] Number As ErrorConstants, Description As String )

Part | Description
Object | Evaluates to a Service Control.
Index | Integer. Array index if the object is part of an array.
Number | ErrorConstants value.
Description | String. ErrorConstants description.


Message Event

Fires when an application sends the service a user message. This can be used any way you wish, as it has no special meaning to the operating system.

Syntax

Private Sub Object_Message ( Number as Long )

Part | Description
Object | Evaluates to a Service Control.
Number | Long. Message number sent from an application in range 128 to 255.


State Event

Fires to indicate the State property has changed value.

Syntax

Private Sub Object_State ( )

Part | Description
Object | Evaluates to a Service Control.

Remarks

You should place service control code in this event.

When the State property changes to serviceRunning, the service is running. This state change always occurs first. The Params property will include any parameters passed to the service.

When the State property changes to serviceStopped, the service has stopped (this may have been accomplished interactively by the user or upon system shutdown). Place any service shutdown code here. You should be brief as typically you only have up to 20 seconds.

When the State property is set to servicePaused or serviceResume, the service is pausing from a running state or resuming from a paused state, respectively.


ErrorConstants

The Number parameter of the Error event is always set to one of the following values:

Value | Constant | Description
1 | serviceUnknownError | An Unknown error occurred.
5 | serviceAccessDenied | The requested access was denied due to insufficient security privileges.
87 | serviceInvalidParameter | A parameter that was specified was invalid.
120 | serviceUnsupported | The method is unsupported on this operating system.
123 | serviceInvalidName | The specified service name is invalid.
1056 | serviceAlreadyRunning | An instance of the service is already running.
1057 | serviceBadAccount | The account name specified is invalid.
1060 | serviceDoesNotExist | The specified service does not exist.
1063 | serviceFailedConnect | Cannot connect to the service controller.
1072 | serviceMarkedUninstall | The service has already been marked to uninstall.
1073 | serviceAlreadyExists | The specified service already exists in the service control manager database.


EventConstants

The Event parameter of the Log method is always set to one of the following values:

Value | Constant | Description
100 | serviceNoStartEvent | Service could not be initialized and started.
101 | serviceStartedEvent | Service was started log entry.
102 | serviceStoppedEvent | Service was stopped log entry.
103 | servicePausedEvent | Service was paused log entry.
104 | serviceResumeEvent | Service was resumed log entry.
105 | serviceDebugEvent | Debug event log entry.
106 | serviceErrorEvent | Error event log entry.
107 | serviceInfoEvent | Informational event log entry.


StateConstants

The State property is always set to one of the following values:

Value | Constant | Description
0 | serviceStopped | The service is not currently running.
1 | servicePaused | The service is paused.
2 | serviceRunning | The service is running.
3 | serviceResumed | The service has resumed after being paused.


TypeConstants

The Type parameter of the Log method is always set to one of the following values:

Value | Constant | Description
1 | serviceError | Error message.
2 | serviceWarning | Warning message.
4 | serviceInformation | Informational message.
8 | serviceAuditSuccess | AuditSuccess event message.
16 | serviceAuditFailure | AuditFailure event message.


Session Object

Use the Session Object to manage information describing a client session. A session persists from the initial connection of the client to the log out or termination of the connection.


Id Property

Unique identifier for the session.

Syntax

Object.Id

Part | Description
Object | Evaluates to a Session Object.

Data Type

String

Remarks

This property is a unique identifier for a session over time and space. The ID is sent to the client in the form of a "per-session" cookie that is not stored. When the client makes subsequent requests the ID is sent back to the server. This ID is then used to match a Session Object from the Sessions Object with a specific client.


IdleTime Property

Example

Amount of time in minutes the session has been idle.

Syntax

Object.IdleTime

Part | Description
Object | Evaluates to a Session Object.

Data Type

Long

Remarks

Inactivity means no data or commands have been sent to the server and no response or data have been sent to the client. Set this property at anytime to either prevent or force a session to be killed.


User Property

User object associated with the session.

Syntax

Object.User

Part | Description
Object | Evaluates to a Session Object.

Data Type

User Object

Remarks

Represents the current user for this session. This property is used in the Login event to authenticate a user. A session with a valid user object is an authenticated session. Set this property to Nothing to prevent a user from logging in.


Variables Property

Collection of variables defined as name/value pairs.

Syntax

Object.Variables

Part | Description
Object | Evaluates to a Session Object.

Data Type

FtpVariables Object

Remarks

This property contains a collection of user defined variables associated with the session. The Value in this case may contain any Variant type.


Sessions Object

Use the Sessions Object to manage multiple Session Objects.


Count Property

Number of nonsecure TCP connections currently open.

Syntax

Object.Count

Part | Description
Object | Evaluates to a WebServer Control.

Data Type

Long

Remarks

Read-only.

The number of nonsecure client connections currently open may be greater than the number of Session Objects, since a client may have more than one connection to the server at the same time.


Item Method

Provides array subscript access into the collection.

Syntax

Value = Object.Item Index

Part | Description
Object | Evaluates to a Sessions Object.
Index | Long or String. Specifies a Session by position in the collection or by Id.
Value | Session Object requested.

Remarks

This method returns a Session from the collection. Index may be a long value between 1 and Count, or Index may be a string value specifying a Session ID to return.

Error Codes

The Item method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1 (Index is out of bounds or ID is not found)

  • ptNoBufferSpace


Remove Method

Remove a Session from the collection.

Syntax

Value = Object.Remove Index

Part | Description
Object | Evaluates to a Sessions Object.
Index | Long or String. Specifies a Session by position in the collection or by Id.
Value | Session Object removed from the collection.

Remarks

This method removes a Session from the collection. Index may be a long value between 1 and Count, or Index may be a string value specifying a Session Id to remove.

Error Codes

The Remove method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1 (Index is out of bounds or Id is not found)

  • ptNoBufferSpace


TCP Control

Properties Methods Events Constants Example

Use the TCP Control to manage streams of data. It simplifies the use of TCP communications by providing methods to establish, send and receive data, and terminate socket-based connections. By default, communications will block execution of your program, but non-blocking use can be easily enabled for demanding applications that require event-driven communications.

You can use this control to implement upper-layer protocols, including protocols of your own creation. You can also use it with the Daemon Control to build simple server applications. The robust Server Control uses a single Daemon Control with dynamic TCP Controls to provide a "turn-key" server control.

Miscellaneous

Product | PowerTCP Server Tool , PowerTCP Winsock Tool
Prog ID | Dart.Tcp.1
File | DartSock.dll
Dependencies | None
Threading | Apartment Model
Licensed | Yes


TCP Control Usage

Developing Client Software that Makes Active Connections

  1. Use a TCP Control to connect to a remote server (application) with the Connect method.

  2. Send data to the remote application with the Send method.

  3. Receive and process data from the remote application with the Receive, Fill, or Search methods. These methods receive data in slightly different ways, depending upon your requirements.

  4. Close the connection with the Close method.

Developing Server Software that Listens for Passive Connections

  1. Use a Daemon Control to listen for incoming connections with the Listen method.

  2. When an incoming connection is requested, use the Accept method to capture the socket identifier from within the Accept event, create a TCP control to manage the connection, and pass it the socket identifier by setting the Socket property. TCP objects can be created dynamically or as members of an array. Either way, some housekeeping is required to manage all the connections. Use the Server Control to simplify building servers.

  3. Use the TCP Control as described above.

  4. Close the Daemon with the Close method.


TCP Protocol Overview

This topic covers:

  • Protocol Overview

  • Features

  • Connections

Protocol Overview

Transmission Control Protocol (TCP) is a data communications protocol—a set of rules for communications between computers. TCP provides a reliable stream of data between two connected computers.

TCP is the base protocol used for Telnet, FTP, SMTP, HTTP, POP, IMAP and other upper-layer protocols that use stream-based communications. Using TCP, you can implement any of these more complicated protocols. In fact, PowerTCP does exactly that by using the TCP Control for all communications.

Back to Top

Features

TCP is built upon IP (Internet Protocol), which provides an unreliable transfer of data. TCP uses the following methods to provide a reliable stream:

  • When one end of a connection receives data, it sends back an acknowledgment message. If one end of a connection does not receive a confirmation after it sends data, it resends the data until it receives a confirmation or times out.

  • Checksums are used to ensure no data corruption occurs. If the checksum on received data does not match the data sent, it discards the data and does not acknowledge having received the data. The other end then resends the data because it has not received an acknowledgment.

  • Both ends of a connection use buffering to store data before it is used by the application, and ensures that neither buffer will overflow. This is known as flow control.

  • Data being sent may be split up or combined into segments of any size. Bytes sent from one end of a connection arrive at the other end in the same order, but not necessarily in the same size segments as which they were sent.

  • Because TCP is built upon the unreliable IP, TCP must ensure that bytes arrive in the correct order and are not duplicated. To achieve this, TCP changes the order of received data and deletes duplicate data if necessary.

  • TCP is a stream-oriented protocol; the flow of data is without any predictable breaks. It is up to an application to define meaningful record blocking and protocol signaling.

  • TCP provides simultaneous two-way (full-duplex) data transfer; data can flow both ways at the same time.

Back to Top

Connections

TCP is a connection-oriented protocol—a connection must be established between two computers before they can exchange data. This works as follows:

  1. A client computer sends a message to a server computer requesting a connection. The server has a Daemon process running on a port that handles this request.

  2. The server responds, acknowledging the connect request.

  3. The client then sends a second message to the server acknowledging the server's message.

The previous steps establish the connection. The server must be listening for connections before the client can connect. The following two actions occurred:

  • The server made a passive connection—it was listening for client computers trying to connect.

  • The client computer that initiated the connection made an active connection.

While the connection is active, it is uniquely defined by the following four values that are included in each TCP packet:

  • Two port numbers that identify the source and destination TCP port. Port numbers are used by the operating system to route the data to the application "bound" to that port.

  • Two 4-byte addresses that identify the source and destination host interface. For example, a notebook computer may have one IP address for a LAN card and one IP address for RAS connections using COM3. This would be considered a "multi-homed host", and applications can bind to either port.

Closing a connection works in a similar way to establishing a connection. One end makes an active close and the other end then performs a passive close.

Back to Top


NoDelay Property

When True, the NODELAY socket option is set to defeat Nagle's algorithm.

Syntax

Object.NoDelay

Part | Description
Object | Evaluates to a PowerTCP control.

Data Type

Boolean

Remarks

This property is available only at run time and can only be set when the State property is tcpConnected.

Nagle's algorithm is a technique used to conserve bandwidth by buffering data that would otherwise be sent in individual packets. The NODELAY socket option is rarely needed, but may be desirable for Telnet and other online protocols. The Telnet Control uses this socket option to improve interactive responsiveness.


ReceiveBufferSize Property

Number of bytes the system has for buffering incoming data.

Syntax

Object.ReceiveBufferSize

Part | Description
Object | Evaluates to a PowerTCP object.

Data Type

Long

Remarks

The default value for Microsoft TCP/IP is 8192. This property can be used only at run time when the State property is tcpConnected. A substantial increase in data rate is possible using larger values on high-speed networks. See the ReceiveBufferCount property.

Error Codes

The ReceiveBufferSize property may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptNetworkDown


SendBufferSize Property

Number of bytes the system uses for buffering outgoing data.

Syntax

Object.SendBufferSize

Part | Description
Object | Evaluates to a PowerTCP object.

Data Type

Long

Remarks

The default value for Microsoft TCP/IP is 8192.

This property can be used only at run time when the State property is tcpConnected. A substantial increase in data rate is possible using larger values on high-speed networks. Refer to the SendBufferCount property for more information.

Error Codes

The SendBufferSize property may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptNetworkDown


Connect Method

Establish a connection. The State property immediately changes to tcpConnecting and then changes to tcpConnected when the connection is established. The State property can be checked in the body of the State event, polled off a timer, or checked immediately after this method is used when a positive Timeout is specified.

Syntax

Object.Connect RemoteName [ , RemotePort ] [ , LocalName ] [ , LocalPort ]

Part | Description
Object | Object expression that evaluates to a TCP Control.
RemoteName | String. Specifies either a host name (host.dart.com) or dot address (nnn.nnn.nnn.nnn).
RemotePort | Optional Long. Specifies a remote port between 1 and 65535, inclusive. Default is 23.
LocalName | Optional String. Specifies the local network interface (either a host name, host.dart.com, or dot address, nnn.nnn.nnn.nnn). Not usually used.
LocalPort | Optional Long. Species the local port. Not usually used.

Remarks

This method blocks if Timeout is greater than 0. The Blocked property may be checked to verify the control is not executing another method.

Error Codes

The Connect method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAbort

  • ptAddressInUse

  • ptAddressNotAvailable

  • ptBlocked

  • ptConnectionRefused

  • ptHostNotFound

  • ptInvalidParam1 (RemoteName is not a valid string)

  • ptInvalidParam2 (RemotePort is not between 1 and 65535, inclusive)

  • ptNetworkDown

  • ptNetworkUnreachable

  • ptNoBufferSpace

  • ptNoData

  • ptNotInitialized

  • ptTimeout

  • ptTryAgain


Fill Method

Use this method when you know exactly how many bytes or characters you want from the TCP stream. Data is either filled to capacity or no data is returned. This method is useful for processing fixed-length records that can include binary structures.

Syntax

[ Count = ] Object.Fill Data

Part | Description
Object | Object expression that evaluates to a PowerTCP Control.
Data | String or Byte array. Received bytes will be used to fill Data.
Count | Long. Returns the number of Unicode characters or bytes copied into Data.

Remarks

This method can only be used when the State is tcpConnected or tcpClosing (otherwise a ptNotConnected error is generated). When the State is tcpClosing, the Receive, Fill, or Search methods can be used to flush the buffer and cause the State to change to tcpClosed.

Unlike the Receive and Search methods, the Fill method will not resize Data because its size indicates how many bytes should be read.

If Timeout is 0, this method immediately returns a Count of either 0 (no data was read) or the size of Data (Data was filled). If Timeout is greater than 0, this method attempts to completely fill Data with bytes or generate a ptTimeout error. If a ptTimeout error is generated, the session is aborted and all system resources are released.

If Data is a String and the default ANSI code page is not ASCII, multi-byte characters may convert to single Unicode characters. Blocked returns True while performing a blocking method (Timeout is greater than 0).

Out-of-band data is sent using the Send method with the Urgent parameter set to True. PowerTCP uses the SO_OOBINLINE socket option to always receive out-of-band data "in-line". In other words, all out-of-band data is received as normal data. It is up the user to correctly process this data.

Error Codes

The Fill method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAbort

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptInvalidParam1 (Data is not a String or Byte array)

  • ptNetworkDown

  • ptNetworkReset

  • ptNotConnected

  • ptTimeout


Send Method

Send data after a connection is established. The Send event fires when data is accepted by the system. The SendBufferCount property always indicates the number of bytes that have been submitted but have not yet been accepted by the system.

Syntax

[ SentCount = ] Object.Send Data [ , Count ] [ , Urgent ]

Part | Description
Object | Object expression that evaluates to a SecureTcp Control or a TCP Control.
Data | String, Byte or Byte array. Contains the data to send.
Count | Optional Long. Specifies the number of bytes to send (limits a String or Byte array to Count bytes).
Urgent | Optional Boolean. Defaults to False. If True, Data is sent using the "out-of-band" flag.
SentCount | Optional Long. Indicates the number of bytes accepted.

Remarks

This method can only be used when the State property is tcpConnected (otherwise a ptNotConnected error is generated).

Data can be provided in two ways:

  • A String will be converted from Unicode to multi-byte according to the default ANSI code page. If the code page is US-ASCII, then each 16-bit Unicode character is translated into an 8-bit byte. If the code page is not US-ASCII, then each 16-bit Unicode character is translated into a general multi-byte representation. This is a convenient coding mechanism for many environments, but is not as efficient as sending a Byte array.

  • A Byte or Byte array is sent as presented, with no translation.

If Count is specified and is greater than 0, then the number of bytes sent is limited to Count. For example, if a Byte array of length 8192 contains only 100 bytes that you wish to send, then a Count of 100 can be used to override the default behavior, which would be to send the entire 8192 bytes (the length of the array).

This method supports blocking and non-blocking operation, depending on the value of the Timeout property. The Blocked property may be checked to verify the control is not busy executing another method. If the Timeout property is positive, this method will block until the system accepts the data for sending (SendBufferCount decrements to 0) or the timeout period expires.

Set the Urgent parameter to True to send Out-of-band data. This is not typically used, but some servers rely on it. PowerTCP uses the SO_OOBINLINE socket option to always receive out-of-band data "in-line".

You can also send binary data types and structures. Use the Fill method to receive binary data types and structures.

Error Codes

The Send method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptBlocked

  • ptConnectionAborted

  • ptConnectionReset

  • ptInvalidParam1 (Data is not a String, Byte or Byte array)

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected

  • ptTimeout


User Object

Use the User Object to obtain information about the current user and to indicate that a client has been authenticated.


CurrentPath Property

Current path of the user.

Syntax

Object.CurrentPath

Part | Description
Object | Evaluates to a User Object.

Data Type

String

Remarks

The path is relative to the directory specified by the RootDirectory parameter of the FtpServer Control Start method. This property can be changed to relocate a users current directory path.


Id Property

Unique ID for the user.

Syntax

Object.Id

Part | Description
Object | Evaluates to a User Object.

Data Type

String

Remarks

This property is a unique identifier for the current user. Use this property to uniquely identify a user.


Name Property

Username specified by the client

Syntax

Object.Name

Part | Description
Object | Evaluates to a User Object.

Data Type

String

Remarks

When the client sends the USER command this property is populated by the username sent.


Password Property

Password specified by the client.

Syntax

Object.Password

Part | Description
Object | Evaluates to a User Object.

Data Type

String

Remarks

When the client sends the PASS command this property is populated by the password sent.


PowerTCP SSL Tool

PowerTCP SSL Tool (Formerly Secure Tool)

Support Licensing Distribution Certificate Manager Security Overview

Windows 95/98 Security Compatibility

Automatically authenticate and encrypt/decrypt all data sent and received over a TCP connection using SSL2, SSL3, PCT, and TLS. The SSL Tool supports both server and client operation.

Controls

Control | Description
CertificateList Control | Present the user with an interface to select certificates
Daemon Control | Accept connections
SecureFtp Control | Establish secure FTP sessions
SecureFtpServer Control | Build into your application a fully-functioning standalone or custom secure FTP server
SecurePop Control | Download mail from a secure POP server
SecureServer Control | Combines a Daemon Control with a collection of SecureTcp Controls for superior "turn-key" secure server performance
SecureTcp Control | Send data securely over the Internet
Service Control | Turn your server application into an NT service

You can integrate this product with other PowerTCP Tools to provide a complete solution for any number of applications:

  • Combined with the PowerTCP Winsock Tool or PowerTCP Server Tool, you can create a proxy server that accepts either clear or secure TCP connections and generates secure or clear TCP connections, respectively.

  • Combined with the PowerTCP Emulation Tool, you can create a secure VT Terminal Emulator that connects to your internal proxy server (that you create) that uses a Telnet connection to connect to internal corporate resources.

  • Create any client/server application that implements secure transactions knowing that your data is safe from any security risk on the Internet.

Note The SecureTcp Control is dependent upon system services provided by Windows 2000 or Windows NT 4 service pack 4 or higher. A digital certificate must be present for server applications or client applications when the server requires client authentication. Win 9X requires crypto update.

Supporting Objects

Object | Description
Certificate Object | Access information about a digital certificate
Certificates Object | Collection of Certificate Objects
CertificateStore Object | Gain access to a store of certificates on the local system
FtpVariable Object | Store and manage variables
FtpVariables Object | Collection of FtpVariable Objects
ListEntry Object | Provides easy access to file information provided by an FTP listing
ListEntries Object | Collection of ListEntry Objects
Request Object | Obtain information about the current request
Response Object | Manage information sent back to the client
Session Object | Manage information describing a client session
Sessions Object | Manage multiple Session Objects
User Object | Obtain information about the current user and to indicate that a client has been authenticated

Sample Projects

The following sample projects demonstrate how to use the SSL Tool:

Sample Project | Description
Secure FTP Client | Demonstrates a simple secure FTP client that can be used with the Secure FTP Server sample. Visual Basic 6.
Secure FTP Server | Demonstrates a simple secure FTP server that can be used with the Secure FTP Client sample. Visual Basic 6.
Secure POP Client | Demonstrates a simple secure POP client that can be used with any POP server that supports secure communications. Visual Basic 6.
Secure TCP Blaster | A simple TCP Daemon and Secure Client application, written using blocking operation, that uses all three methods for receiving data: Receive , Search, and Fill . Visual Basic 6.
Secure Web Client | Demonstrates a simple Secure HTTP/S Client application written using non-blocking operation. Visual Basic 6.
Secure Web Server | Demonstrates a simple multi-threaded Web Server application that serves up HTML pages stored in local files over a secure connection. Visual Basic 6.


Certificate Manager

To take advantage of security features, you might need to manage security certificates on your computers. Browsers that support HTTPS, for example, usually provide some kind of certificate management. Access the Certificate Manager Application from your PowerTCP Tool program group to request, install, view, and delete certificates.

This topic covers:

  • Requesting Certificates

  • Installing Certificates

  • Viewing Certificates

  • Deleting Certificates

Requesting Certificates

Select Generate Certificate Request item from the Action menu. Upon answering the questions, the application creates a certification request that you can submit to a Certificate Authority. VeriSign, for example, lets you paste your request right into their request page for posting. The request may look similar to the following:

-----BEGIN NEW CERTIFICATE REQUEST-----

MIICSjCCAfgCAQAwYDENMAsGA1UEAxMEdGVzdDENMAsGA1UECxMEdGVzdDENMAsG

A1UEChMEdGVzdDERMA8GA1UEBxMIU3lyYWN1c2UxETAPBgNVBAgTCE5ldyBZb3Jr

MQswCQYDVQQGEwJVUzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDYz7fwOdypBbVg

RoEokSPD/dxX13WWKvEycGR/osQvFe1buyUhbyBoYhGWEgYdwTH8szEbw7gEhnFH

MOOO0SI/AgMBAAGgggExMDUGCisGAQQBgjcCAQ4xJzAlMA4GA1UdDwEB/wQEAwIB

ODATBgNVHSUEDDAKBggrBgEFBQcDATCB9wYKKwYBBAGCNw0CAjGB6DCB5QIBAR5U

AE0AaQBjAHIAbwBzAG8AZgB0ACAAQgBhAHMAZQAgAEMAcgB5AHAAdABvAGcAcgBh

AHAAaABpAGMAIABQAHIAbwB2AGkAZABlAHIAIAB2ADEALgAwA4GJAF9xaVOKjlSs

CT9lWiaNdxWeaLsH7Y/wt/GZBRWAZKjYh8NYqc4m/rMH16OBvrhuBxVoRBe+gYB1

odurIdEfvJwdSfDl3Ul/teQJ8DmUKmuDD9tWDqNhnxLU1yCQVJvGmQxEA9Ubmiqg

oowc9milVy4RQKWPd3Hsammgyx4gjuAFAAAAAAAAAAAwCQYFKw4DAh0FAANBAGyQ

S0UioDjGPehblj3NkhH+w5DIE5gCBymm1pVLUS+YEIGGtJIxMd0ZMXnyD/BGKPvo

eyFjG9A8Sp105tKn2dQ=

-----END NEW CERTIFICATE REQUEST-----

Back to Top

Installing Certificates

Select the Install Certificate item from the Action menu. You can take the certificate generated by your Certificate Authority (generated from your certificate request), and install it into the desired Certificate Store. This certificate can now be referenced by the CertificateStore Object.

Back to Top

Viewing Certificates

The main window of the application allows you to view the certificates installed in the "MY" and "ROOT" stores defined in the HKEY_LOCAL_MACHINE and HKEY_CURRENT_USER registry locations.

Back to Top

Deleting Certificates

Select the Delete Certificate item from the Action menu.

Back to Top


Security Overview

This topic covers:

  • What is a digital certificate?

  • Where do I get a certificate?

  • How does the authentication process work?

  • What is a certificate store?

  • What are the system store and the machine store?

  • What is the X500 naming convention?

What is a digital certificate?

Authentication is important for secure communications. Users must be able to prove their identity to the entities they are communicating with. In addition they must be able to verify the identity of the entity communicating with them. This is accomplished by presenting or verifying some form of trusted credentials.

A digital certificate is a common credential that provides authentication. A trusted organization, called a Certificate Authority (CA), assigns a certificate to a user or entity and the user or entity then uses the certificate to prove itself to the other side. You may configure your system to accept any number of Certificate Authorities. Completing the following steps to access the Certificates dialog box:

  1. In the Control Panel, double-click Internet Options.

  2. Select the Content tab, and then click Certificates.

Back to Top

Where do I get a certificate?

Certificates must come from a trusted CA. A user submits a certificate request to a CA and the CA returns a certificate for the user to use. Listed below are some Certificate Authorities:

  • Microsoft Certificate Server – used for internal corporate Certificate delegation

  • VeriSign – (www.verisign.com) provides certificates for Internet users and servers

You always need a digital certificate installed to operate as a server. You only need a digital certificate installed on a client if the server requests authentication.

Back to Top

How does the authentication process work?

  1. The client will always initiate the TCP connection. Port 443 is normally used for Secure Socket Layer (SSL) connections. The Connect method makes this TCP connection, sends a "client hello" message, and automatically responds to authentication requests received from the server.

  2. The server accepts the connection initiated by the client, constructs its digital credentials from the digital certificate referred to by its Certificate Property, and sends its credentials to the client.

  3. If the server's ClientAuthentication Property is True, it also sends an authentication request to the client.

  4. The client receives the server's credentials, verifies it against the CAs it is configured to trust, and responds with its own credentials if an authentication request is received (this response is based upon the client's digital certificate referenced by its Certificate Property).

  5. If the client and server cannot negotiate a mutually acceptable security protocol, an error is generated and the connection is closed.

  6. If the client cannot validate the server's credentials, an error is generated and the client closes the connection.

  7. If the server cannot validate the client's credentials (if requested), an error is generated and the server closes the connection.

  8. Once protocol negotiation and authentication is successful, secure encryption/decryption is performed on all data passing over the connection.

  9. The session is terminated when one side closes the connection.

Back to Top

What is a certificate store?

A certificate store is a location on the system (memory, disk, registry, etc.) where certificates are stored for use. There are three major system stores.

  • MY – personal certificates go here

  • ROOT – certificates for Trusted Root Certificate Authorities

  • CA – all other certificates

Back to Top

What are the system store and the machine store?

The system store is the certificate store located in the HKEY_CURRENT_USER key. The machine store is the certificate store located in the HKEY_LOCAL_MACHINE key. Applications installed as a service should store their certificates in the machine store since there is no current user when running as a service.

Back to Top

What is the X500 naming convention?

This is a format for creating a distinguished name. The different parts of the name are described below:

  • C – country you are in (ex. US)

  • S – state you are in (ex. New York)

  • L – locality value or city (ex. Syracuse)

  • O – your organization (ex. Dart)

  • OU – organizational unit (ex. Development)

  • CN – common name; typically the name of the system or user (Ex. MyMachine)

Here are some examples of X500 names:

  • C=US, S=New York, L=Syracuse, O=Dart, OU=Development, CN=My Machine

  • C=US, S=Georgia, L=Atlanta, O=MyOrg, OU=Toy Department, CN=John Doe

Back to Top


Windows 95/98 Security Compatibility

Until recently, the SSL/TLS Security Support Provider on the Windows 9x platforms was not fully implemented. Microsoft addressed this issue through a series of procedures we will explain below. For more in-depth information, please see http://support.microsoft.com/support/kb/articles/q276/2/45.asp.

The following steps must be incorporated before installing any secure-dependent products.

  1. Make sure you have the latest Dart update from http://www.dart.com/support.

  2. Install Internet Explorer 5.01 or higher with 128-bit encryption.

  3. Install Directory Service Client software for Windows 9x. This program can be found on any Windows 2000 CD in the \Clients\Win9x folder. The name of this application is DSCLIENT.EXE. If you do not have a Windows 2000 CD, please contact Microsoft Developer Support. For more information on this software, please see http://msdn.microsoft.com/library/periodic/period99/support.htm.

  4. Enable the SChannel Security Support Provider in the registry.

    • Start Registry Editor (Regedit.exe).

    • Locate the following key in the registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders

    • On the Edit menu, click Modify, and then modify the following registry value:

      • Value Name: Security Providers

      • Data Type: REG_SZ

      • Value: Append ",schannel.dll" (with comma, no quotes) to previous string.

Note: Certificates for use with the SSL/TLS protocols on Windows 95, 98, Me, and Windows NT 4.0 must be marked exportable. Windows 2000 SSL/TLS protocols do not have this requirement.


Certificate Object

Properties Constants Example

Use the Certificate Object to access information about a digital certificate.


Handle Property

Handle of the certificate.

Syntax

Object.Handle

Part | Description
Object | Evaluates to a Certificate Object.

Data Type

Long

Remarks

Use this handle in place of PCCERT_CONTEXT values in relevant Crypto API functions.


IssuedBy Property

Name of the Certificate Authority (CA) that issued/signed the certificate.

Syntax

Object.IssuedBy

Part | Description
Object | Evaluates to a Certificate Object.

Data Type

String

Remarks

Read-only.


IssuedTo Property

Certificate subject or owner.

Syntax

Object.IssuedTo

Part | Description
Object | Evaluates to a Certificate Object.

Data Type

String

Remarks

Read-only.

When a certificate request is made, a "common name" is specified. The Certificate Authority usually uses this name for the subject name as defined by X.509, which corresponds to this property.


KeyName Property

Name of the key container that contains the private key of the certificate.

Syntax

Object.KeyName

Part | Description
Object | Evaluates to a Certificate Object.

Data Type

String

Remarks

Read-only.

The key name is also useful when deleting the key pair associated with a certificate. You cannot recover a key pair once it is destroyed. A new key pair needs to be generated and a new certificate needs to be issued. This is recommended for advanced users only. See the Microsoft Crypto API documentation for more information.


KeySize Property

Size of the key measured in bits.

Syntax

Object.KeySize

Part | Description
Object | Evaluates to a Certificate Object.

Data Type

Long

Remarks

Read-only.

This property indicates the strength of the keys used by the certifcate.

Key | Size | Strength
512 | bit | Weak
1024 | bit | Strong
2048 | bit | Stronger

Note To generate keys that are greater than 512 bits the "Microsoft Enhanced Cryptographic Provider v1.0" is needed.


KeyUsage Property

Key usage attributes.

Syntax

Value = Object.KeyUsage ( Usage )

Part | Description
Object | Evaluates to a Certificate Object.
Usage | KeyUsageContants enumerated type.

Data Type

Boolean

Remarks

Read-only.


SerialNumber Property

Certificate serial number.

Syntax

Object.SerialNumber

Part | Description
Object | Evaluates to a Certificate Object.

Data Type

String

Remarks

Read-only.

In combination with IssuedBy, this property can be used to uniquely identify a certificate.


ValidFrom Property

Example

Starting date and time (in Greenwich Mean Time) the certificate is valid.

Syntax

Object.ValidFrom

Part | Description
Object | Evaluates to a Certificate Object.

Data Type

Date

Remarks

Read-only.


ValidTo Property

Example

Ending date and time (in Greenwich Mean Time) the certificate is valid.

Syntax

Object.ValidTo

Part | Description
Object | Evaluates to a Certificate Object.

Data Type

Date

Remarks

Read-only.


Version Property

Version of the certificate.

Syntax

Object.Version

Part | Description
Object | Evaluates to a Certificate Object.

Data Type

Long

Remarks

Read-only.


KeyUsageConstants

Enumerates the Usage parameter of the KeyUsage property:

Value | Constant | Description
-1 | usageAll | Used for the KeyUsageSelect property. Performs no filtering on the Certificates Object (collection).
0 | usageDataEncipherment | Certificate can be used for Data Encipherment.
1 | usageDigitalSignature | Certificate can be used for Digital Signatures.
2 | usageKeyAgreement | Certificate can be used for Key Agreement.
3 | usageCertSign | Certificate can be used for Certificate Signing.
4 | usageEnciphermentKey | Certificate can be used for Key Encipherment.
5 | usageNonRepudiation | Certificate can be used prevent Repudiation.
6 | usageOfflineCrlSign | Certificate can be used for CRL Signing.
7 | usageServerAuthentication | Certificate can be used for Server Authentication.
8 | usageClientAuthentication | Certificate can be used for Client Authentication.
9 | usageCodeSigning | Certificate can be used for Code Signing.
10 | usageEmailProtection | Certificate can be used for Email Protection.
11 | usageIPSecEndSystem | Certificate can be used for IPSec End System.
12 | usageIPSecTunnel | Certificate can be used for IPSec Tunneling.
13 | usageIPSecUser | Certificate can be used for IPSec Users.
14 | usageTimeStampSigning | Certificate can be used for Time Stamp signing.


CertificateList Control

Properties Methods Events Constants Example

Use this control to present the user with an interface to select certificates. The CertificateList Control is derived from a standard ListView window. By default it has this standard appearance:

  • Report view

  • Three column headers: Issued By, Issued To, and Key Size

  • Default certificate icon

Miscellaneous

Product | PowerTcp SSL Tool, PowerTcp WebServer Tool, PowerTCP Web Enterprise Tool
Prog ID | Dart.CertificateList.1
File | DartCertificate.dll
Dependencies | DartSock.dll
Threading | Apartment Model
Licensed | Yes


Appearance Property

Returns or sets the appearance (flat or 3-D) of the control.

Syntax

Object.Appearance

Part | Description
Object | Evaluates to a CertificateList Control.

Data Type

AppearanceConstants


BackColor Property

Returns or sets the background color of the control.

Syntax

Object.BackColor

Part | Description
Object | Evaluates to a CertificateList Control.

Data Type

Long value or constant that specifies an RGB color.

Remarks

The default value is the system color for window background.

Reference the standard Windows controls documentation for information on color usage.


BorderStyle Property

Returns or sets the border style of the control.

Syntax

Object.BorderStyle

Part | Description
Object | Evaluates to a CertificateList Control.

Data Type

BorderStyleConstants


Certificates Property

Collection of Certificate Objects in the store.

Syntax

Object.Certificates

Part | Description
Object | Evaluates to a CertificateStore Object.

Data Type

Certificates Object

Remarks

Read-only.

The Refresh method must be called to populate this collection.


Enabled Property

Returns or sets a value that determines whether the control can respond to user-generated events.

Syntax

Object.Enabled

Part | Description
Object | Evaluates to a CertificateList Control.

Data Type

Boolean

Remarks

The default value is True (respond to events).

When set to True, the CertificateList Control can respond to events. When set to False, the CertificateList Control cannot respond to events.


Font Property

Returns or sets the font used in the display of the control.

Syntax

Object.Font

Part | Description
Object | Evaluates to a CertificateList Control.

Data Type

Font


ForeColor Property

Returns or sets the foreground color used for text.

Syntax

Object.ForeColor

Part | Description
Object | Evaluates to a CertificateList Control.

Data Type

Long value or constant that specifies an RGB color

Remarks

Reference the standard Windows controls documentation for information on color usage.


Gridlines Property

Returns or sets a value the determines if the CertificateList Control displays gridlines in Report View. The default is False (no gridlines).

Syntax

Object.Gridlines

Part | Description
Object | Evaluates to a CertificateList Control.

Data Type

Boolean

Remarks

When set to True, the CertificateList Control displays gridlines. When set to False, the CertificateList Control does not display gridlines.


Height Property

Returns or sets the height of the control.

Syntax

Object.Height

Part | Description
Object | Evaluates to a CertificateList Control.

Data Type

Single


HideColumnHeaders Property

Returns or sets whether ColumnHeader objects in the CertificateList Control are hidden in Report view.

Syntax

Object.HideColumnHeaders

Part | Description
Object | Evaluates to a CertificateList Control.

Data Type

Boolean

Remarks

The default is False (column headers visible).

When set to True, the CertificateList Control column headers are not visible. When set to False, the CertificateList Control column headers are visible.


HotTracking Property

Returns a value that determines whether mouse-sensitive highlighting is enabled.

Syntax

Object.HotTracking

Part | Description
Object | Evaluates to a CertificateList Control.

Data Type

Boolean

Remarks

The default is False (mouse-sensitive highlighting disabled).

When set to True, hot tracking is enabled and the header is highlighted when the user positions the mouse over the header. When set to False, the headers are not highlighted.


hWnd Property

Returns the handle to the window of the CertificateList Control.

Syntax

Object.hWnd

Part | Description
Object | Evaluates to a CertificateList Control.

Data Type

Long

Remarks

Read-only.


KeyUsageSelect Property

Filters out all certificates that do not have the specified KeyUsage attribute.

Syntax

Object.KeyUsageSelect = Value

Part | Description
Object | Evaluates to a CertificateStore Object or a CertificateList Control.
Value | KeyUsageContants enumerated type.

Data Type

KeyUsageContants

Remarks

The default value is UsageAll.

When set to UsageAll, all certificates can be included in the Certificates property of the same object. When set to another value, the Certificates Object (collection) is filled with certificates that possess the specified KeyUsage value.

The Refresh method must be called after setting this property to refresh the Certificates Object.


Left Property

Returns or sets the distance between the internal left edge of the control and the left edge of the form.

Syntax

Object.Left

Part | Description
Object | Evaluates to a CertificateList Control.

Data Type

Single


SelectedIndex Property

Index of the selected certificate.

Syntax

Object.SelectedIndex

Part | Description
Object | Evaluates to a CertificateList Control.

Data Type

Long

Remarks

This property indicates the index into the Certificates property of the selected certificate when read. You can set this property to force a certificate to be selected by default. The property will return -1 if no certificate is selected.


StoreLocation Property

Location of the certificate store.

Syntax

Object.StoreLocation

Part | Description
Object | Evaluates to a CertificateList Control.

Data Type

StoreLocationConstants


StoreName Property

Name of the certificate store.

Syntax

Object.StoreName

Part | Description
Object | Evaluates to a CertificateStore Object.

Data Type

String

Remarks

Some common names are:

Name | Description
"MY" | Personal certificates.
"CA" | Certifying authority certificates.
"ROOT" | Root certificates.
"SPC" | Software publisher certificates.


Top Property

Returns or sets the distance between the internal top edge of the control and the top edge of the form.

Syntax

Object.Top

Part | Description
Object | Evaluates to a CertificateList Control.

Data Type

Single


Width Property

Returns or sets the width of the control.

Syntax

Object.Width

Part | Description
Object | Evaluates to a CertificateList Control.

Data Type

Single


Find Method

Searches the specified certificate store for the specified Certificate and returns the result.

Syntax

Value = Object.Find Name, Location, IssuedBy, SerialNumber

Part | Description
Object | Evaluates to a CertificateStore Object.
Name | String. Name of the certificate store.
Location | StoreLocationConstants. Registry location of the certificate store.
IssuedBy | String. Name of the Certificate Authority that issued/signed the certificate. Matches the IssuedBy property of the returned certificate.
SerialNumber | String. Serial number of the certificate. Matches the SerialNumber property of the returned certificate.
Value | Returned Certificate.

Remarks

This method is used to do a quick lookup of the specified certificate.

Error Codes

The Find method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptNoCertificate (no matching certificate found)


Refresh Method

Populates the Certificates property with the certificates in the store.

Syntax

Object.Refresh

Part | Description
Object | Evaluates to a CertificateStore Object.


Click Event

Fires when the user clicks the left mouse button on the CertificateList Control.

Syntax

Private Sub Object_Click ( )

Part | Description
Object | Evaluates to a CertificateList Control.


DblClick Event

Fires when the user double clicks the left mouse button on the control.

Syntax

Private Sub Object_DblClick ( )

Part | Description
Object | Evaluates to a CertificateList Control.


KeyDown Event

Fires when the user presses a key while the control has focus.

Syntax

Private Sub Object_KeyDown ( KeyCode As Integer, Shift As Integer )

Part | Description
Object | Evaluates to a CertificateList Control.
KeyCode | Integer. Vvirtual key code for the key pressed.
Shift | Integer. Corresponds to the state of the SHIFT, CTRL, and ALT keys when the event fires.

Remarks

The Shift parameter is a bit field with the least-significant bits corresponding to the SHIFT key (bit 0), the CTRL key (bit 1), and the ALT key (bit 2). The number of bits that can be set depends on which keys are pressed.

One or more of the following values are added together to represent Shift combinations (for example, if both SHIFT and CTRL are pressed, Shift is 3):

Constant | Setting | Description
vbShiftMask | 1 | SHIFT key bit mask
VbCtrlMask | 2 | CTRL key bit mask
VbAltMask | 4 | ALT key bit mask


RightClick Event

Fires when the user clicks the right mouse button on the control.

Syntax

Private Sub Object_RightClick ( )

Part | Description
Object | Evaluates to a CertificateList Control.


AppearanceConstants

Enumerates the Appearance property.

Constant | Description
ccFlat | Flat. Paints controls and forms without visual effects.
cc3D | (Default) 3D. Paints control or object with three-dimensional effects.


BorderStyleConstants

Enumerates the BorderStyle property.

Constant | Description
ccNone | None (no border or border-related elements).
ccFixedSingle | Fixed Single.


StoreLocationConstants

Enumerates the possible values of the Location property of the CertificateStore Object:

Value | Constant | Description
0 | locationLocalMachine | Store is located in the HKEY_LOCAL_MACHINE registry key.
1 | locationCurrentUser | Store is located in the HKEY_CURRENT_USER registry key.


Certificates Object

Properties Methods

Collection of Certificate Objects.


Count Property

Number of Certificate Objects in the collection.

Syntax

Object.Count

Part | Description
Object | Evaluates to a Certificates Object.

Data Type

Long

Remarks

Read-only.


Item Method

Get a Certificate Object based on an index.

Syntax

Value = Object.Item Index

Part | Description
Object | Evaluates to a Certificates Object.
Index | Long. Index of the desired Certificate Object.
Value | Certificate Object.


CertificateStore Object

Properties Methods Constants Example

Use the CertificateStore Object to gain access to a store of certificates on the local system. The Certificate Manager Application, included with this product, provides a convenient utility for managing local security certificates.

Miscellaneous

Product | PowerTcp SSL Tool, PowerTcp WebServer Tool, PowerTCP Web Enterprise Tool
Prog ID | Dart.CertificateStore.1
File | DartCertificate.dll
Dependencies | DartSock.dll
Threading | Apartment Model
Licensed | Yes


Location Property

Location of the certificate store.

Syntax

Object.Location

Part | Description
Object | Evaluates to a CertificateStore Object.

Data Type

StoreLocationConstants


Name Property

Name of the certificate store.

Syntax

Object.Name

Part | Description
Object | Evaluates to a CertificateStore Object.

Data Type

String

Remarks

Some common names are:

Name | Description
"MY" | Personal certificates.
"CA" | Certifying authority certificates.
"ROOT" | Root certificates.
"SPC" | Software publisher certificates.


Children Object

The Children Object provides a collection of SecureTCP Objects that have been dynamically created. Each object routes events back to the using application via the SecureServer Control event interface.


Item Method

Returns a SecureTCP object from the collection given an index.

Syntax

Value = Object.Item Index

Part | Description
Object | Object expression that evaluates to a Children Object.
Index | Long.
Value | SecureTCP Object (Control)

Remarks

When specifying Index as a Long, its value must be between one and the collection's Count property.

Error Codes

The Item method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptInvalidParam1 (Index is not a Long between 1 and Count or Index is a Name with no match)


Daemon Control

Properties Methods Events Constants Example

Use the Daemon Control to accept TCP connections.

Whereas the TCP Control can accomplish a single active connection (using the Connect method), the Daemon Control can accept an unlimited number of connections that you can assign to unique TCP Controls for management.

See the Server Control control for an easy-to-use alternative for managing multiple child connections.

Miscellaneous

Product | PowerTCP Winsock Tool
Prog ID | Dart.Daemon.1
File | DartSock.dll
Dependencies | None
Threading | Apartment Model
Licensed | Yes


Accept Method

Accept a connection and pass it to a TCP Control for subsequent connection management. The Listen method must have been previously used to listen for passive connections.

Syntax

Socket = Object.Accept

Part | Description
Object | Object expression that evaluates to a TCP Control.
Socket | Long. Value returned from the Daemon Control.

Remarks

Note Since this process involves relatively complex management of dynamically instantiated connections, you might want to use the Server Control as a "turn-key" server to provide automatic management of all child connections.

Error Codes

The Accept method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptTimeout (no socket was accepted)


Accept Event

Fires when a passive connection occurs. Use the Accept method to get the socket, then transfer it to a TCP Control for management.

Syntax

Private Sub Object_Accept ( )

Part | Description
Object | Evaluates to a Daemon Control.

Remarks

After the Listen method is called to enable passive connections, this event fires as each connection is requested. Each request must be accepted and passed to a TCP Control for management (for sending and receiving data, as well as closing).

Note Since this process involves relatively complex management of dynamically instantiated connections, you might want to use the Server Control as a "turn-key" server to provide automatic management of all child connections.


Item Method

Returns an object from a collection. This is the default method for a collection.

Syntax

Value = Object.Item Index

Part | Description
Object | Object expression that evaluates to a PhoneBookEntries Object.
Index | Long or String. If a Long is specified, it should be a number between 1 and the collection's Count property. If a String is specified, it searches for a matching phonebook entry name.
Value | PhoneBookEntry Object

Error Codes

The Item method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptInvalidParam1 (Index does not resolve to a valid Long or Name)


SecureFtp Control

Properties Methods Events Constants

Use the SecureFtp Control to copy files between a local client and an FTP server that supports the SSL2.0/30, TLS or PICT security protocols. Server-to-server transfers are also supported.

Note File transfers will use all available bandwidth to minimize the time it takes to transfer a file or buffer.

Miscellaneous

Product | PowerTCP SSL Tool
Prog ID | Dart.SecureFtp.1
File | DartSecureFtp.dll
Dependencies | DartSock.dll, DartSecure2.dll, DartCertificate.dll, DartFtp.dll
Threading | Apartment Model
Licensed | Yes


Certificate Property

Example

Certificate Object to use when authenticating to the remote host.

Syntax

Object.Certificate

Part | Description
Object | Evaluates to a control that incorporates secure connections.

Data Type

Certificate Object

Remarks

On the server side, always set this property before enabling the server.

On the client side, this property is typically unused. If the server wants the client to authenticate and this property has not been set, then the Certificate event fires to allow you to set a certificate on demand.


Protocol Property

Example

Specifies the security protocol.

Syntax

Object.Protocol

Part | Description
Object | Evaluates to a control that incorporates secure connections.

Data Type

ProtocolConstants

Remarks

The default value is secureAuto. This is a design-time property.

If the server and the client specify secureAuto, then SSL3 is normally used. If one side uses secureAuto and the other side specifies a protocol, then the protocol specified is used. If the client and server specify protocols that are different, then the Error event will fire with Number=ptProtocol and the connection will be closed.


Authenticate Event

Example

Fires when the remote host has sent a certificate to be authenticated.

Syntax

Private Sub Object_Authenticate ( [ Index As Integer , ] RemoteCertificate As Certificate, TrustedRoot As Boolean, ValidDate As Boolean, ValidSignature As Boolean, Valid As Boolean )

Private Sub Object_Authenticate ( [ Index As Integer , ] Child As SecureTcp, RemoteCertificate As Certificate, TrustedRoot As Boolean, ValidDate As Boolean, ValidSignature As Boolean, Valid As Boolean )

Part | Description
Object | Evaluates to one of the following controls that incorporate secure connections: SecureFtp Control, SecureFtpServer Control, SecurePop Control, SecureServer Control, SecureTcp Control, WebASP Control, WebServer Control.
Index | Integer. Array index if the object is part of an array.
Child | Applies only to the SecureFtpServer Control and the SecureServer Control.
RemoteCertificate | Certificate Object. Remote host's certificate.
TrustedRoot | Boolean. Indicates if the certificate was from a Trusted Root Authority (CA).
ValidDate | Boolean. Indicates if the current date-time is within the certificate's life span.
ValidSignature | Boolean. Indicates if the certificate has a valid signature.
Valid | Boolean. Set this value to True to authenticate the remote certificate or set it to False to deny it.

Remarks

Typically, the remote certificate is rejected if TrustedRoot, ValidDate, or ValidSignature is False. This event allows you to ease or strengthen the restrictions on the remote host's certificate. To authenticate a certificate if one or all of the parameters are False, set Valid to True. You can also deny a certificate if the hostname is not the same as the IssuedTo property of the Certificate.


Certificate Event

Fires when the remote host is requesting a certificate and the Certificate property is not set to a valid Certificate Object.

Syntax

Private Sub Object_Certificate ( )

Part | Description
Object | Evaluates to a control that incorporates secure connections.

Remarks

This event is used to set a certificate on demand. In some cases a server will request that the client authenticate, and it may not be desirable to set the Certificate property unless necessary.


ProtocolConstants

Enumerates values of the Protocol property.

Value | Constant | Description
0 | secureAuto | Automatically negotiate the security protocol.
1 | secureSSL3 | Use SSL 3.0 as the security protocol.
2 | secureSSL2 | Use SSL 2.0 as the security protocol.
3 | securePCT | Use PCT 1.0 as the security protocol.
4 | secureTLS | Use TLS 1.0 as the security protocol.
5 | secureNone | Operate connection in the clear.


SecureFtpServer Control

Properties Methods Events Constants

Use the SecureFtpServer Control to build into your application a fully-functioning standalone or custom secure FTP server. This flexible control provides custom authentication and file system management capabilities yet functions as a powerful FTP server will minimal code.

Miscellaneous

Product | PowerTCP SSL Tool
Prog ID | Dart.SecureFtpServer.1
File | DartSecureFtpServer.dll
Dependencies | DartSock.dll, DartServer.dll, DartFtpUtil.dll, DartSecure2.dll
Threading | Apartment Model
Licensed | Yes


ClientAuthentication Property

Applies to server operation only.

Syntax

Object.ClientAuthentication

Part | Description
Object | Evaluates to a control that incorporates secure connections.

Data Type

Boolean

Remarks

The default value is False.

When set to True, the server requires the client to authenticate before secure communications may proceed.


SecurePop Control

Properties Methods Events Constants Example

Use the SecurePop Control to retrieve mail from a POP3 server that supports the SSL2.0/30, TLS or PICT security protocols. Sets of messages may be retrieved and stored in the Messages property.

Powerful default operations are provided, including iteration through a message set to populate the Messages property.

Miscellaneous

Product | PowerTCP SSL Tool
Prog ID | Dart.SecurePop.1
File | DartSecureMail.dll
Dependencies | DartSock.dll, DartSecure2.dll, DartCertificate.dll, DartMail.dll
Threading | Apartment Model
Licensed | Yes


POP3 Protocol Overview

A session begins when a client establishes a TCP connection with a POP3 server, normally on port 110. Once the connection is established, the server sends a greeting, after which the client and server exchange commands and replies (respectively) until the connection is closed or aborted.

Client commands consist of a case-insensitive keyword, possibly followed by one or more arguments, both in printable ASCII characters and terminated by a CRLF pair. Replies consist of a status indicator ("+OK" or "-ERR") and a keyword possibly followed by additional information terminated by a CRLF pair. Replies may be multi-line in pre-defined cases.

A session progresses through multiple of states during its lifetime. After the connection is created and the server sends the greeting, the session enters the authorization state. In this state the client must identify itself to the server. Once the client has successfully done this, the server acquires resources associated with the client's mail drop, and the session enters the transaction state. Login accomplishes all this.

In the transaction state, the client requests actions of the server. After the client issues the QUIT command (using the Logout method), the session enters the update state. In this state the server releases any resources acquired during the transaction state, removes any deleted messages, and says goodbye. The server closes the connection.

Servers often have an inactivity auto-logout timer. Such a timer will be at least ten minutes in duration. The receipt of any command from the client during that interval generally resets the auto-logout timer. When the timer expires, the session does not enter the update state. The server usually terminates the TCP connection without removing any messages.

A server responds to an unrecognized, unimplemented, or syntactically invalid command by returning a negative status indicator. A server also responds to a command issued when the session is in an incorrect state by returning a negative status indicator.

The following exchange illustrates protocol behavior and how it is invoked using control methods:

S: <waiting for connection on TCP port 110>

Pop1.Login "svr.dart.com", "mrose", "password"

C: <open connection>
S: +OK POP3 server ready <1896.697170952@dbc.mtview.ca.us>
C: USER mrose
S: +OK Password required for mrose.
C: PASS password
S: +OK mrose has 2 messages.
C: STAT
S: +OK 2 320

Pop1.Get msgSize

C: LIST
S: +OK 2 messages (320 octets)
S: 1 120
S: 2 200
S: .

Pop1.Get msgContent, "1"

C: RETR 1
S: +OK 120 octets
S: <the POP3 server sends message 1>
S: .

Pop1.Delete "1"

C: DELE 1
S: +OK message 1 deleted

Pop1.Get msgContent, "2"

C: RETR 2
S: +OK 200 octets
S: <the POP3 server sends message 2>
S: .

Pop1.Delete "2"

C: DELE 2
S: +OK message 2 deleted

Pop1.Logout

C: QUIT
S: +OK dewey POP3 server signing off (maildrop empty)
C: <close connection>

For more detailed information about the POP3 protocol refer to RFC 1939.


SecureServer Control

Properties Methods Events Constants Example

Use the SecureServer Control to quickly build custom server applications that use authentication and encryption. This control has an internal Daemon object and dynamically creates internal SecureTcp objects as each passive connection is automatically accepted.

The SecureServer Control targets high-performance server-side use and consequently relies on non-blocking operation. Applications should only use this control in a non-blocking fashion, as blocking operations (where the SecureTcp object's Timeout property is greater than 0) can cause one session to interfere with others. All events include an object reference as the first parameter so the application can easily reference the SecureTcp object pertaining to the event.

Miscellaneous

Product | PowerTCP SSL Tool
Prog ID | Dart.SecureServer.1
File | DartSecure2.dll
Dependencies | DartSock.dll, DartCertificate.dll
Threading | Apartment Model
Licensed | Yes


Children Property

Returns a collection of secure TCP child connections accepted by the server.

Syntax

Object.Children

Part | Description
Object | Evaluates to a SecureServer Control.

Data Type

Children Object

Remarks

Read-only.


Listen Method

Start listening for passive connections.

Syntax

Object.Listen [ LocalPort ] [ , LocalAddress ] [ , Backlog ]

Part | Description
Object | Object expression that evaluates to a SecureServer Control.
LocalPort | Optional Long between 1 and 65535, inclusive. Defaults to 443 for SSL server operation.
LocalAddress | Optional String. Local interface address to use in dot notation. Not usually specified.
Backlog | Optional Long. Maximum length to which the queue of pending connections may grow. Defaults to the maximum number allowed.

Remarks

If this method fails with a ptAddressInUse error, it is usually due to an application is using the LocalPort specified. You can override this error by setting ReuseAddress to True and calling this method again.

Note You should not use this technique to make two Daemon Controls listening on the same port.

Error Codes

The Listen method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAddressInUse

  • ptInvalidParam1 (LocalPort is not a valid port number)

  • ptNetworkDown

  • ptNoBufferSpace


SecureTcp Control

Properties Methods Events Constants Example

Use the SecureTcp Control to manage streams of data that require security. It simplifies the use of TCP communications by providing methods to establish, send and receive data, and terminate socket-based connections. Client and server authentication, and data encryption / decryption are transparent to the developer. By default, communications will block execution of your program, but you can easily enable non-blocking use for demanding applications that require event-driven communications.

You can use this control to implement upper-layer protocols in a secure way, including protocols of your own creation. You can also use it with the included Daemon Control to build secure server applications.

Miscellaneous

Product | PowerTCP SSL Tool
Prog ID | Dart.SecureTcp.1
File | DartSecure2.dll
Dependencies | DartSock.dll, DartCertificate.dll
Threading | Apartment Model
Licensed | Yes


SecureTcp Control Usage

Developing Secure Clients

  1. Use the SecureTcp Control to set the desired security protocol with the Protocol property.

  2. Connect to a remote secure server (application) and establish a secure connection using the Connect method. If the server requests client authentication and the Certificate property does not reference an installed digital certificate, then the Certificate event will fire to request a certificate. The Authenticate event fires when the server's digital certificate arrives.

  3. Send secure data to the remote application with the Send method.

  4. Receive secure data from the remote application with the Receive, Fill, or Search methods. These methods receive data in slightly different ways, depending upon your requirements.

  5. Close the secure connection with the Close method.

Developing Secure Servers

  1. Use the Daemon Control to listen for incoming connections with the Listen method.

  2. Perform the following within the Daemon's Accept event:

  • Create a SecureTcp Control to manage and negotiate the secure connection.

  • Set its Certificate property to the Certificate Object to use.

  • Set its Protocol property to the security protocol to use.

  • Set its ClientAuthentication property to True if client authentication is desired.

  • Set its Socket property to the value returned from Daemon's Accept method.

  3. Automatically negotiate a secure connection. SecureTcp objects can be created dynamically or as members of an array. Either way, some housekeeping is required to manage all the connections.

  4. Use the SecureTcp Control as described above.

  5. Close the TCP Daemon with the Close method when no more connections are desired.


ProxyType Property

Example

The type of proxy server used for this connection.

Syntax

Object.ProxyType

Part | Description
Object | Evaluates to a PowerTCP Control

Data Type

ProxyTypeConstants

Remarks

Read this property to determine what type of proxy server is currently being used.

Write to this property to set the type of proxy server used for the next connection.

When the proxy is a CERN type proxy, then ProxyType should be set to none and the other proxy properties should be set accordingly.


Security Property

Example

Sets the security level during communication.

Syntax

Object.Security

Part | Description
Object | Evaluates to a PowerTCP Control.

Data Type

WebSecurityConstants if using the WebASP Control

SecurityConstants if using the SecureTCP Control

Remarks

This property enables variable security settings, from absolute certificate confirmation to no security.


Socket Property

System identifier assigned to the TCP connection. It is normally used to assume management of a socket accepted from the Daemon Control.

Syntax

Object. Socket

Part | Description
Object | Evaluates to a SecureTcp Control.

Data Type

Long

Remarks

This property is only available at run time. A value of –1 indicates that no system resource is currently allocated. When this property is set, the SecureTcp Control initiates a secure negotiation with the client. The State event immediately fires to indicate that the State has changed to tcpConnecting before returning. The State event fires later to indicate that the State has changed to tcpConnected after protocol negotiation and authentication has succeeded. See the Accept method for additional information.

If Protocol specifies a security protocol and the client does not support that protocol, then the Error event fires with Number=ptProtocol and Description="Security protocol negotiation failed." The State event fires twice as the State changes to ptClosing and ptClosed, respectively.

If Certificate does not reference a valid digital certificate then an error will be returned to the container with Number=ptNoCertificate and Description="There was an error in creating credentials." Typically this means the digital certificate referenced by Certificate could not be found. The State event fires twice as the State changes to ptClosing and ptClosed, respectively.

If ClientAuthentication is True and the client does not authenticate then the Error event fires with Number= ptAuthentication and Description="The client could not be authenticated." The State event fires twice as the State changes to ptClosing and ptClosed, respectively.

The Timeout Property is automatically set to 0 when Socket is set, because server operation requires event-driven communications for best results. You should not set Timeout to a positive number.

Error Codes

The Socket property may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAuthenticate

  • ptInvalidParam1 (assigned value is not a valid system socket identifier)

  • ptNoCertificate (Certificate does not reference a valid digital certificate)

  • ptProtocol


Connect Method

Establish a secure connection. The State immediately changes to tcpConnecting and changes to tcpConnected when the connection is established, the security protocol is negotiated and authentication succeeds. The State can be checked in the body of the State Event, polled off a timer, or checked immediately after this method is used when a positive Timeout is specified.

Syntax

Object.Connect RemoteName [ , RemotePort] [ , LocalName ] [ , LocalPort ]

Part | Description
Object | Evaluates to a SecureTcp Control.
RemoteName | String. Specifies either a host name (host.dart.com) or dot address (nnn.nnn.nnn.nnn).
RemotePort | Optional Long. Specifies a remote port between 1 and 65535, inclusive. Defaults to 443.
LocalName | Optional String. Specifies the local network interface (either a host name, host.dart.com, or dot address, nnn.nnn.nnn.nnn). Not usually used.
LocalPort | Optional Long. Species the local port. Not usually used.

Remarks

This method initiates a connection and a secure negotiation with a secure server. This method blocks if Timeout is greater than 0. The Blocked Property may be checked to verify the control is not executing another method.

If Protocol specifies a security protocol and the server does not support that protocol, then the Error event fires (and an error will be returned if Timeout is greater than 0) with Number=ptProtocol and Description="Security protocol negotiation failed." The State event fires twice as the State changes to ptClosing and ptClosed, respectively.

If the server requests authentication and Certificate does not reference a valid certificate (by the time the Certificate Event returns) then the Error event fires (and an error will be returned if Timeout is greater than 0) with Number=ptNoCertificate and Description="There was an error in creating credentials." Typically this means the digital certificate referenced by Certificate could not be found. If the server closes the connection the State event fires twice as the State changes to ptClosing and ptClosed, respectively.

If the server does not authenticate then the Error event fires (and an error will be returned if Timeout is greater than 0) with Number= ptAuthentication and Description="The server could not be authenticated." The State event fires twice as the State changes to ptClosing and ptClosed, respectively.

Error Codes

The Connect method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1 (RemoteName is not a valid string)

  • ptAbort

  • ptAddressInUse

  • ptAddressNotAvailable

  • ptAuthentication

  • ptBlocked

  • ptConnectionRefused

  • ptHostNotFound

  • ptInvalidParam2 (RemotePort is not between 1 and 65535, inclusive)

  • ptNetworkDown

  • ptNetworkUnreachable

  • ptNoBufferSpace

  • ptNoCertificate

  • ptNoData

  • ptNotInitialized

  • ptProtocol

  • ptTimeout

  • ptTryAgain


ProxyTypeConstants

Value | Constant | Description
0 | ptProxyNone | No proxy server. Straight connection.
1 | ptProxySocks4 | Uses a SOCKS V4 Proxy.
2 | ptProxySocks5 | Uses a SOCKS V5 Proxy.


SecurityConstants

Value | Constant | Description
0 | secureNormal | Apply all server certificate checks.
1 | secureIgnoreCertificate | Accept all certificates passed from the server.
2 | secureIgnoreDate | Accept otherwise valid certificate if date has expired.
4 | secureIgnoreUntrustedRoot | Accept otherwise valid certificate if Certificate Authority Root is not known.
8 | secureIgnoreSignature | Accept otherwise valid certificate if signature cannot be verified.


PowerTCP SNMP Tool

PowerTCP SNMP Tool version 2

Support Licensing Distribution Protocol Overview

Put the "simple" back into Simple Network Management Protocol. The SNMP Tool contains a SnmpMessage Object that converts an SNMP message packet into an object (that your program can easily manipulate), and back again. The other objects apply the SnmpMessage Object to typical applications such as Agent and Manager functionality, and appropriately integrate it with the UDP transport. Includes robust table support and comprehensive SNMP compliance.

Control | Description
SNMP Agent Control | "Drop-in" SNMP agent
SNMP Manager Control | "Drop-in" SNMP manager
Service Control | Turn your Agent application into an NT service

Note This tool is not dependent upon ANY system support besides normal Winsock communications, so you can have SNMP functionality without any Microsoft SNMP service present.

Supporting Objects

Object | Description
SnmpMessage Object | Encodes and decodes SNMP packets.
SnmpMib Object | Compiles standard MIB files into an object representation.
SnmpTable Object | Collection of SnmpTableRow Objects.
SnmpTableRow Object | Collection of SnmpVariable objects in a table.
SnmpTrap Object | Provides information about traps found in the MIB.
SnmpTraps Object | Collection of SnmpTrap Objects
SnmpVariable Object | Provides variable bindings for OIDs.
SnmpVariables Object | Collection of SnmpVariable Objects.

Sample Projects

The following sample projects demonstrate how to use the SNMP Tool:

Sample Project | Description
MIB Viewer | Allows user to read a MIB file and browse the contents in human readable form. Visual Basic 6 and Visual C++.
SNMP Agent | Includes service support (NT only). Visual Basic 5/6, Delphi 4, PowerBuilder 6, Visual C++ (service support not added for VC++).
SNMP Explorer | Uses the TreeView control to create an explorer-like view of available SNMP Agents. Visual Basic 5/6 and Visual C++.
SNMP Manager | Supports queries for basic variables, either by discovery or specific address. Also shows how to set values. Visual Basic 5/6, Delphi 4, and PowerBuilder 6.
TableBrowser | Demonstrates browsing of SNMP Tables using the SnmpTable and SnmpTableRow Objects. Visual Basic 6
TrapCatcher | Service that listens for and logs traps. Visual Basic 6 and Visual C++. Database that listens for and stores traps. Access 97.
VarChecker | Allows users to construct a request from a list of available MIBs and view the response. Visual Basic 5/6 and Visual C++.

Online ASP Samples

These ASP samples demonstrate the use of the SNMP Tool on the Internet. You must have an active Internet connection to view these Samples.

Sample

Description

SNMP Manager on the Web

The SnmpManager Control queries and set values on any SNMP Agent


SNMP Protocol Overview

This topic covers:

  • Protocol Overview

  • Get/Set/Inform Messages

  • Version 1 Trap Message

  • Version 2 Trap Message

  • Additional Information

Protocol Overview

SNMP supports basic network monitoring and management functions between a management station and managed nodes through applications located on the nodes, called agents.

An agent maintains a database of information (Management Information Base or MIB) about managed nodes and when queried by the manager, retrieves data from the database and sends it to the manager in a response.

SNMP over TCP/IP uses UDP messages as transport for queries and responses, as well as for traps. Traps are sent to the management station when certain events occur, such as when a node comes up or is shut down. All information values are identified using a notation called Abstract Syntax Notation One (ASN.1); a typical Object ID (OID) might be 1.3.6.1.2.1.4.21 (ipRouteTable).

The following drawing illustrates a manager and an agent:

Seven types of messages are exchanged between managers and agents:

Message | Description
GetRequest | Requests the value of one or more objects from an agent's MIB. Required properties are Type, Community, and a collection of SnmpVariable Objects with the Oid property initialized with each OID for which information is requested. The agent usually uses the "well-known" SNMP port 161. Version 1 and 2 packets have the same format.
GetNextRequest | Requests the next entry of one or more objects from a table in an agent's MIB. Similar to GetRequest.
InformRequest | Information sent by one manager to another. Required properties are Type, Community, and a collection of SnmpVariable Objects with the Oid, Type, and Value properties initialized. Version 2 only.
SetRequest | Sets the value of one or more objects in an agent's MIB. Required properties are Type, Community, and a collection of SnmpVariable Objects with the Oid, Type, and Value properties initialized. Version 1 and 2 packets have the same format.
Response | Returns the value of one or more objects in response to a manager's GetRequest, GetNextRequest, SetRequest or InformRequest. Required properties are Type, Community, and a collection of SnmpVariable Objects with the Oid, Type, and Value properties initialized. Version 1 and 2 packets have the same format.
GetBulkRequest | Similar to GetRequest, except that if the Repeat property of the referenced SnmpVariable Object is positive, then up to MaxRepetition variables are returned. Version 2 only.
Traps | Notifies managers when an event occurs on an agent. Required properties are Type, Community, Enterprise, GenericTrap, SpecificTrap, UpTime, and a collection of SnmpVariable Objects with the Oid, Type, and Value properties initialized.

The manager can use any port for initiating a GetRequest, GetNextRequest, InformRequest, GetBulkRequest or SetRequest. The agent always replies to the source address of the message. In the case of a SetRequest, a Response message is used to confirm the updated information on the agent. For Traps, the Manager has port 162 open (or uses some other port that the agent is configured to use). Agents are configured to send trap messages to managers according to local operating procedures. It is possible (but not necessary) for a manager to use port 162 for all GetRequest, GetNextRequest, InformRequest, GetBulkRequest and SetRequest messages, and receive both Response and Trap messages on the same port.

Back to Top

Get/Set/Inform Messages

A message consists of a header and variables. The variables are a sequence of name-value pairs that represents the elements being requested or responded to. Figure 1 illustrates an example of a message of this type:

Header/Variable | Description
Version | SNMP version used to create the message.
Community | Clear-text string that contains the community name for the message. Typically this is used as a password between the manager and agent.
PDU Type | Type of message. Possible values are GetRequest, GetRequest, GetNextRequest, SetRequest, and Response. For version 2 messages this field may also contain GetBulkRequest and InformRequest.
Request ID | Unique ID assigned by the manager to match requests to responses.
ErrorStatus (Exception) | Represents the error status of the message. This is used in Response messages only. For GetRequest, GetNextRequest, GetBulkRequest, InformRequest and SetRequest this field is ignored.
ErrorIndex (ExceptionIndex) | Indicates which variable caused the request to fail. This is used for Response messages only. For GetRequest, GetNextRequest, GetBulkRequest, InformRequest and SetRequest this field is ignored.
Variable Bindings (Variables) | Sequence of name-value pairs representing data that is requested or returned. On a request the values are ignored and on a response the values are set.

Back to Top

Version 1 Trap Message

Figure 2 illustrates a Version 1 Trap message.

Header/Variable | Description
Version | SNMP version used to create the message.
Community | Clear-text string that contains the community name for the message. Typically this is used as a password between the manager and agent.
PDU Type | Type of message. Value is snmpTrap1.
Enterprise | OID of the object that generated the trap.
Agent Addr | IP address of the agent that generated the trap. Since this is redundant with the source address of the UDP packet, its use was discontinued with Version 2 Traps. PowerTCP does not support it as an SnmpMessage Object property (the UDP Receive method provides this information).
Trap Type (GenericTrap property) | Type of trap that the message represents. The possible values are enumerated by TrapConstants.
Specific Code (SpecificTrap property) | Contains specific information about a trap.
Time Stamp (UpTime property) | Time elapsed in 1/100ths of seconds between the (re)start of the agent and the time the trap was generated.
Variable Bindings (Variables) | Sequence of name-value pairs representing data that is requested or returned.

Back to Top

Version 2 Trap Message

A Version 2 Trap message follows the format of the Response message illustrated in Figure 1 with the Type property set to snmpTrap2. The first variable in the variable bindings is the UpTime and the second variable is the OID of the object that generated the trap.

Back to Top

Additional Information

Refer to the following for detailed information about SNMP and its applications:

SNMP Version 1: RFC1155, RFC1157, and RFC1213.

SNMP version 2: RFC1901, RFC1902, RFC1903, RFC1904, RFC1905, RFC1906, RFC1907, and RFC1908.

Stallings, William, SNMP, SNMPv2, and CMIP: The Practical Guide to Network-Management Standards, Addison-Wesley Publishing Company 1994

Stallings, William, SNMP, SNMPv2, and RMON: Practical Network Management, Second Edition, Addison-Wesley 1996

Back to Top


Agent Control

SNMP Agent Control

Properties Methods Events Example

Use the Agent Control to build Simple Network Management Protocol (SNMP) agents. The Agent Control provides an easy-to-use interface, and in most cases will handle all details of processing and responding to a manager's request. Simply set the Auto property to True and all Get/Set requests will be processed and responded to appropriately. The agent can accept requests from both SNMP version 1 and version 2 managers.

Miscellaneous

Product | PowerTCP SNMP Tool
Prog ID | Dart.Agent.1
File | DartSnmp2.dll
Dependencies | DartSock.dll
Threading | Apartment Model
Licensed | Yes


Agent Control Usage

The following code snippet demonstrates how to respond to a snmpGetNext1 or snmpGetNext2 request and how to implement a table:

Private Sub Agent1_Request()

Dim Variable As SnmpVariable

Dim PhysAddr As String * 6

Dim i As Integer

If (Agent1.Message.Type = snmpGetNext1) Or (Agent1.Message.Type = snmpGetNext2) Then

i = 1

Agent1.Message.Type = snmpResponse1

For Each Variable In Agent1.Message.Variables

Select Case Variable.Oid

Case "1.3.6.1.2.1.3.1.0" 'first value in at table

Variable.Type = snmpInteger

Variable.Value = 1

Variable.Oid = "1.3.6.1.2.1.3.1.1.1.1.1." + Agent1.LocalAddress

Case "1.3.6.1.2.1.3.1.1.1.1.1." + Agent1.LocalAddress

Variable.Type = snmpInteger

Variable.Value = 1

Variable.Oid = "1.3.6.1.2.1.3.1.1.1.1.1.16.1.0.8"

Case "1.3.6.1.2.1.3.1.1.1.1.1.16.1.0.8"

Variable.Type = snmpOctetString

PhysAddr = Chr(1) & Chr(5) & Chr(198) & Chr(55) & Chr(0) & Chr(19)

Variable.Value = PhysAddr

Variable.Oid = "1.3.6.1.2.1.3.1.1.2.1.1." + Agent1.LocalAddress

Case "1.3.6.1.2.1.3.1.1.2.1.1." + Agent1.LocalAddress

Variable.Type = snmpOctetString

PhysAddr = Chr(1) & Chr(5) & Chr(167) & Chr(67) & Chr(0) & Chr(17)

Variable.Value = PhysAddr

Variable.Oid = "1.3.6.1.2.1.3.1.1.2.1.1.16.1.0.8"

Case "1.3.6.1.2.1.3.1.1.2.1.1.16.1.0.8"

Variable.Type = snmpIpAddress

Variable.Value = Agent1.LocalAddress

Variable.Oid = "1.3.6.1.2.1.3.1.1.3.1.1." + Agent1.LocalAddress

Case "1.3.6.1.2.1.3.1.1.3.1.1." + Agent1.LocalAddress

Variable.Type = snmpIpAddress

Variable.Value = "16.1.0.8" 'some bogus IP address

Variable.Oid = "1.3.6.1.2.1.3.1.1.3.1.1.16.1.0.8"

Case "1.3.6.1.2.1.3.1.1.3.1.1.16.1.0.8"

Variable.Type = snmpInteger

Variable.Value = 1

Variable.Oid = "1.3.6.1.2.1.4.1.0"

Case Else

Agent1.Message.Exception = snmpNoSuchName

Agent1.Message.ExceptionIndex = i

Agent1.Send

End Select

i = i + 1

Next

Agent1.Send

End If

End Sub


AgentUptime Property

Elapsed time the Agent has been active.

Syntax

Object.AgentUptime

Part | Description
Object | Evaluates to an Agent Control.

Data Type

Long

Remarks

Read-only.

The time (in hundredths of a second) that has elapsed after the (re)start of the agent. This is used to automatically set the SnmpMessage Object UpTime property when sending if the UpTime is 0. This value will roll over every 16 months if the Agent stays active that long, as per the SNMPv2 standard.


Auto Property

Enables the automatic processing of all received Get/Set requests.

Syntax

Object.Auto

Part | Description
Object | Evaluates to an Agent Control.

Data Type

Boolean

Remarks

The default value is True. The property can be set at design time.

When set to True, the control transparently handles all Get/Set requests and sends out a warm startup trap when the Open method is called.

Only Get/Set requests are automatically handled. Messages of Type snmpGetNext1, snmpGetNext2 and snmpGetBulk2 are not automatically responded to, so you must place code within the Request event to handle these requests.

The Request and Response events continue to fire when this property is set to True, so your application can monitor all activity.


Community Property

Community name to which the agent belongs.

Syntax

Object.Community

Part | Description
Object | Evaluates to an Agent Control.

Data Type

String

Remarks

The default value is "public". This property can be set at design time.

When Auto is True, all requests are authenticated using this property. If Auto is True and a request is received, the control compares the Community property of the message with this property. If they match, then the request is processed and responded to; if they do not match, then an authentication trap is sent to each manager in the TrapManagers property.

Note This property is not used if Auto is False.


ManagerName Property

Name (hostname or IP address in dot notation) of the SNMP manager associated with the Message property.

Syntax

Object.ManagerName

Part | Description
Object | Evaluates to an Agent Control.

Data Type

String

Remarks

This property can be set only at run time. It holds the:

  • Source IP address of the manager's request when the Request event fires.

  • Destination IP address or hostname for the agent's response when the Response event fires.


ManagerPort Property

Port of the SNMP manager associated with the Message property.

Syntax

Object.ManagerPort

Part | Description
Object | Evaluates to an Agent Control.

Data Type

Long

Remarks

This property can be set only at runtime. It holds the:

  • Source port of the manager's request when the Request event fires.

  • Destination port for the agent's response when the Response event fires.


Message Property

Current SnmpMessage Object.

Syntax

Object.Message

Part | Description
Object | Evaluates to an Agent Control or a Manager Control.

Data Type

SnmpMessage Object


Mib Property

SnmpMib Object used for storing the Management Information Base (MIB).

Syntax

Object.Mib

Part | Description
Object | Evaluates to an Agent Control.

Data Type

SnmpMib Object

Remarks

Use this property to set and get values in the agent's MIB. When set, the existing object is released and the reference count of the object being assigned is incremented. If Auto is True, the values for a Get request are taken from this object. Set requests update the values in this object. Refer to the SnmpMib Object for information on directly setting and getting values.

The application can save this information for later use by assigning it to a new object, as shown in the Mib Property Example.


SendDatagramCount Property

Number of datagrams queued for sending.

Syntax

Object.SendDatagramCount

Part | Description
Object | Evaluates to a UDP Control.

Data Type

Long

Remarks

Read-only.

Datagrams are queued while the remote host name is asynchronously resolved or when the system does not have sufficient buffer space. For this reason it is possible for datagrams to be sent out over the wire in a different order than submitted by the Send method.


TrapManagers Property

Collection of remote names and ports of managers that will receive trap messages.

Syntax

Object.TrapManagers

Part | Description
Object | Evaluates to an Agent Control.

Data Type

DartStrings Object

Remarks

This property can be set to any existing DartStrings Object. The format of the hostname / port pair is "Name:Port", where "Name" can be a hostname or IP address in dot notation and ":Port" defaults to the SNMP Trap "well-known" port of 162 if it is omitted.

This property is used when:

  • Auto is True and the control generates a trap. The trap will be sent to each manager in this collection.

  • The Send method is invoked and the Type property of the SnmpMessage Object is snmpTrap1 or snmpTrap2. The trap message is sent to each manager in this collection.


Close Method

Release system resources.

Syntax

Object.Close

Part | Description
Object | Object expression that evaluates to an Agent Control, Manager Control, or UDP Control.

Remarks

If you specify a Timeout, this method blocks while attempting to send any queued packets. After all queued packets have been sent (or the Timeout period has expired), the socket and all system resources are released. If no Timeout is specified, then all queued packets and system resources are immediately released.

If Blocked and you wish to cancel the method and release resources, use the Abort method. Using Close when another method is blocking results in a ptBlocked error.

Error Codes

The Close method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptBlocked (the Blocked property is True)


Open Method

Allocate a socket for sending and receiving datagrams.

Syntax

Object.Open [ LocalPort ] [ , LocalAddress ]

Part | Description
Object | Object expression that evaluates to a PowerTCP control.
LocalPort | Optional Long. Specifies the port desired.
LocalAddress | Optional String. Specifies the address interface desired.

Remarks

LocalPort defaults to 0, which indicates to the system that it should assign an unused (ephemeral) port.

If Object is an SNMP Agent control, you will normally use the well-known port 161. If this port is not used, then managers must be configured to use the port you specify.

If Object is an SNMP Manager control, you can use the well-known port 162 (so a single port can be used for both normal messaging and traps). If 0 is used, then you will not be able to receive traps (because agent applications will not normally know what port to send them to).

Upon success, the address used can be read from the LocalAddress property and the port used can be read from the LocalPort property.

Error Codes

The Open method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAddressInUse

  • ptInvalidParam1 (LocalPort is not between 0 and 65535, inclusive)

  • ptInvalidParam2 (LocalAddress is not a valid address string in dot notation, for example, "204.7.222.2")

  • ptNetworkDown

  • ptNoBufferSpace

  • ptNotInitialized


Send Method

Encode and send an SNMP message.

Syntax

Object.Send

Part | Description
Object | Object expression that evaluates to an SNMP Agent Control or an SNMP Manager Control.

Remarks

The Open method must be used to open a socket prior to using this method (the LocalPort property must not be 0).

Set values in the Message and related properties, then use this method to encode the message and send it.

If Object is a Manager Control, then a non-zero Timeout causes this method to block (the Blocked property returns True) until the agent responds or a timeout occurs. Set the contents of the Message, AgentName, and AgentPort properties and send a message.


Request Event

Fires when an SNMP request arrives. Use the Message, ManagerName and ManagerPort properties to obtain the decoded message and its source.

Syntax

Private Sub Object_Request ( [ Index As Integer ] )

Part | Description
Object | Evaluates to an Agent Control.
Index | Integer. Array index if the object is part of an array.

Remarks

This event fires before any automatic handling of the message occurs (Auto is True). It is possible to alter the message by changing the contents of the Message property before the message is automatically processed. Altering the contents of the message before automatic processing is only recommend for advanced users, since this can have unintended side effects.

Any message that is not handled by the control (the Type property is snmpNext1, snmpNext2 or snmpGetBulk2) must be responded to within this event.


Response Event

Fires immediately before a response is encoded and sent to a manager. Use the Message, ManagerName, and ManagerPort properties to obtain the decoded message and its destination.

Syntax

Private Sub Object_Response ( [ Index As Integer ] )

Part | Description
Object | Evaluates to an Agent Control.
Index | Integer. Array index if the object is part of an array.

Remarks

This event provides the application with a preview of the message just before it is encoded and sent. It is generated each time the Send method is used, either explicitly by the application or implicitly when Auto is True and a request is received with a Type property of snmpGet1, snmpGet2, snmpSet1 or snmpSet2.

It is possible to alter the message by changing the contents of the Message property. Changing the ManagerName property or the ManagerPort property can also alter the destination of the message. This is recommended for advanced users only, since altering the message and destination can have side effects.


Manager Control

SNMP Manager Control

Properties Methods Events Example

Use the Manager Control to build Simple Network Management Protocol (SNMP) managers. This control handles the underlying details of the SNMP protocol, allowing you to focus on the user interface.

Miscellaneous

Product | PowerTCP SNMP Tool
Prog ID | Dart.Manager.1
File | DartSnmp2.dll
Dependencies | DartSock.dll
Threading | Apartment Model
Licensed | Yes


Manager Control Usage

The following code snippet demonstrates requesting a variable from an agent:

Private Sub GetVariable_Click()

Dim Variable As New SnmpVariable

Manager1.Message.Type = snmpGet1

Variable.Oid = "1.3.6.1.2.1.1.1.0" 'Get sysDescr Value

Manager1.Message.Variables.Add Variable

'port defaults to 161

Manager1.AgentName = "agent.dart.com"

Manager1.Send

End Sub

The following code snippet demonstrates displaying the values of a response:

Private Sub Manager1_Response()

Dim Variable As SnmpVariable

If Manager1.Message.Exception = snmpOk Then

For Each Variable In Manager1.Message.Variables

List1.AddItem Variable.Value

Next

Else

MsgBox "Error in variable: " & Manager1.Message.ExceptionIndex

End If

End Sub


AgentName Property

Name (hostname or IP address in dot notation) of the SNMP agent associated with the Message property.

Syntax

Object.AgentName

Part | Description
Object | Evaluates to an SNMP Manager Control.

Data Type

String

Remarks

This property can be set at design time. It is the:

  • Destination IP address or name of the manager's request when the Send method is used.

  • Source IP address of the agent's response when the Response event fires.


AgentPort Property

Port number used by the SNMP agent associated with the Message property.

Syntax

Object.AgentPort

Part | Description
Object | Evaluates to an SNMP Manager Control.

Data Type

Long

Remarks

This property can be set at design time, and it defaults to the SNMP agent "well-known" port of 161. It is the:

  • Destination port of the manager's request when the Send method is used.

  • Source port of the agent's response when the Response event fires.


AgentVariable Property

Make a single variable Get/Set request. Set the property to a value, and a request of type snmpSet1 executes. Assign the property to a variable, and a request of type snmpGet1 executes. In both cases, execution blocks until confirmation is received from the agent.

Syntax

[ Value = ] Object.AgentVariable ( Oid As String ) [ = Value ]

Part | Description
Object | Object expression that evaluates to an SNMP Manager Control.
Oid | String expression. Represents the OID of the object to Set/Get.
Value | SnmpVariable Object. Represents the variable on the agent.

Data Type

SnmpVariable Object

Remarks

This property can only be read or set after calling the Open method (the LocalPort property must not be 0).

If Timeout is 0, a default value of 30 seconds is used.

Error Codes

The AgentVariable property may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAddressInUse

  • ptInvalidParam1 (Oid is not a valid OID)

  • ptNetworkDown

  • ptNoBufferSpace

  • ptNotInitialized

  • ptProtocol (Exception property of message is not snmpOk)


Response Event

Fires after a response has been received and decoded into the Message property. Use the Message, AgentName, and AgentPort properties to obtain the decoded message and its source.

Syntax

Private Sub Object_Response ( [ Index As Integer ] )

Part | Description
Object | Evaluates to a Manager Control.
Index | Integer. Array index if the object is part of an array.


Send Event

Fires when the system accepts a datagram for transmission.

Syntax

Private Sub Object_Send ( [ Index As Integer ] )

Part | Description
Object | Evaluates to a Manager Control or a UDP Control.
Index | Integer. Array index if the object is part of an array.

Remarks

Each time the Send method is used, data can be queued while the RemoteName is resolved or the system buffers are temporarily full. Between the time the Send method is called and this event fires, SendDatagramCount has a positive value that indicates how many datagrams are currently in this queue. This event fires every time SendDatagramCount decreases in value because the system has accepted more data.

WARNING Timeout must be 0 when calling methods from within an event. Failure to observe this rule may cause reentrancy problems and unpredictable results.


Trap Event

Fires after a trap message has been received from an agent and decoded into the Message property. Use the Message, AgentName, and AgentPort properties to obtain the decoded message and its source.

Syntax

Private Sub Object_Trap ( [ Index As Integer ] )

Part | Description
Object | Evaluates to a Manager Control.
Index | Integer. Array index if the object is part of an array.


SnmpMessage Object

Properties Methods Constants Example

Use the Simple Network Management Protocol (SNMP) Message Object to perform complex encoding and decoding of SNMP messages. Received messages, when decoded, populate an SnmpMessage Object that your application can easily manipulate. Conversely, your application can build any SnmpMessage Object and encode it into a message that is ready to send over the network.

PowerTCP supports SNMP versions 1 and 2. See TypeConstants.

Miscellaneous

Product | PowerTCP SNMP Tool
Prog ID | Dart.SnmpMessage.1
File | DartSnmp2.dll
Dependencies | DartSock.dll
Threading | Apartment Model
Licensed | Yes


SnmpMessage Object Usage

Simple SNMP Agent Simple SNMP Manager

The SnmpMessage Object functions as a formatting tool that converts any SNMP Version 1 or Version 2 (encoded) message into an object model that your application can easily manipulate. It is also used to build messages from your object model. When the Decode method is used, the object model is dynamically created from the SNMP message presented. When the Encode method is used, a message is dynamically created from the object model.

Since the SnmpMessage Object only provides message formatting, it can be used to build both SNMP agents and managers. A complete description of agent / manager operation is beyond the scope of this documentation, but the following sections use some simple code snippets to show how easy SNMP applications can be written.


Community Property

Community name for an SnmpMessage Object.

Syntax

Object.Community

Part | Description
Object | Evaluates to an SnmpMessage Object.

Data Type

String

Remarks

The default value is "public".

The community name is often used as a pseudo-password (for example, "public" or "private"). For requests it must match the community name on the agent. For responses it must match the community name on the manager.


Enterprise Property

Example

Object Identifier (OID) of the network management subsystem that generated the trap.

Syntax

Object.Enterprise

Part | Description
Object | Evaluates to an SnmpMessage Object.

Data Type

String

Remarks

This value is taken from the sysObjectID in the System group, and is only used when the Type property is snmpTrap1.


Exception Property

Exception for the message.

Syntax

Object.Exception

Part | Description
Object | Evaluates to an SnmpMessage Object.

Data Type

ExceptionConstants

Remarks

The default value is snmpOk.

Set this property before encoding to indicate an error. Inspect this property after decoding to determine if an error occurred.

Set this property to indicate that an error occurred while processing a request. For example, a manager may request a variable that is not supported by the agent. In that case this property should be set to snmpNoSuchName to indicate to the manager that the variable does not exist.

If a version 1 message and this property is not snmpOk, then the Value property of each SnmpVariable Object is left empty. If a version 2 message and this property is not snmpOk, then the Value property of each successfully processed variable can be set.


ExceptionIndex Property

Indicates the variable that caused an exception.

Syntax

Object.ExceptionIndex

Part | Description
Object | Evaluates to an SnmpMessage Object.

Data Type

Long

Remarks

A manager receiving a message with an ExceptionIndex of 1 would know that the first variable object in the Variables property caused an exception.


GenericTrap Property

General type of trap represented by the SNMP message.

Syntax

Object.GenericTrap

Part | Description
Object | Evaluates to an SnmpMessage Object.

Data Type

TrapConstants

Remarks

A trap is sent by an agent to a manager to notify the manager of a specific event. This property is used only when the Type property is snmpTrap1.


Id Property

Request ID of the message used to distinguish between responses.

Syntax

Object.Id

Part | Description
Object | Evaluates to an SnmpMessage Object.

Data Type

Long

Remarks

The default value is 0.

This is a handshaking value used to match a request message with a response message. It is useful when sending multiple requests to an agent, so each response can be matched to a corresponding request.


MaxRepetition Property

Maximum repetition for each repeating variable in the message.

Syntax

Object.MaxRepetition

Part | Description
Object | Evaluates to an SnmpMessage Object.

Data Type

Long

Remarks

This property is used when sending and receiving messages of Type snmpGetBulk2. For each Variable Object in the Variables property with a True Repeat property, there are up to this many GetNext requests for the variable.


SpecificTrap Property

Enterprise-specific type of trap represented by the message.

Syntax

Object.SpecificTrap

Part | Description
Object | Evaluates to an SnmpMessage Object.

Data Type

Long

Remarks

This property is used only when Type is snmpTrap1, GenericTrap is snmpEnterpriseSpecific, and a trap type other than the generic trap types defined by TrapConstants must be indicated.


Type Property

SNMP version and type of operation represented by the message.

Syntax

Object.Type

Part | Description
Object | Evaluates to an SnmpMessage Object.

Data Type

TypeConstants

Remarks

Set this property to indicate the type of message to encode. Inspect this property to determine the type of message the object represents.


UpTime Property

Elapsed time the Agent has been active.

Syntax

Object.UpTime

Part | Description
Object | Evaluates to an SnmpMessage Object.

Data Type

Long

Remarks

The time (in hundredths of a second) that has elapsed between the (re)start of the agent and the time the trap message was generated. Only used when Type is snmpTrap1. If left 0 then this field is automatically generated when the packet is encoded, and then set back to 0.


Variables Property

Collection of SnmpVariable Objects included in the message.

Syntax

Object.Variables

Part | Description
Object | Evaluates to an SnmpMessage Object.

Data Type

SnmpVariables Object

Remarks

Read-only.

This property is used to read received variables and create variables to send.


Decode Method

Decode an SNMP message and initialize the SnmpMessage Object.

Syntax

Object.Decode Message

Part | Description
Object | Object expression that evaluates to an SnmpMessage Object.
Message | Byte array. Holds the message to be decoded.

Remarks

To decode a message into an SnmpMessage Object, pass the received (encoded) datagram to this method. The existing properties are replaced with values that represent the message presented.


Encode Method

Encode the SnmpMessage Object into a transport-ready SNMP message.

Syntax

Object.Encode Message

Part | Description
Object | Object expression that evaluates to an SnmpMessage Object.
Message | Byte array for the encoded message. Resized as needed.

Remarks

To encode a message prior to sending, set the properties of the SnmpMessage Object to the desired values and use this method to encode the message.


Reset Method

Clear the Variables property and reset all properties to default values.

Syntax

Object.Reset

Part | Description
Object | Object expression that evaluates to an SnmpMessage Object.


ExceptionConstants

Enumerates values of the Exception property.

Value | Constant | Description
0 | snmpOk | No exception.
1 | snmpTooBig | The response generated is too big for the local limitations of the agent.
2 | snmpNoSuchName | The OID can not be found in the agents MIB.
3 | snmpBadValue | The value is not appropriate for the variable being set.
4 | snmpReadOnly | The variable can only been read.
5 | snmpGeneralError | An error occurred.
6 | snmpNoAccess | No such variable or no access to the variable.
7 | snmpWrongType | The type of the value being set does not match the type of the variable on the agent.
8 | snmpWrongLength | The length of the value exceeds the maximum length of the possible values of the variable.
9 | snmpWrongEncoding | Error in the encoding of a variable.
10 | snmpWrongValue | The value could not be assigned to the agents variable.
11 | snmpNoCreation | The variable can not be created on the agent.
12 | snmpInconsistentValue | The value can not be set to the variable under the current circumstances. Possibly could be set under other circumstances.
13 | snmpResourceUnavailable | Could not allocate a resource needed for the variable.
14 | snmpCommitFailed | An assignment failed and all other assignments are being undone.
15 | snmpUndoFailed | An undo of an assignment failed.
16 | snmpAuthorizationError | The community name does not match the one on the agent.
17 | snmpNotWritable | The variable can not be set.
18 | snmpInconsistentName | The variable does not exist and currently can not be created under the current circumstances. May be possible under other circumstances.


TrapConstants

Enumerates values of the GenericTrap property.

Value | Constant | Description
0 | snmpColdStart | The agent is initializing (cold start).
1 | snmpWarmStart | The agent is reinitializing (warm start).
2 | snmpLinkDown | An interface has changed from the up to down state. Variables(1) of the SnmpMessage object contains the interface.
3 | snmpLinkUp | An interface has changed from the down to up state. Variables(1) of the SnmpMessage object contains the interface.
4 | snmpAuthenticationFailure | A message was received from a manager with an invalid community.
5 | snmpEgpNeighborLoss | An EGP peer has changed to the down state. Variables(1) of the SnmpMessage object contains the IP address of the peer.
6 | snmpEnterpriseSpecific | The SpecificTrap property contains information on the trap.


TypeConstants

Enumerates values of the Type Property.

This value is used to indicate the type of message and SNMP version used. A version 1 type can be identified by performing a logical AND with snmp1. A version 2 type can be identified by performing a logical AND with snmp2.

Value | Constant | Description
32 | snmp1 | Version 1 message (use this as a mask).
32 | snmpGet1 | GetRequest version 1 message.
33 | snmpGetNext1 | GetNextRequest version 1 message.
34 | snmpResponse1 | Response version 1 message.
35 | snmpSet1 | SetRequest version 1 message.
36 | snmpTrap1 | Trap version 1 message.
64 | snmp2 | Version 2 message (use this as a mask).
64 | snmpGet2 | GetRequest version 2 message.
65 | snmpGetNext2 | GetNextRequest version 2 message.
66 | snmpResponse2 | Response version 2 message.
67 | snmpSet2 | SetRequest version 2 message.
69 | snmpGetBulk2 | GetBulkRequest version 2 message.
70 | snmpInform2 | InformRequest version 2 message.
71 | snmpTrap2 | Trap version 2 message.


SnmpMib Object

Properties Methods Example

Use the SNMP Management Information Base (MIB) Object to compile and maintain MIB modules for cross-reference purposes.

Miscellaneous

Product | PowerTCP SNMP Tool
Prog ID | Dart.SnmpMib.1
File | DartSnmp2.dll
Dependencies | DartSock.dll
Threading | Apartment Model
Licensed | Yes


MIB Object Overview

MIB Overview

The Management Information Base (MIB) is a collection of data variables that represent various attributes of a node. It acts as a collection of access points at the agent, and contains information about the configuration, behavior and status of an agent.

Variables are referenced by their Object Identifier (OID). Figure 1 illustrates how the MIB is structured.

To discover the OID of a variable you start at the root of the tree and move through the tree until reaching that variable. For example the OID for sysDescr in Figure 1 is 1.3.6.1.2.1.1.1. To access the value of a variable you take the variable's OID and append a ".0" to it. For example, to access the value of sysDescr you would use 1.3.6.1.2.1.1.1.0.

MIB Modules

MIB modules are files that can be loaded to add one or more objects to the MIB tree. The module describes the attributes and locations of the objects in the tree. For example a vendor may have a piece of hardware that can be managed by SNMP. The vendor would include a MIB module describing the information that the hardware provides for management. The manager can then use this module to get key information for accessing and describing the information.

How does the SnmpMib Object make this easier?

The SnmpMib Object decodes MIB modules into an object representation that is easily manipulated. Simply use the MIB object to load a MIB module. When the module is finished loading the developer will have access to the attributes and descriptions of the variables contained in the module.

Loading a MIB Module

Loading a MIB module is easy. The following Visual Basic code snippet demonstrates:

Dim Mib As SnmpMib

Mib.Load "c:\MIBs\Dart.mib"

Typical use of the SnmpMib Object

After loading a module the SnmpMib Object can be used by a manager to describe information that is returned from an agent. The following Visual Basic code snippet demonstrates presenting a description about the objects returned by an agent:

'The message has been received and decoded.

'Mib is declared as a global variable of type SnmpMib.

For Each Variable In Message.Variables

List1.AddItem Variable.Oid

List1.AddItem Variable.Value

' Access the objects description by its identifier.

List1.AddItem Mib.Variables(Variable.Oid).Description

Next

The SnmpMib Object is also useful for presenting trap information. The following Visual Basic code snippet demonstrates:

'The message has been received and decoded.

'Mib is declared as a global variable of type SnmpMib.

For Each Trap In Mib.Traps

If Trap.Enterprise = Message.Enterprise Then

If Trap.SpecificTrap = Message.SpecificTrap Then

List1.AddItem Trap.Description

End If

End If

Next

When a manager makes a request the agent can check to see if the manager has access rights by examining the Access attribute of the variable. The following Visual Basic code snippet demonstrates this. In addition, the variables in the SnmpMib Object can be used to store and retrieve values.

'If the manager is getting the value then check for read access.

If Mib.Variables(Variable.Oid).Access = snmpVariableReadWrite Or Mib.Variables(Variable.Oid).Access = snmpVariableReadOnly Then

'Ok. The MIB object can also store values to be retrieved later

Variable.Value = Mib.Variables(Variable.Oid).Value

Else

'Manager has no access

List1.AddItem "Access Denied!"

End If

OR

'If the manager is setting the value then check for write access.

If Mib.Variables(Variable.Oid).Access = snmpVariableReadWrite Or Mib.Variables(Variable.Oid).Access = snmpVariableWriteOnly Then

'Ok. The MIB object can also store values to be retrieved later

Mib.Variables(Variable.Oid).Value = Variable.Value

Else

'Manager has no access

List1.AddItem "Access Denied!"

End If


Modules Property

Collection of loaded module names.

Syntax

Object.Modules

Part | Description
Object | Evaluates to an SnmpMib Object.

Data Type

DartStrings Object

Remarks

Read-only.

The name of the module is added to this collection when Load is called. An example module name would be "RFC1155-SMI".


Name Property

Returns a human readable name given an OID.

Syntax

Value = Object.Name ( Oid )

Part | Description
Object | Object expression that evaluates to an SnmpMib Object.
Oid | String expression. Represents an OID that will be used when searching.
Value | String. Contains a human readable name.

Data Type

String

Remarks

If the OID cannot be resolved to a human readable name a NULL string is returned.


Oid Property

Returns an OID given a human readable name.

Syntax

Value = Object.Oid ( Name )

Part | Description
Object | Object expression that evaluates to an SnmpMib Object.
Name | String expression. Represents the human readable name to search for.
Value | String. Contains an OID.

Data Type

String

Remarks

If the human readable name can not be resolved to an OID a NULL string is returned.

WARNING Human readable names are case-sensitive.


Traps Property

Collection of SnmpTrap Objects.

Syntax

Object.Traps

Part | Description
Object | Evaluates to an SnmpMib Object.

Data Type

SnmpTraps Object

Remarks

Read-only.

Populated with SnmpTrap objects each time Load is used.


Compile Method

Example

Load and compile a group of .mib files into an SNMP MIB object.

Syntax

Object.Compile Filenames

Part | Description
Object | Object expression that evaluates to an SnmpMib Object.
Filename | DartStrings Object. Filled with a list of .mib files to open.

Remarks

This method updates Modules, Traps, and Variables. The Filenames parameter will accept MIB compliant files in any order. If a file is designated to be missing, the ptFile error code will return requesting the addition of the missing file. If an error occurs during MIB compilation, the ptCompile error code will return specifying the corrupt MIB file and the line number.

Duplicate modules, and objects will be ignored without causing an error to be returned.

The Compile method supercedes the Load method and is the recommended functionality for loading MIB files. The Load method has been left to support legacy implementations.

The Compile method can accept files with assignment blocks in any order, as long as they follow the basic ASN.1 file format. Thus:

RFC1155-SMI DEFINITIONS ::= BEGIN

EXPORTS -- EVERYTHING

internet, directory, mgmt,

experimental, private, enterprises,

OBJECT-TYPE, ObjectName, ObjectSyntax, SimpleSyntax,

ApplicationSyntax, NetworkAddress, IpAddress,

Counter, Gauge, TimeTicks, Opaque;

-- the path to the root

internet OBJECT IDENTIFIER ::= { iso org(3) dod(6) 1 }

directory OBJECT IDENTIFIER ::= { internet 1 }

would be the normally acceptable version of the file but:

RFC1155-SMI DEFINITIONS ::= BEGIN

EXPORTS -- EVERYTHING

internet, directory, mgmt,

experimental, private, enterprises,

OBJECT-TYPE, ObjectName, ObjectSyntax, SimpleSyntax,

ApplicationSyntax, NetworkAddress, IpAddress,

Counter, Gauge, TimeTicks, Opaque;

-- the path to the root

directory OBJECT IDENTIFIER ::= { internet 1 }

internet OBJECT IDENTIFIER ::= { iso org(3) dod(6) 1 }

would also be acceptable. Another copy of the same thing would be:

RFC1155-SMI DEFINITIONS ::= BEGIN EXPORTS internet, directory, mgmt, experimental, private, enterprises, OBJECT-TYPE, ObjectName, ObjectSyntax, SimpleSyntax, ApplicationSyntax, NetworkAddress, IpAddress, Counter, Gauge, TimeTicks, Opaque; directory OBJECT IDENTIFIER ::= { internet 1 } internet OBJECT IDENTIFIER ::= { iso org(3) dod(6) 1 }

Finally, comments are accepted ANYWHERE; Everything after a '--' to the end of the line is ignored.

For example:

RFC1155-SMI –-Filename

DEFINITIONS ::= BEGIN EXPORTS -– EVERYTHING

internet, directory, mgmt, experimental, private, enterprises, OBJECT-TYPE, ObjectName, ObjectSyntax, SimpleSyntax, ApplicationSyntax, NetworkAddress, IpAddress, Counter, Gauge, TimeTicks, Opaque; directory OBJECT –directory path

IDENTIFIER ::= { internet 1 -–another comment

} internet OBJECT IDENTIFIER ::= --Just don’t comment out necessary items

{ iso org(3) dod(6) 1 }

The Compile method takes quadratic (O(n*n)) time to compile files in any order, where n is the number of independent object IDs in the files.

Error Codes

The Compile method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptCompile

  • ptFile (file not found)


Load Method

Example

Load a MIB module from a file, or load a serialized group of MIBs from a binary file.

Syntax

Object.Load Filename

Part | Description
Object | Object expression that evaluates to an SnmpMib Object.
Filename | String expression. Indicates the file and path name of the MIB module to load.

Remarks

This method updates Modules, Traps, and Variables. A MIB must be defined before it is used.

The Compile method supercedes the Load method and is the recommended functionality for loading MIB files. The Load method has been left to support legacy implementations, and for loading serialized Mibs.

The Load method's primary suggested usage now is to load binary serialized MIBs. If a file ends in the extension ".bin", then it will be loaded as a serialized file. Note that serialized files must be created with the Dart Serializer application, or else they will return errors. Also note that trial notifications will appear if a trial serialized Mib is used. Serialized Mibs load in O(n) time, about a factor of four times faster than their equivalent normal Mibs (2MB/s, 8,000 Variables/s), and are about 40% of the size.

Error Codes

The Load method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptCompile

  • ptFile (file not found)


SnmpTable Object

Properties Methods Example

A Collection of SnmpTableRow Objects. This object is NOT updated when variables are added or removed from the SnmpVariables collection, but modifications to the variables held here will modify those in the SnmpVariables collection.

The SnmpTable Object is intended to work with information from the network that follows the SNMPv2 table format. In this case, all objects with OIDs that come subsidiary to the OID passed in are assumed to be part of a table. Rows and columns are separated based on the assumption that the row index comes after the column index.

Note that column indices are defined in the Mib, but row indices can vary based upon implementation.

Common Table OID structure:

TableOID.Entry(1).Column.Row


ColumnCount Property

Example

The number of variables per row.

Syntax

Object.ColumnCount

Part | Description
Object | Evaluates to an SnmpTable or SnmpTableRow object.

Data Type

Long

Remarks

Read-only.


RowCount Property

Example

Refers to the number of rows in this table.

Syntax

Object.RowCount

Part | Description
Object | Evaluates to an SnmpTable object.

Data Type

Long

Remarks

Read-only. This value is the collection size


TableOID Property

Example

The OID of the variable this SnmpTable is based on.

Syntax

Object.TableOID

Part | Description
Object | Evaluates to an SnmpTable object.

Data Type

String

Remarks

Read-only.


Item Method

Returns an SnmpTableRow Object based on a numerical index or OID.

Syntax

Value = Object.Item Index

Part | Description
Object | Object expression that evaluates to an SnmpTable object.
Index | String or Long. Specifies an OID to search for or an index into the collection.
Value | SnmpTableRow Object

Remarks

When specifying Index as a String, the first object with a matching OID is returned. When specifying Index as a Long, its value must be between one and the collection's Count property.

Error Codes

The Item method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1 (Index is not a Long between 1 and Count or Index is a Name with no match)


SnmpTableRow Object

Properties Methods Example

A collection of SnmpVariable objects that correspond to one row in a table. This will normally correspond to one set of entries in a table, such as the information for one port mapping on a machine.


RowIndex Property

Example

The OID of the INDEX object in this TableRow.

Syntax

Object.RowIndex

Part | Description
Object | Evaluates to an SnmpTableRow object.

Data Type

String

Remarks

Read-only. The INDEX value for the current row. If there are multiple indices, the first one is used.


Item Method

Returns an SnmpVariable Object based on a numerical index or OID.

Syntax

Value = Object.Item Index

Part | Description
Object | Object expression that evaluates to an SnmpTableRow object.
Index | String or Long. Specifies an OID to search for or an index into the collection.
Value | SnmpVariable Object

Remarks

When specifying Index as a String, the first object with a matching OID is returned. When specifying Index as a Long, its value must be between one and the collection's Count property.

Error Codes

The Item method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1 (Index is not a Long between 1 and Count or Index is a Name with no match)


SnmpTrap Object

Properties

The SnmpTrap Object provides an easy way to manage trap information.


Description Property

Human readable description of the object represented.

Syntax

Object.Description

Part | Description
Object | Evaluates to an SnmpVariable Object or an SnmpTrap Object.

Data Type

String


Name Property

Human readable identifier that represents the object (for example, sysDescr).

Syntax

Object.Name

Part | Description
Object | Evaluates to an SnmpVariable Object or an SnmpTrap Object.

Data Type

String

Remarks

Read-only.


Oids Property

Collection of OIDs representing the variables contained in the trap.

Syntax

Object.Oids

Part | Description
Object | Evaluates to an SnmpTrap Object.

Data Type

DartStrings Object

Remarks

Read-only.


Reference Property

Reference to another document. This document should have information about the object.

Syntax

Object.Reference

Part | Description
Object | Evaluates to a PowerTCP Object.

Data Type

String


Status Property

Status of the SnmpVariable Object.

Syntax

Object.Status

Part | Description
Object | Evaluates to an SnmpVariable Object or SnmpTrap Object.

Data Type

StatusConstants


SnmpTraps Object

Collection of SnmpTrap Objects .


Add Method

Add an SnmpTrap Object to the collection.

Syntax

Object.Add Item [ , Index ]

Part | Description
Object | Object expression that evaluates to an SnmpTraps Object.
Item | SnmpTrap Object to add to the collection.
Index | Optional Long. Defaults to the end of the collection. Specifies where in the collection the object should be inserted. Should be at least 1 and no greater than 1 more than the Count property.

Error Codes

The Add method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1 (Item is not a reference to an object)

  • ptInvalidParam2 (Index is not between 1 and Count + 1)


Item Method

Returns an SnmpTrap Object from the collection given an index or Trap name.

Syntax

Value = Object.Item Index

Part | Description
Object | Object expression that evaluates to an SnmpTraps Object.
Index | String or Long. Specifies a Name to search for or an index into the collection.
Value | SnmpTrap Object

Remarks

When specifying Index as a String, the first object with a matching Name is returned. When specifying Index as a Long, its value must be between one and the collection's Count property.

Error Codes

The Item method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptInvalidParam1 (Index is not a Long between 1 and Count or Index is a Name with no match)


SnmpVariable Object

Properties Constants

Use the SnmpVariable Object to manage SNMP variables.


Access Property

Current access privileges for the variable.

Syntax

Object.Access

Part | Description
Object | Evaluates to a SnmpVariable Object.

Data Type

AccessConstants

Remarks

The Access property is ONLY set by MIB files. The Agent doesn't send this over the network, they are assumed to be standardized.


Exception Property

Success/failure status of the Get/Set operation.

Syntax

Object.Exception

Part | Description
Object | Evaluates to an SnmpVariable Object.

Data Type

VariableExceptionConstants

Remarks

The default value is snmpNoException.

Set this property to indicate the variable has caused an exception. Inspect this property to determine if the variable caused an exception. SNMP Version 2 allows variables to be returned even if one of the variables causes an exception.


Index Property

Human readable identifier(s) that represent the names of the index(s) for this table

Syntax

Object.Index

Part | Description
Object | Evaluates to an SnmpVariable Object.

Data Type

DartStrings

Remarks

Read-only. Use GetOIDFromName to convert to OID if desired.


Oid Property

Object Identifier (OID) of the variable (for example, "1.3.6.1.2.1.1.1.0").

Syntax

Object.Oid

Part | Description
Object | Evaluates to an SnmpVariable Object.

Data Type

String

Remarks

Read-only.


Repeat Property

Repeat status of the variable.

Syntax

Object.Repeat

Part | Description
Object | Evaluates to an SnmpVariable Object.

Data Type

Boolean

Remarks

When set to True, multiple successors will be returned for this variable when the message Type is snmpGetBulk2. The maximum number is determined by the MaxRepetition property.


Type Property

Data type represented by the Value property.

Syntax

Object.Type

Part | Description
Object | Evaluates to an SnmpVariable Object.

Data Type

VariableTypeConstants


Value Property

Value of the SnmpVariable Object.

Syntax

Object.Value

Part | Description
Object | Evaluates to an SnmpVariable Object.

Data Type

String

Remarks

Type determines the data type of this property.


ValueEx Property

Value of the SnmpVariable Object.

Syntax

Object.Value

Part | Description
Object | Evaluates to an SnmpVariable Object.

Data Type

Byte Array

Remarks

Type property determines the data type of this property.


AccessConstants

Enumerates values of the Access property.

Value | Constant | Description
0 | snmpNotAccessible | Variable is not accessible for set/get operations.
1 | snmpVariableReadOnly | Variable is only accessible for get operations.
2 | snmpWriteOnly | Variable is only accessible for set operations.
3 | snmpReadWrite | Variable is accessible for set/get operations.
4 | snmpReadCreate | Variable is accessible for get/create operations.
5 | snmpAccessibleForNotify | Variable is accessible for notification operations.
6 | snmpVariableAccessNotUsed | Variable is accessible for notification operations.


StatusConstants

Enumerates values of the Status property.

Value | Constant | Description
0 | snmpMandatory | Variable is mandatory.
1 | snmpObsolete | Variable is obsolete.
2 | snmpOptional | Variable is optional.
3 | snmpDeprecated | Variable is deprecated.
4 | snmpCurrent | Variable is current (version 2 MIBs).


VariableExceptionConstants

Enumerates values of the Exception property.

Value | Constant | Description
0 | snmpNoException | Variable caused no exception.
1 | snmpNoSuchObject | Variable did not have an OID prefix that exactly matched an accessible variables prefix on the agent.
2 | snmpNoSuchInstance | Variable did not have an OID that exactly matched an accessible variable on the agent.
3 | snmpEndOfMIBView | Variable has no lexicographic successor.


VariableTypeConstants

Enumerates values of the Type property.

Value | Constant | Description
0 | snmpNull | NULL.
1 | snmpInteger | Signed 32 bit integer.
2 | snmpOctetString | String.
3 | snmpObjectID | String that represents an Object Identifier (OID).
4 | snmpIpAddress | String that represents an IP Address in dot notation.
5 | snmpCounter32 | Unsigned 32 bit integer that represents a counter.
6 | snmpGuage32 | Unsigned 32 bit integer that represents a guage.
7 | snmpTimeTicks | Unsigned 32 bit integer that represents time ticks.
8 | snmpOpaque | String.
9 | snmpNSAPAddress | String that represents an Network Service Access Point Address.
10 | snmpUInteger32 | Unsigned 32 bit integer.
11 | snmpCounter64 | Unsigned 64 bit integer.


SnmpVariables Object

Properties Methods Example

Collection of SnmpVariable Objects.


Add Method

Add an SnmpVariable Object to the collection.

Syntax

Object.Add Item

Part | Description
Object | Object expression that evaluates to an SnmpVariables Object.
Item | SnmpVariable Object to add to the collection.

Error Codes

The Add method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1 (Item is not a reference to an object)

  • ptInvalidParam2 (Index is not between 1 and Count + 1)


GetIndex Method

Returns the numerical index of the OID.

Syntax

Value = Object.GetIndex(OID)

Part | Description
Object | Object expression that evaluates to an SnmpVariables Object.
OID | String. Corresponds to the table's OID.
Value | Long.

Error Codes

The Item method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1 (Index is not a Long between 1 and Count, or Index is an OID or Name with no match)


GetNext Method

Example

Gets the next item in Lexigraphical order. Useful for implementing GetNext and GetBulk requests.

Syntax

Value = Object.GetNext OID

Part | Description
Object | Object expression that evaluates to an SnmpVariables Object.
OID | String . Specifies an Oid to search with and recover the variable after.
Value | SnmpVariable Object

Remarks

The first Variable AFTER the given OID is returned.

Error Codes

The Item method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1 (Index is not a Long between 1 and Count, or Index is an Oid or Name with no match)


GetOIDFromName Method

An efficient method for converting a name to an OID.

Syntax

OID = Vars.GetOIDFromName(Name)

Part | Description
Name | String
OID | String
Vars | SnmpVariables Object

Remarks

This method is an efficient O(n) technique for converting between OIDs and Names. The exact Name (including case) must be passed in, and from that the OID is found. It will not significantly increase the access time of a program accessing variables individually. If there are multiple matches (which cannot happen when compiled from a MIB), this will return the first match.


GetTable Method

Example

Creates and fills a table object from the SnmpVariables collection.

Syntax

Value = Object.GetTable(OID)

Part | Description
Object | Object expression that evaluates to an SnmpVariables Object.
OID | String. Corresponds to the table's OID.
Value | SnmpTable. Corresponds to the given Variable.

Remarks

A good way to implement a table on a manager would be to use this method to get the initial table, with its ColumnCount, and then to use the getBulk message to grab a table from the Agent row by row, using the ColumnCount as the repeat length. Note that the TableOID passed in should be the tableentry value (basetableoid.1). This should matter only when dealing with the MIB.Variables collection (which is not suggested).

This algorithm is O(n+columncount*rowcount).

Will return an error "SEQUENCE expected" if the SYNTAX is not a SEQUENCE or SET.

GetTable is not intended for use with variable definitions compiled from the MIB.

Error Codes

The Item method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1 (Index is not a Long between 1 and Count, or Index is an Oid or Name with no match)


GetTableRow Method

Example

This method creates and fills a SnmpTableRow object from the SnmpVariables collection.

Syntax

Row = Object.GetTableRow(OIDindex)

Part | Description
Object | Object expression that evaluates to an SnmpVariables Object.
OIDindex | String. Corresponds to the table's OID + the index. The OID that should be passed in is the Entry OID, which is normally the table OID.1
Row | The SnmpTableRow being created.

Remarks

This is useful for responding to a GetBulk request, or viewing a single row of information from a table.

The algorithm is O(n+columncount).

GetTableRow can be used with variables compiled from the MIB.

Error Codes

The Item method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1 (Index is not a Long between 1 and Count, or Index is an Oid or Name with no match)


Item Method

Returns an SnmpVariable Object from the collection.

Syntax

Value = Object.Item Index

Part | Description
Object | Object expression that evaluates to an SnmpVariables Object.
Index | String or Long. Specifies an Oid or Name to search for, or an index into the collection.
Value | SnmpVariable Object

Remarks

When Index is a Long, it must be between one and the collection's Count property. When Index is a String, the first object with a matching OID or Name is returned.

Note that this method is much faster for indexing by a long (constant time) or an OID (O(log(n)) time) than by a Name (O(n) time). It is strongly suggested that OIDs or longs be used for indexing, with the help of the GetOIDFromName method if necessary.

Error Codes

The Item method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptInvalidParam1 (Index is not a Long between 1 and Count, or Index is an Oid or Name with no match)


Remove Method

Remove an object from the SnmpVariables collection.

Syntax

Value = Object.Remove Index

Part | Description
Object | Object expression that evaluates to an SnmpVariables Object.
Index | String or Long. Specifies an Oid or Name to search for, or an index into the collection.
Value | SnmpVariable Object

Remarks

When Index is a Long, it must be between one and the collection's Count property. When Index is a String, the first object matching the specified Oid or Name is removed.

Error Codes

The Remove method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptInvalidParam1 (Index is not a Long between 1 and Count, or Index is an Oid or Name with no match)


PowerTCP Telnet Tool

Support Licensing Distribution

Manage Telnet, Rexec, Rsh, and Rlogin sessions. Blocking operation is ideal for hidden scripting applications, and non-blocking can be easily enabled for interactive, high-performance, event-driven communications. Option negotiation (automatic and custom) is fully supported.

Some users with online communication requirements may use one of several protocols. By including all online protocols in a single control, you can explore the alternatives without swapping out controls.

Control | Description
Telnet Control | Manage Telnet, Rexec, Rsh, and Rlogin sessions

Sample Projects

The following sample project demonstrates how to use the Telnet Tool:

Project | Description
Telnet Client | Demonstrates a simple Telnet client application written using non-blocking techniques. An edit box is used for viewing and keyboard entry. Visual Basic, Visual C++, Delphi, and C++Builder.

Online ASP Samples

These ASP samples demonstrate the use of the Telnet Tool on the Internet. You must have an active Internet connection to view these Samples.

Sample

Description

Rexec on the Web

The Telnet Control uses the REXEC protocol to log into a UNIX host, execute a task, and return the generated output for display in the browser.

AutoLogin on the Web

The Telnet Control is used to automatically log in to a Telnet server based on given values for the server's address and various prompts and responses.


PowerTCP Web Tool

Support Licensing Distribution

Communicate with Web Servers using HTTP and HTTP/S. The Web Tool provides a programming object model for session transport and header management.

Control | Description
Web Control | Access Web page documents (supports secure HTTP).

This tool handles HTTP communications. For FTP support, please see the PowerTCP FTP Tool. For MIME formatting support, please see the PowerTCP Mail Tool (the Message Object can be used with the HTTP Control to encode/decode MIME messages available as URLs).

Sample Projects

The following sample projects demonstrate how to use the HTTP Tool:

Project | Description
Link Spider | Demonstrates a web link spider application. Visual Basic 6.
Page Fetch | Demonstrates a simple HTTP application that fetches a web page. Visual Basic 6, Visual C++ 6, PowerBuilder 6, and Delphi 4.
Post | Demonstrates a simple HTTP POST application. Visual Basic 6.
WebAlive | Compares the download performance of any 2 web pages. Useful for comparing the relative performance of mirrored Web Servers. Visual Basic 6.

Online ASP Samples

These ASP samples demonstrate the use of the Web Tool on the Internet. You must have an active Internet connection to view these Samples.

Sample

Description

Stock Quotes on the Web

The Web Control accesses Yahoo's stock quote service. what is the current value of your portfolio.

Web Site Scraping

The Web Control downloads the page you specify, and displays the header and body in edit boxes.

HTML Mail on the Web

The Web Control gets a page (including all images) and then sends it to the specified Email address.


HTTP Control

Web Control

Properties Methods Events Constants Example

Use the Web Control to communicate with Web Servers using HTTP (Hypertext Transfer Protocol) and HTTPS (HTTP with Secure Socket Layer encryption). It provides a programming object model for session transport and header management.

Miscellaneous

Product | PowerTCP Web Tool, PowerTCP Web Enterprise Tool
Prog ID | Dart.Http.1
File | DartWeb.dll
Dependencies | DartSock.dll
Threading | Apartment Model
Licensed | Yes


HTTP Control Usage

Web Control Usage

To fetch data (such as a web page) from a remote server, set the Url property then call the Get method or GetEx method. To determine whether the page exists, its speedier to only fetch the headers using the Head method. To send data to a remote web server (such as when posting form input data), set the Url Property and call the Post method. To write data to a server, set the Url Property and call the Put method. If the server requires basic HTTP authentication for doing the Put, specify the Username and Password parameters.

You can get at the pieces of a URL. When the Url Property is set, the UrlRemoteHost, UrlPath, UrlScheme, and UrlExtra properties are updated.

To monitor the status of any server operation, use the State event to trigger a check of the State property. To monitor progress of a data transfer, use the Progress event. Any errors that occur will always fire the Error event.

Control cookie access with the Cookies property. Control the use of the internal cache with the Cache property. Proxy server support is available with the Proxy and ProxyBypass properties.

Use "https" in the URL to access secure servers. Control the security of access with the Security property.

For more detailed information, see HTTP Protocol Overview.


HTTP Protocol Overview

This topic covers:

  • Protocol Overview

  • Uniform Resource Locator

  • Headers

  • Fetching Content

  • Basic Authentication

  • Posting Data

  • Establishing the Existence of Content

  • Sending Content

  • Cookies

  • Cache

  • HTTPS

  • Proxies

  • Redirect

Protocol Overview

The HyperText Transport Protocol (HTTP) provides a simple, stateless protocol for transporting generic content over the Internet. This protocol links web client browsers to web servers (collectively referred to as the "world-wide web"). Content can be as simple as static HTML pages or as complex as dynamic application data. The PowerTCP Web Tool provides easy access to the client side of this protocol.

A session is defined as follows:

  1. A client makes a TCP connection to a web server.

  2. The client issues a single command: "GET", "HEAD", "POST", or "PUT", sending a data path, headers, and optionally basic authentication and data to the remote server.

  3. The server responds with a status indication, response headers, and optionally data.

  4. The server closes the connection.

The PowerTCP HTTP Control supports versions 1.0 and 1.1 of the HTTP protocol.

Back to Top

Uniform Resource Locator

The Uniform Resource Locator (URL) identifies a resource (for example, data) on the server. The URL is made up of several parts, including the scheme, remote host, data path, and possibly extra information specific to the data. The scheme identifies the protocol used (HTTP and HTTPS are supported). The remote host identifies the server and is either a host name (server.dart.com) or dot address (nnn.nnn.nnn.nnn). The data path locates the data on the server.

The full specification of the URL is: Scheme:://Remotehost[/Path][Extra]. Path and Extra are optional.

For example, the URL "http://www.dart.com/Trials/Index.html?Product=PowerTCP" is made up of the scheme "http", the remote host "www.dart.com", the data path "Trials/Index.html", and the extra "?Product=PowerTCP".

Set the Url property before starting a session.

Back to Top

Headers

Headers describe data content sent to and returned from a server, and follows the RFC822/MIME protocol. A header is a string consisting of a label, followed by a colon, followed by a value. Headers are separated by a carriage-return / line-feed pairs. Headers are referred to as "response headers" when sent from the server and typically identify the data, in addition to other information that may be application specific.

An example of headers sent from a server:

Content-Length: 1072
Content-Type: text/html
Last-Modified: Mon, 02 Nov 1998 12:49:26 GMT

The Content-Length header indicates the number of octets of content. The Content-Type header identifies the type of content. For more information on HTTP headers, see RFC 1268. For information on MIME headers in general, see RFC 822.

Back to Top

Fetching Content

The typical client will get web page content from servers.

The client connects to the server specified in the remote host part of the URL. The client issues the "GET" command, sending it the URL path of the content on the server. The server responds with a status indicating that response headers and content will follow, or an error message if the resource does not exist or insufficient authentication was provided.

The Get and GetEx methods retrieves content from servers.

Back to Top

Basic Authentication

Commands may optionally include basic authentication consisting of a username and password. If the data requires authentication, and it is not provided or is incorrect, the server will send back an error status.

Back to Top

Posting Data

The "POST" command is used to send data to a server. Typically, this could be the posting of a completed HTML form or information for a database query.

The client connects to the server specified in the remote host of the URL. The client issues the "POST" command, sending the URL path of the resource, headers, data, and optional basic authentication to the server. The server responds with a status indicating the success or failure of the command, followed optionally by response headers and data.

When posting an HTML form, the "Content-Type" header is sent with value "application/x-www-form-urlencoded" and the "Content-Length" header states the length of the form.

The Post method sends data to servers.

Back to Top

Establishing the Existence of Content

The "HEAD" command is typically used to determine what content exists on a server. This command gets the response headers without the content. The "HEAD" command is otherwise identical to the "GET" command.

The Head method fetches headers.

Back to Top

Sending Content

The "PUT" command is used to send content to a server. This command differs from the "POST" command in that with "POST" the URI specifies the resource that will "handle" the posted data and with "PUT" a request is made for storage under the given URI. Basic authentication is typically required. The URL path identifies the name and location of the newly created content (file) on the server.

The Put method sends content to servers.

Back to Top

Cookies

Cookies are used to store information on the client for later use by the server. They simplify setting a persistent, client-side state and extend the capabilities of web-based client/server applications.

The Cookies property controls the use of cookies.

Back to Top

Cache

The operating system maintains built-in cache support. Any data retrieved from the network is cached on the hard disk and used for subsequent requests, based on a simple time stamp algorithm. Most response headers are also cached. When a request is satisfied from the cache, the cached headers are also returned to the client. Caching can be enabled or disabled for each command sent. The effect is transparent to the client, except for an increase in responsiveness.

The Cache property and the CacheEx property together controls the use of caching.

Back to Top

HTTPS

The HTTPS protocol supports the secure transport of information using Secure Socket Layer/Private Communications Technology encryption (SSL/PCT). HTTPS uses SSL/PCT-based security certificates to handle all security, and is transparent to the client. Use of the HTTPS protocol is enabled automatically when the URL has the scheme set to "https" (for example, in the URL "https://www.amazon.com/order.html"). To the client, the HTTPS session is identical to an HTTP session.

The Security property provides security control over the use of SSL/PCT-based security certificates.

Back to Top

Proxies

The client can use proxies in all commands sent to servers. When enabled, all requests are routed automatically through the proxy host. CERN type proxies are supported. If Internet Explorer is installed, SOCKS proxies are also supported. Proxy bypass servers identify servers that require direct routing, bypassing proxy support.

Use the ProxyUsername property and the ProxyPassword property if the proxy server requires authentication.

The Proxy and ProxyBypass Properties support the use of proxies.

Back to Top

Redirect

A Web Server may point a requested URL to another location through the use of a Redirect response.

If the Redirect property is set to TRUE, the control will automatically retrieve the redirected URL, otherwise it is up to the application to determine the new URL from the Get Method response.

Back to Top


HTTP Control Non-Blocking Sample

Web Control Non-Blocking Sample

If we can structure our code so that sequencing is controlled by code in our events, then we will be able to accomplish the Get method in a non-blocking way. We have traded the benefit of sequential code for the greater benefit of robust code that allows PowerTCP to operate relatively independently of your application and any additional processing you may be doing for your user:

Private Sub Get_Clicked()

' Set Timeout to indicate non-blocking use

Http1.Timeout = 0

' Specify the URL of the remote web server and the first item we wish

' to fetch

UrlIndex = 1

Http1.Url = Url[UrlIndex]

' fetch the data; Data has global scope

Http1.Get Data

' the State Event will notify us when the fetch is complete

End Sub

Private Sub Http1_State()

If Http1.State = httpCompleted Then

' save the data fetched

SaveData Data

' start next fetch if not done yet

UrlIndex = UrlIndex + 1

If UrlIndex < UrlMax Then

Http1.Url = Url[UrlIndex]

Http1.Get Data

End If

End If

End Sub


HTTP Control Blocking Sample

Web Control Blocking Sample

By default, the Timeout property is a positive value which specifies that methods should wait until complete. This is called blocking and greatly simplifies the sequencing of operations and error recovery. Consider the following code snippet:

' Use the Timeout property to establish blocking behavior

Http1.Timeout = 20000 'give the command up to 20 seconds

' Specify the URL of the remote web server and the data we wish to fetch

Http1.Url = "http://www.dart.com/contact"

' fetch the data

Dim s As String

Http1.Get s

' the data is now fetched!

Note that the sequencing of the initialization, the transfer, and the tear-down is as easy as it gets. In addition, errors are handled automatically – any failure will result in program termination. The fact that all the code executed without error implies that all went well and the data is in the string.

Now, add error handling so the application won't terminate because of a failure. A simple modification accomplishes this:

On Error GoTo OnError

' Use the Timeout property to establish blocking behavior

Http1.Timeout = 60000

' Specify the URL of the remote web server and the data we wish to fetch

Http1.Url = "http://www.dart.com/contact"

' fetch the data

Dim s As String

Http1.Get s

' the data is now fetched!

Text1.Text = s

Exit Sub

OnError:

' Don't use MsgBox because that interrupts event notification

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

So far so good, but now we want to put up a progress indication for our user. To do this, we need event notification during the course of the download. We get this by putting code in the Progress event as follows:

Private Sub Http1_Progress(ByVal Count As Long, ByVal Size As Long)

If Size > 0 Then

Label1.Caption = (Count / Size) * 100 & "%" & " done..."

End If

End Sub

The final code sample would look similar to the following:

Private Sub Command1_Click()

On Error GoTo OnError

' Use the Timeout property to establish blocking behavior

Http1.Timeout = 20000 'give the command up to 20 seconds

' Specify the URL of the remote web server and the data we wish to fetch

Http1.Url = "http://www.dart.com/contact"

' fetch the data

Dim s As String

Http1.Get s

' the data is now fetched!

Text1.Text = s

Exit Sub

OnError:

' Don't use MsgBox because that interrupts event notification

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Private Sub Http1_Progress(ByVal Count As Long, ByVal Size As Long)

If Size > 0 Then

Label1.Caption = (Count / Size) * 100 & "%" & " done..."

End If

End Sub

The code now puts up progress information, but there are still limitations:

  1. If the user wants to exit the application, you will have to defeat it because you can't allow him/her to unload things while you are executing the Get method.

  2. If the user initiates another activity through the user interface, you'll have to ensure he/she doesn't affect the Get method (by calling another method or capturing the thread for any length of time).

These limitations can be overcome by using non-blocking techniques.


Cache Property

Returns or sets a value that enables internal caching for all GetEx and Get method calls.

Syntax

Object.Cache

Part | Description
Object | Evaluates to a Web Control.

Data Type

Boolean

Remarks

The default value is True. This property can be set at design-time.

When set to True, the Get Method uses persistent cache storage on the local machine. When performing a Get, the date of the data on the server is compared to the entry in the cache, and the data is downloaded if it is newer or the cache copy has expired. It also takes the cache copy if the connection with the remote server cannot be established.

When set to False, a new copy is always retrieved.

See Protocol Overview and the CacheEx property for more information.


CacheEx Property

Allows extended caching properties to be set.

Syntax

Object.CacheEx

Part | Description
Object | Evaluates to a Web Control.

Data Type

CacheExConstants

Remarks

The default value is httpIfModified.

If the Cache property is set the TRUE, the CacheEx property is used to set the type of caching performed within the Web Control.

When CacheEx is set to httpIfModified, the entire object is retrieved only if the cache copy is older than the server copy or the cached copy has expired.

When CacheEx is set to httpCacheOnly, the object is returned only if it resides in the system cache. This option generates no network traffic. If the object is not in the cache then a File Not Found error is returned.


Cookies Property

Example

Returns or sets a value that determines whether cookies are automatically handled.

Syntax

Object.Cookies

Part | Description
Object | Evaluates to a Web Control.

Data Type

Boolean

Remarks

The default value is True. This property can be set at design time. If you want to send your own Cookies, or intercept Cookies before they are handled by the system, set this value to False.

See Protocol Overview for more information.


Proxy Property

Returns or sets a value that specifies a proxy host for communications with servers. Can be either a host name (proxy.dart.com) or dot address (nnn.nnn.nnn.nnn), optionally followed by a colon and remote port.

Syntax

Object.Proxy

Part | Description
Object | Evaluates to a Web Control.

Data Type

String

Remarks

The default value is Empty. This property can be set at design-time.

When used, the specified proxy server transparently forwards requests and returns responses. The remote port for the proxy server can be specified after the host name, separated by a colon. SOCKS proxies are supported if Microsoft Internet Explorer is installed.

When empty, the operating system determines Proxy support by reading the registry.

See Protocol Overview for more information.


ProxyBypass Property

A collection of remote hosts that will bypass proxy support.

Syntax

Object.ProxyBypass

Part | Description
Object | Evaluates to a Web Control.

Data Type

DartStrings Object

Remarks

By default the collection is empty.

To bypass all proxy support, add one entry consisting of a single asterisk ("*").

To force all hosts on the local network to bypass proxy server support, add one entry consisting of the string "<local>".

See Protocol Overview for more information.


ProxyPassword Property

Password to be sent on all requests routed through a proxy server.

Syntax

Object.ProxyPassword

Part | Description
Object | Evaluates to a Web Control.

Data Type

String

Remarks

Set this property if HTTP requests are routed through a proxy server, and the proxy server requires user authentication.

See Protocol Overview for more information.


ProxyUsername Property

Username to be sent on all requests routed through a proxy server.

Syntax

Object.ProxyUsername

Part | Description
Object | Evaluates to a Web Control.

Data Type

String

Remarks

Set this property if HTTP requests are routed through a proxy server, and the proxy server requires user authentication.

See Protocol Overview for more information.


Redirect Property

Determines if auto redirection is to take place.

Syntax

Object.Redirect

Part | Description
Object | Evaluates to a Web Control.

Data Type

Boolean

Remarks

The default value is True.

When redirection occurs, the Url Property is updated to reflect the current page. See HTTP Protocol Overview for more information.


Security Property

Example

Returns or sets security level when accessing a secure server.

Syntax

Object.Security

Part | Description
Object | Evaluates to a Web Control.

Data Type

SecurityConstants

Remarks

The default value is zero (greatest security level). This property can be set at design time.

Decrease security levels by adding SecurityConstants together. See Protocol Overview for more information.


State Property

The State event fires to signal that this property has changed in value. It can be used to provide status information to the user interface.

Syntax

Object.State

Part | Description
Object | Evaluates to a Web Control.

Data Type

StateConstants

Remarks

Read-only.


Status Property

Response code from the last completed HTTP request.

Syntax

Object.Status

Part | Description
Object | Evaluates to a Web Control.

Data Type

Long

Remarks

See RFC 2616 for more information regarding each of the possible status codes returned from an HTTP server.


StatusText Property

Response text of the last completed HTTP request.

Syntax

Object.StatusText

Part | Description
Object | Evaluates to a Web Control.

Data Type

String

Remarks

The StatusText property is the human-readable result message for the last HTTP Request.

See RFC 2616 for more information regarding each of the possible status codes returned from an HTTP server.


Url Property

Returns or sets the URL (uniform resource locator) to use when invoking the Get, Head, Post, and Put methods.

Syntax

Object.Url

Part | Description
Object | Evaluates to a Web Control.

Data Type

String

Remarks

The default value is Empty. This property can be set at design-time.

When set, the following properties are updated: UrlRemoteHost, UrlPath, UrlScheme, and UrlExtra. The full specification of the URL is: Scheme://Remotehost[/Path][Extra]. Path and Extra are optional. For example, the URL "http://www.dart.com/Trials/Index.htm?Product=PowerTCP" is made up of the scheme "http", the remote host "www.dart.com", the path "Trials/Index.html", and the extra "?Product=PowerTCP".

The URL you specify is automatically encoded according to the rules stated in URL RFC 1738.

See Protocol Overview for more information.


UrlExtra Property

Returns the extra part (everything in a URL following the path) of the Url property.

Syntax

Object.UrlExtra

Part | Description
Object | Evaluates to a Web Control.

Data Type

String

Remarks

Setting the Url property automatically updates this property. For example, if the Url property is set to "https://www.dart.com/index/a.html?aa=bbb", then UrlExtra is set to "?aa=bbb".

See Protocol Overview for more information.


UrlPath Property

Returns the path part of the Url property.

Syntax

Object.UrlPath

Part | Description
Object | Evaluates to a Web Control.

Data Type

String

Remarks

Setting the Url property automatically updates this property to the path. For example, if the Url property is set to "http://www.dart.com/index/a.html", then UrlPath is set to "index/a.html".

See Protocol Overview for more information.


UrlRemoteHost Property

Returns the remote host part of the Url property.

Syntax

Object.UrlRemoteHost

Part | Description
Object | Evaluates to a Web Control.

Data Type

String

Remarks

Setting the Url property updates this property to the remote host. For example, if the Url property is set to "http://www.dart.com/index/a.html", then the UrlRemoteHost property is set to "www.dart.com".

See Protocol Overview for more information.


UrlScheme Property

Returns the scheme part of the Url property.

Syntax

Object.UrlScheme

Part | Description
Object | Evaluates to a Web Control.

Data Type

String

Remarks

Setting the Url property automatically updates this property to the scheme. For example, if the Url Property is set to "https://www.dart.com/index/a.html", then the UrlScheme property is set to "https".

See Protocol Overview for more information.


UserAgent Property

Returns or sets a value that identifies the user agent in all communications with a server.

Syntax

Object.UserAgent

Part | Description
Object | Evaluates to a Web Control.

Data Type

String

Remarks

The default value is "Dart Communications PowerTCP". This property can be set at design time.


Version Property

Returns or sets a value that selects the version of the HTTP Protocol to use.

Syntax

Object.Version

Part | Description
Object | Evaluates to a Web Control.

Data Type

String

Remarks

The default value is "HTTP/1.0". Set this to "HTTP/1.1" to use version 1.1 of the HTTP Protocol. This property can be set at design-time.


Get Method

Get content (a web page) from a server.

Syntax

Object.Get Content [ , Headers ] [ , Username ] [ , Password ]

Part | Description
Object | Object expression that evaluates to a Web Control.
Content | String or Byte array. Specifies the destination file name, or an un-dimensioned String or Byte array that will be dynamically expanded and filled with response data.
Headers | Optional DartStrings Object. The response headers received from the server.
User | Optional String. Username for basic HTTP authentication. Defaults to no user.
Password | Optional String. Password for basic HTTP authentication. Defaults to no password.

Remarks

This method uses the HTTP GET command to get content from an HTTP server. Before using this method, you must set the Url property. See Usage and Protocol Overview for more information.

If you wish to use the response headers for the Content, specify Headers with a DartStrings Object. The strings are cleared and filled with headers received from the server.

Specify Username and Password when the remote server requires HTTP authentication to reference the Url.

The Progress event will fire multiple times as the operation proceeds. When the Timeout property is greater than 0, this method blocks until the command completes or an error occurs. When the Timeout property is zero, this method immediately returns and the transfer operates in the background. The Content and Headers parameters must not go out of scope while the command completes (they must have file or global scope). The State property immediately changes to httpStartingRequest. Many intermediate states may exist as the method proceeds. The final state of httpCompleted indicates success. The State Property can be checked in the body of the State event or polled off a timer.

See Web Control Blocking Sample and Web Control Non-Blocking Sample for more information on blocking and the Timeout property.

Error Codes

The Get method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • httpBlocked

  • httpInvalidParam1 (Data is not a String or Byte array)

  • httpInvalidParam2 (Headers is not a valid DartStrings object)


GetEx Method

Get content (a web page) from a server.

Syntax

Object.GetEx RequestHeaders, Content [ , ResponseHeaders ] [ , Username ] [ , Password ]

Part | Description
Object | Object expression that evaluates to a Web Control.
RequestHeaders | DartStrings Object. The request headers sent to the server.
Content | String or Byte array. Specifies the destination file name, or an un-dimensioned String or Byte array that will be dynamically expanded and filled with response data.
ResponseHeaders | Optional DartStrings Object. The response headers received from the server.
Username | Optional String. Username for basic HTTP authentication. Defaults to no user.
Password | Optional String. Password for basic HTTP authentication. Defaults to no password.

Remarks

This method is functionally equivalent to the Get method with the exception that the GetEx method allows you to specify additional headers to be sent with the request using the RequestHeaders parameter.

When using the RequestHeaders parameter, each header line must in the form of Label: + Space + FieldValue. If RequestHeaders contains an item not formatted properly, a run-time error of httpInvalidParam1 will be thrown.

This method uses the HTTP GET command to get content from an HTTP server. Before using this method, you must set the Url property. See Usage and Protocol Overview for more information.

If you wish to use the response headers for the Content, specify ResponseHeaders with a DartStrings Object. The header labels are cleared and filled with headers received from the server.

Specify Username and Password when the remote server requires HTTP authentication to reference the Url.

The Progress event fires multiple times as the operation proceeds. When the Timeout property is greater than 0, this method blocks until the command completes or an error occurs. When the Timeout property is zero, this method immediately returns and the transfer operates in the background. The RequestHeaders, Content and ResponseHeaders parameters must not go out of scope while the command completes (they must have file or global scope). The State property immediately changes to httpStartingRequest. Many intermediate states may exists as the method proceeds. The final state of httpCompleted indicates success. The State Property can be checked in the body of the State event or polled off a timer.

See Web Control Blocking Sample and Web Control Non-Blocking Sample for more information on blocking and the Timeout property.

Error Codes

The GetEx method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • httpBlocked

  • httpInvalidParam1 (Data is not a String or Byte array)

  • httpInvalidParam2 (Headers is not a valid DartStrings Object)


Head Method

Example

Get HTML headers.

Syntax

Object.Head Headers [ , Username ] [ , Password ]

Part | Description
Object | Object expression that evaluates to a Web Control.
Headers | DartStrings Object. The response headers from a successful Head Method call.
Username | Optional String. Username for basic HTTP authentication. Defaults to no user.
Password | Optional String. Password for basic HTTP authentication. Defaults to no password.

Remarks

This method uses the HTTP HEAD command to fetch headers from an HTTP server. No other content is fetched. Before using this method, you must set the Url property. Specify the Headers parameter with a DartStrings Object. The contents are cleared and filled with headers received from the server. See Usage and Protocol Overview for more information.

Specify Username and Password when the remote server requires HTTP authentication to reference the Url.

The Progress event fires multiple times as the operation proceeds. When the Timeout property is greater than 0, this method blocks until the command completes or an error occurs. When the Timeout property is zero, this method immediately returns and the transfer operates in the background. The Headers parameter must not go out of scope while the command completes (it must have file or global scope). The State property immediately changes to httpStartingRequest. Many intermediate states may exists as the method proceeds. The final state of httpCompleted indicates success. The State Property can be checked in the body of the State event or polled off a timer.

See Web Control Blocking Sample and Web Control Non-Blocking Sample for more information on blocking and the Timeout property.

Note: Error 12152 will be generated if the server does not support Head requests.

Error Codes

The Head method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • httpBlocked

  • httpInvalidParam1 (Data is not a String or Byte array)


Post Method

Example

Post data to an HTTP server.

Syntax

Object.Post Data [ , RequestHeaders ] [ , Result ] [ , Headers ] [ , Username ] [ , Password ]

Part | Description
Object | Object expression that evaluates to a Web Control.
Data | String or Byte array. Specifies the source file name, or a String or Byte array that contains data to be sent to the server.
RequestHeaders | Optional DartStrings Object. The headers to send in the request.
Result | Optional String or Byte array. Specifies the destination file name, or an un-dimensioned String or Byte array that will be dynamically expanded and filled with response data.
Headers | Optional DartStrings Object. The headers received from the server.
Username | Optional String. Username for basic HTTP authentication. Defaults to no user.
Password | Optional String. Password for basic HTTP authentication. Defaults to no password.

Remarks

This method uses the HTTP POST command to post data to a server. Before using this method, you must set the Url property. See Usage and Protocol Overview for more information.

Specify the data to send to the server with the Data parameter. If you wish to send headers with the data, specify RequestHeaders with a DartStrings Object filled with headers.

When using the RequestHeaders parameter, each header line must in the form of Label: + Space + FieldValue, as shown in the sample below. If RequestHeaders contains an item not formatted properly, a runtime error of httpInvalidParam2 will be thrown.

The most common example of the Post Method is posting of HTML form input data. In this case, the "Content-Type" and "Content-Length" headers must be sent. If RequestHeaders is not specified, then a "Content-Type" header is sent with value "application/x-www-form-urlencoded", followed by a "Content-Length" header with value set to the length of Data.

Specify Headers to capture the headers for the data sent back from the server. The contents of Headers are cleared before the response headers are added.

Specify Username and Password when the remote server requires HTTP authentication to reference the Url.

The Progress event will fire multiple times as the operation progresses. When the Timeout property is greater than 0, this method blocks until the command completes or an error occurs. When the Timeout property is zero, this method immediately returns and the transfer operates in the background. The Result and Headers parameters must not go out of scope while the command completes (they must have file or global scope). The State property immediately changes to httpStartingRequest. Many intermediate states may exist as the method proceeds. The final state of httpCompleted indicates success. The State Property can be checked in the body of the State event or polled off a timer.

See Web Control Blocking Sample and Web Control Non-Blocking Sample for more information on blocking and the Timeout property.

Error Codes

The Post method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • httpBlocked

  • httpInvalidParam1 (Data is not a String or Byte array)

  • httpInvalidParam2 (Headers is not a valid DartStrings Object)

  • httpInvalidParam3 (Result is not a valid String or Byte array)

  • httpInvalidParam4 (Headers is not a valid allocated DartStrings Object)


Put Method

Example

Put content to a server.

Syntax

Object.Put Content [ , RequestHeaders ] [ , Result ] [ , Headers ] [ , Username ] [ , Password ]

Part | Description
Object | Object expression that evaluates to a Web Control.
Content | String or Byte array. Specifies the source file name, or a String or Byte array that contains data to be sent to the server.
RequestHeaders | Optional DartStrings Object. The headers to send.
Result | Optional String or Byte array. The results received from the server.
Headers | Optional DartStrings Object. The response headers received from the server.
Username | Optional String. Username for basic HTTP authentication. Defaults to no user.
Password | Optional String. Password for basic HTTP authentication. Defaults to no password.

Remarks

This method uses the HTTP PUT command to send content to a server. Before using this method, you must set the Version property to webHTTP11, and the Url Property to the destination location. Additionally, the server must support HTTP protocol version 1.1. See Usage, and Protocol Overview for more information.

Specify RequestHeaders to provide request headers for the Content.

When using the RequestHeaders parameter, each header line must in the form of Label: + Space + FieldValue, as shown in the sample below. If RequestHeaders contains an item not formatted properly, a runtime error of httpInvalidParam2 will be thrown.

If you are interested in results or headers sent back from the server, specify Result and Headers. Result is always re-dimensioned and filled with data from the server. Headers is cleared and filled with headers received from the server.

Specify both Username and Password when the remote server requires basic HTTP authentication for reference to the Url.

The Progress event fires multiple times as the operation proceeds. When the Timeout property is greater than 0, this method blocks until the command completes or an error occurs. When the Timeout property is zero, this method immediately returns and the transfer operates in the background. The Result and Headers parameters must not go out of scope while the command completes (they must have file or global scope). The State property immediately changes to httpStartingRequest. Many intermediate states may exist as the method proceeds. The final state of httpCompleted indicates success. The State Property can be checked in the body of the State event or polled off a timer.

Error Codes

The Put method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • httpBlocked

  • httpInvalidParam1 (Data is not a String or Byte array)

  • httpInvalidParam2 (RequestHeaders is not a valid DartStrings Object)

  • httpInvalidParam3 (Result is not a valid String or Byte array)

  • httpInvalidParam4 (Headers is not a valid DartStrings Object )


Error Event

Any method can generate an error, and some errors are generated asynchronously. For this reason, robust applications must use this event to respond to runtime errors.

Some environments, such as IIS Active Server Pages, do not support Event handling. In this case a positive Timeout property forces all errors to be passed back to the container using an Error object that is initialized by each PowerTCP method used.

Syntax

Private Sub Object_Error ( [ Index As Integer , ] Number As ErrorConstants, Description As String )

Part | Description
Object | Evaluates to a Web Control.
Index | Integer. Array index if the object is part of an array.
Number | ErrorConstants value.
Description | String. ErrorConstants description.


Progress Event

The GetEx, Get, Post, Head and Put methods transfer data between the server and your application. During the transfer process, this event fires periodically to indicate progress.

Syntax

Private Sub Object_Progress ( [ Index As Integer , ] Count As Long, Size As Long )

Part | Description
Object | Evaluates to a Web Control.
Index | Array index if the object is part of an array.
Count | Long. Indicates the number of bytes that have been transferred (so far) for the transfer that is currently in progress. The value will normally fall between 0 and Size.
Size | Long. Indicates the total number of bytes for the transfer that is currently in progress.

Remarks

When performing a request, there will be two sets of progress events. One for the sending of the request followed by a series of events for the retrieving the response.

During a Get request, the second series of Progress events can be used to monitor the progress of large downloads.

When performing a Get request, the Size parameter is determined from the Content-Length header value. When the Content-Length header is not found, Size is set to zero.

If doing a Put or a Post request, the first series of Progress events may be used to monitor the progress of the upload of data to the server.


State Event

Example

Fires to indicate that the State property has changed value.

The Get, GetEx, Head, Post, and Put methods normally cause the State Property to transition from httpStartingRequest through a number of states, ending with httpCompleted indicating successful completion of the method. The State event fires as each change occurs.

Syntax

Private Sub Object_State ( [ Index As Integer ] )

Part | Description
Object | Evaluates to a Web Control.
Index | Integer. Array index if the object is part of an array.


CacheConstants

CacheExConstants

Enumerates values of the CacheEx property.

Value | Constant | Description
0 | httpIfModified | Direct the server to only send the object if it is newer than the version in the cache. Responses will be updated in the system cache.
1 | httpCacheOnly | Only uses to cache to fulfill responses. If not found in cache returns suitable error. No network traffic generated.


ErrorConstants

The ErrorConstants fall into two classes: design errors and run time errors. The Error event ALWAYS fires when ANY error occurs. When the Timeout property is 0, however, run time errors are not thrown back to the container. This will allow applications that use only non-blocking techniques to localize all error handling in the Error Event. To summarize:

  1. Timeout is 0 (non-blocking). All errors are reported via the Error Event. Only errors classified as design errors are also reported back from methods using the error object.

  2. Timeout is not 0 (blocking). All errors are reported via the Error Event. All errors occurring within the scope of a method are reported back to the container using the error object.

Design Errors

Value | Constant | Description
9001 | httpInvalidParam1 | Parameter #1 is invalid.
9002 | httpInvalidParam2 | Parameter #2 is invalid.
9003 | httpInvalidParam3 | Parameter #3 is invalid.
9004 | httpInvalidParam4 | Parameter #4 is invalid.
9009 | httpInvalidProperty | Invalid property assignment.
9011 | httpBlocked | User thread is blocking in another method.

Run Time Errors

Value | Constant | Description
9060 | httpTimeout | Timeout occurred for requested operation.
9103 | httpAbort | Blocking operation cancelled by user.
12001 | httpOutOfHandles | No more handles could be generated at this time.
12004 | httpInternaLError | An internal error has occurred.
12005 | httpInvalidUrl | The URL is invalid.
12006 | httpUnrecognizedScheme | The scheme for the URL (whether http: or https: or other) is not given and unknown.
12007 | httpNameNotResolved | The server name could not be resolved.
12011 | httpOptionNotSettable | The requested option cannot be set, only queried.
12012 | httpShutdown | The Win32 Internet function support is being shut down or unloaded.
12017 | httpOperationCancelled | The operation was canceled, usually because the handle on which the request was operating was closed before the operation completed.
12020 | httpNotProxyRequest | The request cannot be made via a proxy.
12023 | httpNoDirectAccess | Direct network access cannot be made at this time.
12026 | httpRequestPending | The required operation could not be completed because one or more requests are pending.
12028 | httpItemNotFound | The requested item could not be located.
12029 | httpCannotConnect | The attempt to connect to the server failed.
12030 | httpConnectionAborted | The connection with the server has been terminated.
12031 | httpConnectionReset | The connection with the server has been reset.
12032 | httpForceRetry | The Win32 Internet function needs to redo the request.
12033 | httpInvalidProxyRequest | The request to the proxy was invalid.
12034 | httpNeedui | A user interface or other blocking operation has been requested.
12037 | httpSecCertDateInvalid | SSL certificate date that was received from the server is bad. The certificate is expired.
12038 | httpSecCertCnInvalid | SSL certificate common name (host name field) is incorrect—for example, if you entered www.server.com and the common name on the certificate says www.different.com.
12039 | httpHttpToHttpsOnRedir | The application is moving from a non-SSL to an SSL connection because of a redirect.
12040 | httpHttpsToHttpOnRedir | The application is moving from an SSL to an non-SSL connection because of a redirect.
12041 | httpMixedSecurity | The content is not entirely secure. Some of the content being viewed may have come from unsecured servers.
12042 | httpChgPostIsNonSecure | The application is posting and attempting to change multiple lines of text on a server that is not secure.
12043 | httpPostIsNonSecure | Cannot post to non secure server.
12044 | httpClientAuthCertNeeded | The server is requesting client authentication.
12045 | httpInvalidCa | The function is unfamiliar with the Certificate Authority that generated the server's certificate.
12046 | httpClientAuthNotSetup | Client authorization is not set up on this computer.
12047 | httpAsyncThreadFailed | The application could not start an asynchronous thread.
12048 | httpRedirectSchemeChange | The function could not handle the redirection, because the scheme changed (for example, HTTP to FTP).
12049 | httpDialogPending | Another thread has a password dialog in progress.
12053 | httpInsertCdrom | The request requires a CD-ROM to be inserted in the CD-ROM drive to locate the resource requested.
12150 | httpHeaderNotFound | The requested header could not be located.
12151 | httpDownlevelServer | The server did not return any headers.
12152 | httpInvalidServerResponse | The server response could not be parsed.
12153 | httpInvalidHeader | The supplied header is invalid.
12155 | httpHeaderAlreadyExists | The header could not be added because it already exists.
12156 | httpRedirectFailed | The redirection failed because either the scheme changed (for example, HTTP to FTP) or all attempts made to redirect failed (default is five attempts).
12160 | httpNotRedirected | Could not redirect (generic).
12161 | httpCookieNeedsConfirmation | The redirection requires user confirmation.
12162 | httpCookieDeclined | The cookie was not accepted.
12168 | httpRedirectNeedsConfirmation | Need to confirm redirect.
12157 | httpSecurityChannelError | The application experienced an internal error loading the SSL libraries.
12158 | httpUnableToCacheFile | The function was unable to cache the file.
12159 | httpTcpipNotInstalled | The required protocol stack is not loaded and the application cannot start WinSock.
12163 | httpDisconnected | The Internet connection has been lost.
12164 | httpServerUnreachable | The Web site or server indicated is unreachable.
12165 | httpProxyServerUnreachable | The designated proxy server cannot be reached.
12169 | httpSecInvalidCert | SSL certificate is invalid.
12170 | httpSecCertRevoked | SSL certificate was revoked.
21000 | httpNoMemory | The system could not allocate internal buffers. No free memory.
21001 | httpFile | The specified file is not available for access.


SecurityConstants

The Security property is always set to zero or one or more of the following values (multiple values can be added together):

Value | Constant | Description
1 | httpIgnoreCertNameCheck | Ignore name checking. Disables checking of SSL/PCT-based certificates that are returned from the server against the host name given in the request. Normally a simple check against certificates is done by comparing for matching host names and simple wildcard rules.
2 | httpIgnoreCertDateCheck | Ignore certificate-date checking. Disables checking of SSL/PCT-based certificates for proper validity dates.
4 | httpAllowRedirectToHTTP | Allow redirect to HTTP. Allow redirecting from a secure HTTPS connection to an HTTP connection.
8 | httpAllowRedirectToHTTPS | Allow redirect to HTTPS. Allow redirecting to an HTTPS connection, if already switched to HTTP protocol.
16 | httpIgnoreUnkCertAuth | Ignore unknown certification authority. Allows control to ignore the error when the certification authority is unknown. This should normally be avoided by installing the CA root information. This option is supported only by the newer versions of WinInet in IE 4.0 and higher.
32 | httpIgnoreCertRevocation | Ignores certificate revocation problems. Allows control to ignore the errors related to certificate revocation.


StateConstants

Enumerates values of the State property.

Value | Constant | Description
0 | httpCompleted | Completed. The control has completed an operation, and/or currently is idle.
1 | httpStartingRequest | Starting Request. The control is starting the request sequence.
2 | httpResolvingHost | Resolving Host. The control is looking up the IP address of the specified host computer.
3 | httpHostResolved | Resolved Host. The control successfully found the IP address of the specified host computer.
4 | httpConnecting | Starting a connection. The control is connecting to the host computer.
5 | httpConnected | Connected to server. The control successfully connected to the host computer.
6 | httpRequesting | Requesting Host. The control is sending a request to the host computer.
7 | httpRequestSent | Request sent. The control successfully sent the request.
8 | httpReceivingResponse | Receiving response. The control is receiving a response from the host computer.
9 | httpResponseReceived | Response received. The control successfully received a response from the host computer.
10 | httpClosing | Closing a connection. The control is disconnecting from the host computer.
11 | httpClosed | Connection closed. The control successfully disconnected from the host computer.
12 | httpError | Error in communications. An error occurred in communicating with the host computer.
13 | httpResponseCompleted | Response completed. The request has completed and all data has been received.
14 | httpAborting | Releasing resources as quickly as possible.


PowerTCP Web Enterprise Tool

Support Licensing Distribution WebASP Tool/Web Tool Comparison

Windows 95/98 Security Compatibility

Use the Web Enterprise Tool to communicate with Web Servers using HTTP (Hypertext Transfer Protocol) and HTTPS (HTTP with Secure Socket Layer encryption). Use supporting objects for superior HTML page parsing.

Control | Description
CertificateList Control | Present the user with an interface to select certificates
Web Control | Access Web page documents (supports secure HTTP).
WebASP Control | Wininet independent control used to access Web page documents using WebMessage Object (supports secure HTTP).

Supporting Objects

Object | Description
Certificate Object | Digital certificate.
Certificates Object | Collection of Certificate Objects.
CertificateStore Object | Use to gain access information about a digital certificate.
Cookie Object | Manages cookies.
Cookies Object | Collection of Cookie Objects.
DartStream Object | Manages file access and buffers.
DartStreams Object | Collection of DartStream Objects
DartStrings Object | High-powered C++ optimized string manipulation collection.
HttpHeaderFields Object | Manages strings that represent the Request and Response header.
HttpVariable Object | Stores Http variables.
HttpVariables Object | Collection of HttpVariable Objects.
WebMessage Object | Decodes and presents HTTP requests and responses as a simple object.
WebPage Object | A web page parsing object that can be used to conduct search and retrieval operations on the specified page.
WebResource Object | Describes a WebResource on the page.
WebResources Object | A high-performance collection for rapid access to many WebResource Objects.
WebTable Object | Represents an individual table on an HTML page.
WebTables Object | Collection of WebTable Objects.

Sample Projects

The following sample projects demonstrate how to use the WebASP Control of the Web Enterprise Tool:

Project | Description
PageFetch | Demonstrates a simple HTTP application that fetches a web page. Delphi5, VC 6, Visual Basic 6.
Post | Demonstrates a simple HTTP POST application. Visual Basic 6, Visual C++ 6, Delphi5
AutoUpdate | Demonstrates how to build your own auto-update application. Visual Basic 6.
SOAPClient | Demonstrates how to build a SOAP client with the WebASP control. Delphi5, VC6, VB6, BCB5, PB6

The following sample projects demonstrate how to use the Web Control of the Web Enterprise Tool:

Project | Description
Link Spider | Demonstrates a web link spider application. Visual Basic 6.
Page Fetch | Demonstrates a simple HTTP application that fetches a web page. Visual Basic 6, Visual C++ 6, PowerBuilder 6, BCB4, and Delphi 5.
Post | Demonstrates a simple HTTP POST application. Visual Basic 6.
WebAlive | Compares the download performance of any 2 web pages. Useful for comparing the relative performance of mirrored Web Servers. Visual Basic 6.

Online ASP Samples

These ASP samples demonstrate the use of the WebASP Control of the Web Enterprise Tool on the Internet. You must have an active Internet connection to view these Samples.

Sample

Description

ImageGet

Demonstrates WebResource collection by performing a Google search on a keyword and displaying associated images.

News Ticker

Demonstrates the parsing power of the WebPage Object Find method by extracting headlines from a news web page and displaying them in a JavaScript news ticker.

These ASP samples demonstrate the use of the Web Control of the Web Enterprise Tool on the Internet. You must have an active Internet connection to view these Samples.

Sample

Description

Stock Quotes on the Web

The Web Control accesses Yahoo's stock quote service. what is the current value of your portfolio.

Web Site Scraping

The Web Control downloads the page you specify, and displays the header and body in edit boxes.

HTML Mail on the Web

The Web Control gets a page (including all images) and then sends it to the specified Email address.


HTTP Control Comparison

Web Tool and Web Enterprise Tool Comparison

This table illustrates the differences between the Web Tool and the WebEnterprise Tool.

 | Web Tool | WebEnterprise Tool
Dependencies: | Is dependent on WinInet.dll and Microsoft's approach to handling HTTP functionality. | No dependency on WinInet.dll. We have replicated and improved the functionality in our product. For this to work properly on Windows 95/98/Me, please see Windows 95/98 Security Compatibility.
Architecture: | A flat design, providing a more object-oriented approach than Microsoft's API implementation. | A purer, object-oriented design with a versatile WebMessage Object that is available as a Response and Request property.
Power: | No method for this functionality. | A Command method that enables any command to be sent to the server.
Security Flexibility: | Security information passed with HTTP commands. No security events as all secure interactivity is handled by WinInet.dll. | Events let you respond to secure connectivity. Properties let you specify security information, separating HTTP commands and security settings.
HTML Parsing | No method for this functionality. | Objects that represent web pages and tables, allowing advanced parsing of the HTML head and body.
HTML Resource Collecting | No method for this functionality. | WebResource object acts as collector and manager of all resources on a web page.
Object-Oriented Flexibility: | These values are returned with command methods from the server. | The Body, Headers, Cookies, and Variables of a message are represented as collections in the Request and Response properties.


Developing With the WebASP Control Without Security

The WebASP Control relies on the latest Microsoft security API to process all HTTPS requests. This means that you must follow the instructions outlined in the Windows 95/98 Security Compatibility page if you wish to develop or deploy using HTTPS functionality on Windows 95 or 98. If you or your clients need ONLY HTTP functionality, then the security update is NOT needed, but if you attempt to use secure functionality without the required update an error willl result. If secure functionality is needed, but you are unable to use or distribute Microsoft's security update, then you will need to use the Web Control for development. We recommend using the WebASP control whenever possible as that is far more powerful than the Web Control.


Cookie Object

Properties Example

Use the Cookie Object to manage cookies. Cookies are passed between client and server in the header of the request or response.

An HTTP cookie is a mechanism for storing a small amount of data on the client. When the client makes subsequent requests, the data in each cookie is sent back to the server. Refer to RFC 2109 for more information on cookies.


All Property

Example

Sets or returns the entire cookie string.

Syntax

Object.All

Part | Description
Object | Evaluates to a Cookie Object.

Data Type

String

Remarks

If writing a value to this property, the passed string is parsed and used to populate the Cookie Object.

Reading from this property returns the contents of the entire cookie string. You can then use the string as a value for a "Set-Cookie:" header.


Domain Property

Example

DNS-registered domain name of the server from which the cookie originated.

Syntax

Object.Domain

Part | Description
Object | Evaluates to a Cookie Object.

Data Type

String

Remarks

The client software uses this value to locate this cookie in the client's cookie store and send the cookie with all future requests to the specified domain.


Expires Property

Example

Date and time the cookie expires.

Syntax

Object.Expires

Part | Description
Object | Evaluates to a Cookie Object.

Data Type

Date

Remarks

When set to 0, the cookie only persists on the client browser until the browser closes.


Name Property

Example

Name of the cookie.

Syntax

Object.Name

Part | Description
Object | Evaluates to a Cookie Object.

Data Type

String

Remarks

This property provides the case-sensitive name of the cookie. The name may contain any combination of alphanumeric characters, including spaces.


Path Property

Example

URL path associated with the cookie.

Syntax

Object.Path

Part | Description
Object | Evaluates to a Cookie Object.

Data Type

String

Remarks

When a document is requested with the value of this property as the root, the cookie is sent with the request.


Secure Property

Example

Specifies if the cookie is secure.

Syntax

Object.Secure

Part | Description
Object | Evaluates to a Cookie Object.

Data Type

Boolean

Remarks

When set to True, the client only sends the cookie back over a secure connection.


SubValues Property

Example

Collection of HttpVariable Objects that represent the subvalues of a cookie.

Syntax

Object.SubValues

Part | Description
Object | Evaluates to a Cookie Object.

Data Type

HttpVariables Object

Remarks

Use this property to access the values of cookies that contain multiple values. For example, the following cookie contains multiple values:

Cookie1 = SubValue1 = "Val1" & SubValue2 = "Val2"

Use the Value property to access the entire value string (SubValue1 = "Val1" & SubValue2 = "Val2"). The Value property is also used for cookies that contain only one value.


Value Property

Example

Complete value of the cookie.

Syntax

Object.Value

Part | Description
Object | Evaluates to a Cookie Object.

Data Type

String

Remarks

Specifies the complete value of a cookie even if it has subvalues.


Cookies Object

Properties Methods

Collection of Cookie Objects.


Add Method

Example

Add a Cookie Object to the collection.

Syntax

Object.Add Cookie

Part | Description
Object | Evaluates to a Cookies Object.
Cookie | Cookie Object to add to the collection.


Item Method

Example

Provides array subscript access to the collection.

Syntax

Value = Object.Item Index

Part | Description
Object | Evaluates to a Cookies Object.
Index | Long or String. Specifies a cookie by position in the collection or by name.
Value | Cookie Object. Contains requested cookie.

Remarks

If Index is specified as a Long value, it must be between 1 and Count. If Index is specified as a String value, the first Cookie Object in the collection with the matching case-sensitive name is returned.

Error Codes

The Item method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1

  • ptNoBufferSpace


Remove Method

Example

Remove a cookie from the collection.

Syntax

Value = Object.Remove Index

Part | Description
Object | Evaluates to a Cookies Object.
Index | Long or String. Specifies a cookie by position in the collection or by name.
Value | Cookie Object. Contains removed cookie.

Remarks

If Index is specified as a Long value, it must be between 1 and Count. If Index is specified as a String value, the first Cookie Object in the collection with the matching case-sensitive name will be removed.

Error Codes

The Remove method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1 (Index out of range or name not found)

  • ptNoBufferSpace


DartStreams Object

Properties Methods

Collection of DartStream Objects.

Miscellaneous

Product | All PowerTCP Tools
Prog ID | Dart.DartStreams.1
Create | Yes
File | DartSock.dll
Dependencies | None
Threading | Apartment Model
Licensed | No


Add Method

Add a DartStream Object to the collection.

Syntax

Position = Object.Add Stream

Part | Description
Object | Evaluates to a DartStreams Object.
Stream | DartStream Object to be added to the collection.
Position | New value of the Position property.

Error Codes

The Add method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1

  • ptInvalidParam2

  • ptNoBufferSpace


Item Method

Set or return a DartStream Object based on an index.

Syntax

Value = Object.Item Index

Part | Description
Object | Evaluates to a DartStreams Object.
Index | Long. Indicates position in collection to return.
Value | DartStream Object

Error Codes

The Item method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1

  • ptInvalidParam2

  • ptNoBufferSpace


Remove Method

Remove a DartStream Object from the collection based on an index.

Syntax

Value = Object.Remove Index

Part | Description
Object | Evaluates to a DartStreams Object.
Index | Long. Indicates position in collection to be removed.
Value | DartStream Object removed from the collection.

Error Codes

The Remove method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1

  • ptInvalidParam2

  • ptNoBufferSpace


DartStrings Object

Properties Methods

Collection of strings. The DartStrings Object is used as a supporting formatting object for several PowerTCP objects and controls.

Miscellaneous

Product | PowerTCP Winsock Tool
Prog ID | Dart.DartStrings.1
File | DartSock.dll
Dependencies | None
Threading | Apartment Model
Licensed | No


DartStrings Object Usage

The DartStrings Object adds some useful enhancements for string manipulation. It is most commonly used in PowerTCP as a formatting object that can easily carry out some basic manipulations, but it can also be used for other purposes. The Add and Clear methods are fast, taking linear (O(n)) time based on the number of strings (n = # of strings), as does the All property. The Delimiter method takes constant time, so any overhead related to it can usually be ignored. This performance and functionality enables some useful operations. For example, by combining the Delimiter property, Add method and All property, a rapid find/replace of any string to any string can be carried out on large files. Additionally, Dartstrings provides this capability for wide characters, so that these manipulations can be done in many different languages, not just ASCII.

This example VB find/replace code shows the power of the Dartstrings (and Dartstream). It took 500 milliseconds to replace spaces with carriage return/line feeds in a 1.12MB file of email addresses (reading from in, writing to out), including the time required by file I/O. This is about 50 times as fast as Word and Notepad, and can be done with arbitrary strings by changing the delimiter values used.

Option Explicit

Private Sub Command1_Click()

On Error GoTo OnError

Command1.Enabled = False

Dim Stream As New DartStream

Stream.FileMode = createExisting

Stream.FileName = App.Path + "\in.txt"

Dim Strings As New DartStrings

Strings.Delimiter = Space(1)

Strings.Add Stream.ReadString

Dim Stream2 As New DartStream

Stream2.FileMode = createAlways

Stream2.FileName = App.Path + "\out.txt"

Strings.Delimiter = vbCrLf

Stream2.Write Strings.All

GoTo Done

OnError:

Debug.Print "ERROR #" + CStr(Err.Number) + ": " + Err.Description

Done:

Command1.Enabled = True

End Sub


All Property

Concatenates and returns all the strings in the collection. The Delimiter string is inserted between each string in the collection.

Syntax

Object.All

Part | Description
Object | Evaluates to a DartStrings Object.

Data Type

String

Remarks

Read-only. For example, if the Delimiter is ":" and the strings in the collection are "ab", "cd", and "ef", then this property returns "ab:cd:ef".

The All property takes linear (O(n)) time for strings of less than 50kB, and 0(n*size/50kB) for longer strings, where n is the number of independent strings and size is the size of the resultant string in kB. The method used is about 50-100 times as fast as most similar techniques in use today.


Delimiter Property

Separates a string into substrings when adding a string to the collection with the Add method. Also used as a separator when reading the All property.

Syntax

Object.Delimiter

Part | Description
Object | Evaluates to a DartStrings Object.

Data Type

String

Remarks

Read-only. The default value is empty ("").

This Delimiter property takes constant time to get or set.


Item Property

Returns or sets a string in the collection.

Syntax

Value = Object.Item ( Index )

Object.Item ( Index ) = Value

Part | Description
Object | Object expression that evaluates to a DartStrings Object.
Index | String or Long. Specifies a substring to search for or an index into the collection.
Value | String.

Data Type

The string found in the collection or an empty string if none is found.

Remarks

When Index is a Long, its value must be between one and the collection's Count property. When specifying Index as a String, the first string in the collection matching all the characters of the substring is returned (strings are compared starting with the leftmost character, and are case-insensitive).

This is a parameterized property instead of a (read-only) method so that it can be used to set a value.

Error Codes

The Add method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptInvalidParam1 (When reading the property, Index is not a Long or String. When setting the property, Index is not a Long between 1 and Count or the sub-string is not found.)


Add Method

Add one or more strings to the collection.

Syntax

Object.Add Item [ , Index ]

Part | Description
Object | Object expression that evaluates to a DartStrings Object.
Item | String. What is added to the collection.
Index | Optional Long. Defaults to the end of the collection. Specifies where in the collection the string should be inserted. If multiple substrings are added, then they will start at this index. Should be at least 1 and no greater than 1 more than the Count property.

Remarks

Item is parsed for the Delimiter, and is segmented into substrings if found. All substrings are added as individual strings to the collection.

For example, if the Delimiter is ":" and Item is "ab:cd:ef", then "ab", "cd", and "ef" are added.

The Add method takes linear (O(n)) time, where n is the number of delimited strings being added.

Error Codes

The Add method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptInvalidParam2 (Index is not between 1 and Count + 1)


Find Method

Return a string from the collection where the beginning substring matches the specified string. The string comparison is case-insensitive, starting with the leftmost character.

Syntax

Value = Object.Find SubString [ , StartAfter ]

Part | Description
Object | Object expression that evaluates to a DartStrings Object.
SubString | String. The substring to match. Matching starts with the first character.
StartAfter | Optional Long. Defaults to 0. On input, it contains the index in the collection after which to start the search. On return, it is updated to the index of the string returned by Find. If no string is found, StartAfter is set to 0.
Value | String. Returns the string found or "" if none was found.

Remarks

When specifying StartAfter, use an index between 0 and one less than the collection's Count property. Specifying a value of 0 (the default) starts with the first string in the collection.

Error Codes

The Find method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptInvalidParam2 (StartAfter is not between 0 and Count - 1)


Remove Method

Remove a string from the collection.

Syntax

[ Value = ] Object.Remove Index

Part | Description
Object | Object expression that evaluates to a DartStrings Object.
Index | String or Long. Specifies a substring to search for or an index into the collection.
Value | String. Returns a copy of the string removed.

Remarks

When Index is a Long, it must be between one and Count. When Index is a string, the first string in the collection matching all the characters of the specified substring is returned (both strings are compared starting with the left-most character and is case insensitive).

Error Codes

The Remove method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptInvalidParam1 (Index is not a Long or String)


HttpHeaderFields Object

Properties Methods Constants Example

Use the HttpHeaderFields Object to manage HTTP header fields. This collection is similar to the DartStrings Object, with additional methods for processing header fields.

The collection also provides an Item method to support reading by position, symbolic field name, or matching string.


All Property

Concatenation of all strings in the collection with separating CR/LF pairs.

Syntax

Object. All

Part | Description
Object | Evaluates to a HttpHeaderFields Object.

Data Type

String

Remarks

Read-only. Returns the header fields as a single string.


Add Method

Add one or more header fields to the collection. If multiple header fields are provided, they must be separated by CR/LF pairs.

Syntax

Count = Object.Add Label, Value [ , Unique ]

Part | Description
Object | Evaluates to a HttpHeaderFields Object.
Label | HttpLabelConstants. Specifies the symbolic name for the header label being added. Use httpNull if Value includes the label.
Value | String. Value to be added to the collection.
Unique | Optional Boolean. Indicates the header field should replace any existing header fields with the same label. The default value is False.
Count | Long. Number of strings added to the collection.

Remarks

A header field is a label, followed by a colon, followed by a space, followed by one or more values separated by semicolons.

This method allows you to add header fields in the following two ways:

  • If Label is not httpNull, then Value is prepended with the string representation of the specified Label and a space before adding it to the collection.

  • If Label is httpNull, then Value must contain a complete header field, including the label.

Error Codes

The Add method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1

  • ptNoMemory


Find Method

Find a header field in the collection.

Syntax

Value = Object.Find Label [ , LabelString ] [ , StartAfter ]

Part | Description
Object | Evaluates to an HttpHeaderFields Object.
Label | HttpLabelConstants. Specifies the symbolic name for the label to find. If httpNull, the LabelString parameter is used as the search string.
LabelString | Optional String. Specifies the label to find. Use this parameter to find a non-standard label (not available in HttpLabelConstants). When using this parameter, Label should be httpNull.
StartAfter | Optional Long. Indicates the index to start the search after. StartAfter is updated to reflect the index of the header field found.
Value | String. Value containing the value of the requested header field, without the label.

Remarks

This method searches the collection for a label. On return, StartAfter is updated to reflect the index of the label found, allowing you to find multiple header fields having the same label.

StartAfter cannot be a constant because the method updates its value. Providing a constant value for StartAfter generates a run-time error. Specifying StartAfter with a value of zero starts the search at the beginning of the collection. StartAfter is set to 0 and "" is returned if the item is not found.

Error Codes

The Find method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1

  • ptInvalidParam3

  • ptNoBufferSpace


Item Method

Provides array subscript access to the collection.

Syntax

Value = Object.Item Index

Part | Description
Object | Evaluates to an HttpHeaderFields Object.
Index | Long. Specifies a header field by position in the collection.
Value | String. Value containing requested header field.

Error Codes

The Item method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1

  • ptNoBufferSpace


Remove Method

Remove a header field from the collection.

Syntax

Value = Object.Remove Label [ , Index ]

Part | Description
Object | Evaluates to an HttpHeaderFields Object.
Label | HttpLabelConstants. Specifies the symbolic name for the header field to be removed. If httpNull, the Index parameter will be used to specify the header field to be removed.
Index | Optional Long. Identifies a header field by position in the collection. When using this parameter Label must be set to httpNull.
Value | Returned String. Contains the removed header field. An empty string indicates that the label was not found.

Remarks

This method removes the first header field matching Label or the header field at Index in the collection.

Error Codes

The Remove method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1 (invalid label type)

  • ptInvalidParam2 (Index is out of range)

  • ptNoBufferSpace


HttpLabelConstants

Some HttpHeaderFields Object methods use a symbolic name for the Label parameter. The following labels are specified as the Common Internet Message Headers. These headers are explained in RFC 2076.

Value | Constant | Description
1 | httpAccept | "Accept:"
2 | httpAcceptCharset | "Accept-Charset:"
3 | httpAcceptEncoding | "Accept-Encoding:"
4 | httpAcceptLanguages | "Accept-Language:"
5 | httpAcceptRange | "Accept-Range:"
6 | httpAge | "Age:"
7 | httpAllow | "Allow:"
8 | httpAuthorization | "Authorization:"
9 | httpCacheControl | "Cache-Control:"
10 | httpConnection | "Connection:"
11 | httpContentEncoding | "Content-Encoding:"
12 | httpContentLanguage | "Content-Language:"
13 | httpContentLength | "Content-Length:"
14 | httpContentLocation | "Content-Location:"
15 | httpContentMD5 | "Content-MD5:"
16 | httpContentRange | "Content-Range:"
17 | httpContentType | "Content-Type:"
18 | httpDate | "Date:"
19 | httpETag | "ETag:"
20 | httpExpect | "Expect:"
21 | httpExpires | "Expires:"
22 | httpFrom | "From:"
23 | httpHost | "Host:"
24 | httpIfMatch | "If-Match:"
25 | httpIfModifiedSince | "If-Modified-Since:"
26 | httpIfNonMatch | "If-Non-Match:"
27 | httpIfRange | "If-Range:"
28 | httpIfUnmodified | "If-Unmodified:"
29 | httpLastModified | "Last-Modified:"
30 | httpLocation | "Location:"
31 | httpMaxForwards | "Max-Forwards:"
32 | httpPragma | "Pragma:"
33 | httpProxyAuthenticate | "Proxy-Authenticate:"
34 | httpProxyAuthorization | "Proxy-Authorization:"
35 | httpRange | "Range:"
36 | httpReferer | "Referer:"
37 | httpRetryAfter | "Retry-After:"
38 | httpServer | "Server:"
39 | httpTE | "TE:"
40 | httpTrailer | "Trailer:"
41 | httpTransferEncoding | "Transfer-Encoding:"
42 | httpUpgrade | "Upgrade:"
43 | httpUserAgent | "User-Agent:"
44 | httpVary | "Vary:"
45 | httpVia | "Via:"
46 | httpWaring | "Warning:"
47 | httpWWWAuthenticate | "WWW-Authenticate:"
48 | httpCookie | "Cookie:"
49 | httpSetCookie | "Set-Cookie:"


HttpVariable Object

Properties

Use HttpVariable Objects to store and manage variables. The value is a Variant type and may reference another object, data type, or value.


Name Property

Example

Name of the variable.

Syntax

Object. Name

Part | Description
Object | Evaluates to a HttpVariable Object.

Data Type

String

Remarks

Variable names are case-insensitive and may contain any combination of alphanumeric characters, including spaces.


Value Property

Example

Value of the variable.

Syntax

Object. Value

Part | Description
Object | Evaluates to a HttpVariable Object.

Data Type

Variant

Remarks

You can use this property to associate the object with any Variant.


HttpVariables Object

Properties Methods

Collection of HttpVariable Objects.


Item Property

Example

Sets or reads the value of an HttpVariable Object in the collection.

Syntax

Object. Item (Index)

Part | Description
Object | Evaluates to an HttpVariables Object.
Index | String expression. Specifies the variable name to reference. If a variable of that name is set and does not exist, then a variable of that name is automatically created.

Data Type

Variant

Remarks

Variable names are case-insensitive. If the variable name being set does not exist, then an HttpVariable with that name will be created. If the variable name being read does not exist, then a ptInvalidParam1 run-time error is generated, so error handling should be used.

Error Codes

The Item property may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptInvalidParam1 (When read, variable does not exist or index is out of range.)


Add Method

Example

Add an HttpVariable Object to the collection.

Syntax

Object.Add Variable

Part | Description
Object | Evaluates to an HttpVariables Object.
Variable | HttpVariable Object to add to the collection.

Error Codes

The Add method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptNoBufferSpace


Index Method

Provide array subscript access to the HttpVariables Object.

Syntax

Variable = Object.Index Index

Part | Description
Object | Evaluates to an HttpVariables Object.
Index | Long. Identifies the variable in the collection based on position.
Variable | Returned HttpVariable Object. Located at Index in the collection.

Error Codes

The Index method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptInvalidParam1


Remove Method

Example

Remove an HttpVariable from the collection.

Syntax

Object.Remove Index

Part | Description
Object | Evaluates to a HttpVariables Object.
Index | Long or String. Specifies an HttpVariable by position in the collection or by name.

Remarks

If Index is specified as a Long value, it must be between 1 and Count. If Index is specified as a String value, the first HttpVariable in the collection with the matching case-sensitive name will be removed.

Error Codes

The Remove method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1 (Index out of range or name not found)

  • ptNoBufferSpace


WebASP Control

Properties Methods Events Constants Example

Use the WebASP Control to communicate with Web Servers using HTTP (Hypertext Transfer Protocol) and HTTPS (HTTP with Secure Socket Layer encryption). The WebASP Control improves upon the Web Control with the following features:

  1. No dependency upon Wininet.dll (Secure HTTP uses the Crypto API available with NT 4.0 sp 4 and higher, Windows 2000, and Windows ME).

  2. The new WebMessage Object separates the data from the protocol, making the WebASP Control more intuitive and easy-to-use.

Miscellaneous

Product | PowerTCP Web Enterprise Tool
Prog ID | Dart.Web.1
File | DartWebASP.dll
Dependencies | Wsock32.dll (Winsock v. 1.1), DartSock.dll, DartSecure.dll, DartWebUtil.dll, DartCertificate.dll
Threading | Apartment Model
Licensed | Yes


WebASP Control Usage

The WebASP Control improves upon the Web Control by incorporating a more natural, object-oriented approach and more functionality. The WebASP Control is used to manage an HTTP session, making use of the WebMessage Object to represent an individual request/response message. A minimum communication begins by setting the request Url using the WebMessage Object and performing a method (in this example, GET is used).

WebASP1.Request.Url = "www.dart.com"

WebASP1.Get

Other options which could have been used here include proxy management, certificate management, security management, cookie management, posting variables, and putting and posting files. Upon a successful GET, the response from the server will be contained within the Response Object.

' check for good server response from GET

If WebASP1.Response.Status = 200 then

MsgBox "Good Get"

End If

The WebMessage object allows easy manipulation of the various parts of an HTTP response.

' look at headers and body

Debug.Print WebASP1.Response.Headers.All

Debug.Print WebASP1.Response.Body.All

Other supporting objects allow advanced HTML parsing and resource collection. Parsing is achieved using the WebPage and WebTable Objects, by first setting the WebPage Object's Source property.

Dim WebPage1 as new WebPage

' set WebPage Object's source using response from server, this property

' can also be set by use of a local file

WebPage1.Source = WebASP1.Response.Body.ReadString

Once the Source property has been set to a valid source, the WebPage Object can be used in conjunction with the WebTable and WebResource Object for advanced HTML parsing and resource collecting. These objects can be used to parse Metacontent, Tables, Frames, Paragraphs, and HTML Resources.


WebASP Control Blocking Sample

By default, the Timeout property is a positive value which specifies that methods should wait until complete. This is called blocking and greatly simplifies the sequencing of operations and error recovery. Consider the following code snippet:

' Use the Timeout property to establish blocking behavior.

WebASP1.Timeout = 20000

' specify the url we wish to fetch

WebASP1.Request.Url = "www.dart.com"

' perform the fetch

WebASP1.Get

Note that the sequencing of the initialization, the transfer, and the tear-down is as easy as it gets. In addition, errors are handled automatically – any failure will result in program termination. The fact that all the code executed without error implies that all went well and the data is in the string.

Now, add error handling so the application won't terminate because of a failure. A simple modification accomplishes this:

On Error GoTo OnError

' Use the Timeout property to establish blocking behavior.

WebASP1.Timeout = 20000

' specify the url we wish to fetch

WebASP1.Request.Url = "www.dart.com"

' perform the fetch

WebASP1.Get

Exit Sub

OnError:

' if an error occurs, this will execute

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

So far so good, but now we want to put up a progress indication for our user. To do this, we need event notification during the course of the download. We get this by putting code in the Progress event as follows:

Private Sub WebASP1_Progress(ByVal Method As DartWebASPCtl.WebMethodConstants, ByVal Status As DartWebASPCtl.WebStatusConstants, ByVal Count As Long, ByVal Size As Long)

If Size > 0 Then

Label1.Caption = (Count / Size) * 100 & "% done..."

End If

End Sub

The final code sample would look similar to the following:

Private Sub Command1_Click()

On Error GoTo OnError

' Use the Timeout property to establish blocking behavior.

WebASP1.Timeout = 20000

' specify the url we wish to fetch

WebASP1.Request.Url = "www.dart.com"

' perform the fetch

WebASP1.Get

' Display Page to Text Box

Dim WebPage1 As New WebPage

WebPage1.Source = WebASP1.Response.Body.ReadString

Text1.Text = WebPage1.Source

Exit Sub

OnError:

' if an error occurs, this will execute

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Private Sub WebASP1_Progress(ByVal Method As DartWebASPCtl.WebMethodConstants, ByVal Status As DartWebASPCtl.WebStatusConstants, ByVal Count As Long, ByVal Size As Long)

If Size > 0 Then

Label1.Caption = Round((Count / Size) * 100, 0) & "% done..."

End If

End Sub

The code now puts up progress information, but there are still limitations:

If the user wants to exit the application, you will have to defeat it because you can't allow him/her to unload things while you are executing the Get method.

If the user initiates another activity through the user interface, you'll have to ensure he/she doesn't affect the Get method (by calling another method or capturing the thread for any length of time).

These limitations can be overcome by using non-blocking techniques.


WebASP Control Non-Blocking Sample

If we can structure our code so that sequencing is controlled by code in our events, then we will be able to accomplish the Get method illustrated in the Blocking Sample in a non-blocking way. We have traded the benefit of sequential code for the greater benefit of robust code that allows PowerTCP to operate relatively independently of your application and any additional processing you may be doing for your user:

Private Sub Command1_Click()

' Use the Timeout property to establish blocking behavior.

WebASP1.Timeout = 20000

' specify the url we wish to fetch

WebASP1.Request.Url = "www.dart.com"

' perform the fetch

WebASP1.Get

Exit Sub

OnError:

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Private Sub WebASP1_Progress(ByVal Method As DartWebASPCtl.WebMethodConstants, ByVal Status As DartWebASPCtl.WebStatusConstants, ByVal Count As Long, ByVal Size As Long)

' display status to user

If Size > 0 Then

Label1.Caption = Round((Count / Size) * 100, 0) & "% done..."

End If

' check to see if GET completed ok and display text when it does

If Method = webGet And Status = webOk Then

Dim WebPage1 As New WebPage

WebPage1.Source = WebASP1.Response.Body.ReadString

Text1.Text = WebPage1.Source

End If

End Sub


MaxMemBuffer Property

Maximum number of memory bytes used when receiving the body of a request.

Syntax

Object.MaxMemBuffer

Part | Description
Object | Evaluates to a PowerTCP control

Data Type

Long

Remarks

The default value is 4096 (bytes).

The Body of a request is initially memory-buffered. If the size of the request body exceeds MaxMemBuffer, the PowerTCP control switches to file buffering (the FileName is set to an appropriate value). This file is temporary and is removed after the event returns. Switching to a file buffered object provides better memory use and faster responses to client requests.

Generally, only POST and PUT requests will contain data within the body of the request.


Redirect Property

Determines if auto redirection is to take place.

Syntax

Object.Redirect

Part | Description
Object | Evaluates to a WebASP Control.

Data Type

WebRedirectConstants

Remarks

Often times, during a Get or a Head method call, the server will return a 3xx error code. The 3xx error codes represent a class of errors that indicate that the requested object has either permanently moved or has been temporarily moved to a different URL. In addition to returning the 3xx code, the server may also indicate the new location where the object can be found.

When the Web control does follow a redirection request, the returned Response.Url property will contain the updated request location specified by the server.


RemoteCertificate Property

The certificate from the remote machine.

Syntax

Object.RemoteCertificate

Part | Description
Object | Evaluates to a WebASP Control.

Data Type

Certificate Object

Remarks

This certificate is downloaded from the remote machine and verified. Depending on this property and the WebSecurity Constants, the transmission is accepted or rejected.


Request Property

Example

WebMessage Object, the request to be sent to the server.

Syntax

Object.Request

Part | Description
Object | Evaluates to a WebASP Control.

Data Type

WebMessage Object

Remarks

The Command, Get, Head, Put, and Post methods will send the request contained in this property.

The WebMessage Object will perform all the required formatting of the request before sending it to the server for processing.


Response Property

Example

WebMessage Object, the response from the server.

Syntax

Object.Response

Part | Description
Object | Evaluates to a WebASP Control.

Data Type

WebMessage Object

Remarks

The result of a Command, Get, Head, Put, or Post method is returned in this property.


Command Method

Example

Use the Command method to send any command to the server.

Syntax

Object.Command Command

Part | Description
Object | Evaluates to a WebASP Control.
Command | String that specifies the command to send.

Remarks

The command method may be used to send any standard HTTP 1.0 or 1.1 command, in addition to any extension commands your server may support.

Errors

The Command method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptNotInitialized

  • ptNetworkDown

  • ptAddressInUse

  • ptHostNotFound

  • ptTryAgain

  • ptNoData

  • ptBlocked

  • ptAbort

  • ptAddressNotAvailable

  • ptConnectionRefused

  • ptNetworkUnreachable

  • ptNoBufferSpace

  • ptTimeout

  • ptNotConnected

  • ptNetworkReset

  • ptNoBufferSpace

  • ptConnectionAborted

  • ptConnectionReset

  • ptNoCertificate

  • ptAuthentication

  • ptProtocol

  • ptError(Invalid URL)

  • ptFile


Get Method

Example

Use the Get method to retrieve data from the server.

Syntax

Object.Get

Part | Description
Object | Evaluates to a WebASP Control.

Remarks

This method uses the HTTP GET command to retrieve content from an HTTP server. Before using this method, you must set the Request.Url property.

The Progress event will fire multiple times as the operation proceeds. When the Timeout property is greater than zero, this method blocks until the command completes or an error occurs. When the Timeout property is zero, this method immediately returns and the transfer operates in the background.

If Body has nothing in it in response to a Get on a file that has no bytes, add an empty Dartstream to the Body.

Errors

The Get method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptNotInitialized

  • ptNetworkDown

  • ptAddressInUse

  • ptHostNotFound

  • ptTryAgain

  • ptNoData

  • ptBlocked

  • ptAbort

  • ptAddressNotAvailable

  • ptConnectionRefused

  • ptNetworkUnreachable

  • ptNoBufferSpace

  • ptTimeout

  • ptNotConnected

  • ptNetworkReset

  • ptNoBufferSpace

  • ptConnectionAborted

  • ptConnectionReset

  • ptNoCertificate

  • ptAuthentication

  • ptProtocol

  • ptError(Invalid URL)

  • ptFile


Head Method

Example

Use the Head method to retrieve header data from the server.

Syntax

Object.Head

Part | Description
Object | Evaluates to a WebAsp Control.

Remarks

This method uses the HTTP HEAD command to retrieve only the header portion of a response from an HTTP server. Before using this method, you must set the Request.Url property.

The Progress Event will fire multiple times as the operation proceeds. When the Timeout Property is greater than zero, this method blocks until the command completes or an error occurs. When the Timeout Property is zero, this method immediately returns and the transfer operates in the background.

Only a message header is sent to the server and, as a result, if the Request.Body property contains data, it will not be sent.

Note: Error 12152 will be generated if the server does not support Head requests.

Errors

The Head method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptNotInitialized

  • ptNetworkDown

  • ptAddressInUse

  • ptHostNotFound

  • ptTryAgain

  • ptNoData

  • ptBlocked

  • ptAbort

  • ptAddressNotAvailable

  • ptConnectionRefused

  • ptNetworkUnreachable

  • ptNoBufferSpace

  • ptTimeout

  • ptNotConnected

  • ptNetworkReset

  • ptNoBufferSpace

  • ptConnectionAborted

  • ptConnectionReset

  • ptNoCertificate

  • ptAuthentication

  • ptProtocol

  • ptError(Invalid URL)

  • ptFile


Post Method

Example

Use the Post method to send data to the server for processing.

Syntax

Object.Post

Part | Description
Object | Evaluates to a WebASP Control.

Remarks

This method uses the HTTP POST command to send data to the HTTP server for processing. Before using this method, you must set the Request.Url property.

The Progress event will fire multiple times as the operation proceeds. When the Timeout property is greater than zero, this method blocks until the command completes or an error occurs. When the Timeout property is zero, this method immediately returns and the transfer operates in the background.

The contents of Request.Header, Request.Body, and Request.Variables are sent to the server when using this method.

If the Request.Body collection contains more than one object, the Web control will add the proper MIME formatting to the message sent to the server. The MIME encoding is very similar to that used in E-Mail messages and allows the server the find the start and end of each Body part in the message.

In addition, the Body item must have a variable name that the server uses to identify each part of a message. Each DartStream.Ref property in the Request.Body property must contain the name of the variable associated with that part.

In addition to Request.Body, the Web control will also format and send any form variables specified in the Request.Variables property.

Errors

The Post method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptNotInitialized

  • ptNetworkDown

  • ptAddressInUse

  • ptHostNotFound

  • ptTryAgain

  • ptNoData

  • ptBlocked

  • ptAbort

  • ptAddressNotAvailable

  • ptConnectionRefused

  • ptNetworkUnreachable

  • ptNoBufferSpace

  • ptTimeout

  • ptNotConnected

  • ptNetworkReset

  • ptNoBufferSpace

  • ptConnectionAborted

  • ptConnectionReset

  • ptNoCertificate

  • ptAuthentication

  • ptProtocol

  • ptError(Invalid URL)

  • ptFile


Put Method

Example

Use the Put method to store data on the server.

Syntax

Object.Put

Part | Description
Object | Evaluates to a WebASP Control.

Remarks

This method uses the HTTP PUT command to store data on the HTTP server. Before using this method, you must set the Request.Url property.

The Progress event will fire multiple times as the operation proceeds. When the Timeout property is greater than zero, this method blocks until the command completes or an error occurs. When the Timeout property is zero, this method immediately returns and the transfer operates in the background.

Both the Request.Header and Request.Body are sent to the server when using this method. In addition, the Body collection may contain only one object. If the Request.Body collection contains more than one object, only the first object the collection will be sent.

If the request resource is already existing on the server at the given URL, the server will replace the existing resource with the resource contained within the request. If the server successfully modifies the resource, the server will return a 200 (OK) or a 204 (No content) to indicate a successful request completion.

If the resource does not exist in the specified location, a new file will be created and the server will return a status of 201 (Created) to indicate success.

WARNING! The Put Method allows users to alter files on server's file system. Ensure appropriate security measures are taken to avoid any potential damage to the Web Server.

Errors

The command method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptNotInitialized

  • ptNetworkDown

  • ptAddressInUse

  • ptHostNotFound

  • ptTryAgain

  • ptNoData

  • ptBlocked

  • ptAbort

  • ptAddressNotAvailable

  • ptConnectionRefused

  • ptNetworkUnreachable

  • ptNoBufferSpace

  • ptTimeout

  • ptNotConnected

  • ptNetworkReset

  • ptNoBufferSpace

  • ptConnectionAborted

  • ptConnectionReset

  • ptNoCertificate

  • ptAuthentication

  • ptProtocol

  • ptError(Invalid URL)

  • ptFile


Authenticate Event

Example

Fires when the remote host has sent a certificate to be authenticated.

Syntax

Private Sub Object_Authenticate ( [ Index As Integer , ] RemoteCertificate As Certificate, TrustedRoot As Boolean, ValidDate As Boolean, ValidSignature As Boolean, ValidName As Boolean, Valid As Boolean )

Part | Description
Object | Evaluates to a WebASP Control.
Index | Integer. Array index if the object is part of an array.
RemoteCertificate | Certificate Object. Remote host's certificate.
TrustedRoot | Boolean. Indicates if the certificate was from a Trusted Root Authority (CA).
ValidDate | Boolean. Indicates if the current date-time is within the certificate's life span.
ValidSignature | Boolean. Indicates if the certificate has a valid signature.
ValidName | Boolean. Indicates if the certificate's name matches the hostname.
Valid | Boolean. Set this value to True to authenticate the remote certificate or set it to False to deny it.

Remarks

Typically, the remote certificate is rejected if TrustedRoot, ValidDate, ValidSignature, or ValidName is False. This event allows you to ease or strengthen the restrictions on the remote host's certificate. To authenticate a certificate if one or all of the parameters are False, set Valid to True.


Progress Event

Example

Fires when a method has completed, the server has sent a reply, or progress information is available.

Syntax

Web1_Progress(Method as WebMethodConstants, Status as WebStatusConstants, Count as Long, Size as Long)

Part | Description
Method | WebMethodConstants indicates the method that the event pertains to.
Status | WebStatusConstants indicates the status of the method.
Count | Long specifies the number of bytes that have been received or sent (so far) for the transfer that is currently in progress. The value will normally fall between zero and Size. Only valid when Status is webSending or webReceiving, and is zero at other times.
Size | Long specifies the total number of bytes in the message transfer currently in progress. This value is constant during any single transfer. Only valid when Status is webSending or webReceiving, and is zero at other times.

Remarks

For each request sent using the Command, Get, Head, Put or Post methods, there will be two sets of Progress events. The first series of events will update the progress of the request being sent to the server. The Status parameter for these events will be webSending. The next series of Progress events updates while the Web control retrieves the response from the server. In this case the Status parameter will be set to webReceiving.

It is possible for Size to be zero in some cases. If Status is webReceiving and the server did not provide a Content-Length header field, Size will be zero.


Redirect Event

Example

Fires when the remote host has sent a certificate to be authenticated.

Syntax

Private Sub Object_Redirect ( [ Index As Integer , ] SecureSource As Boolean, SecureDestination As Boolean, Allow As Boolean )

Part | Description
Object | Evaluates to a WebASP Control.
Index | Integer. Array index if the object is part of an array.
SecureSource | Boolean. Indicates whether the source page was secure.
SecureDestination | Boolean. Indicates whether the destination page is secure.
Allow | Boolean. Set this value to True to allow the redirection to occur or false to deny it.

Remarks

The initial value of Allow is dependent on the Security property of the WebASP control. For example, if Security is set to webSecureAllowRedirectHTTP and SecureSource is True and SecureDestination is False, then Allow will be false. If you want to allow the redirection to occur anyway, set allow to True.


WebMethodConstants

Enumerates the values of the Method parameter of the Progress event. Indicates the method that initiated the event.

Value

Constant

Description

0

webCommand

Command method

1

webGet

Get method

2

webHead

Head method

3

webPost

Post method

4

webPut

Put method


WebSecurityConstants

Value | Constant | Description
0 | webSecureNormal | Apply all server certificate security checks.
1 | webSecureDisable | Accept all certificates passed from the server.
2 | webSecureIgnoreDate | Accept otherwise valid certificate if date has expired.
4 | webSecureIgnoreCA | Accept otherwise valid certificate if Certificate Authority Root is not known.
8 | webSecureIgnoreSignature | Accept otherwise valid certificate if signature cannot be verified.
16 | webSecureIgnoreName | Accept otherwise valid certificate if name (CN) does not match the host name.


WebStatusConstants

Value

Constant

Description

0

webOk

The method has completed with positive status.

1

webBad

The method has completed with status indicating an error

2

webSending

Indicates intermediate events during the sending of a message. Useful for percentage indication on a status display.

3

webReceiving

Indicates intermediate events during the receipt of a message. Useful for percentage indication on a status display.

4

webRedirecting

The control has received a redirect response, and is proceeding to a new Url. Only fired when the Redirect property is set to TRUE.


WebMessage Object

Properties Constants Example

The WebMessage Object encapsulates the details of an HTTP Request and Response in a easy to understand object. In addition the WebMessage object handles all the formatting details required for a client and HTTP Server to communicate effectively.

The WebMessage Object is compatible with the MS SOAP library (view example).

Miscellaneous

Product | PowerTCP Web Enterprise Tool
Prog ID | Dart.WebMessage.1
File | DartWebASP.dll
Dependencies | Wsock32.dll (Winsock v. 1.1), DartSock.dll, DartSecure.dll, DartWebUtil.dll, DartObjects.dll, DartCertificate.dll
Threading | Apartment Model
Licenced | No


Body Property

Example

A DartStream object that represents the body of the message.

Syntax

Object.Body

Part | Description
Object | Evaluates to a WebMessage Object.

Data Type

DartStream Object

Remarks

For Get and Head request messages this property is ignored during the generation of the request message. For Put and Post request messages, and error will be thrown if the Body property does not contain any data.

This property will be filled in for response messages in reply to Command, Get, Post, and Put messages. The Head method will not result in a response that contains a message with a body.

If a Body collection contains data other than the DartStream object during a Put or Post request, the WebASP Control will apply the proper Mime formatting before sending the request to the server.


Content Property

Read from this property to encode the message or write to this property to initialize the object.

Syntax

Object.Content = EncodedMessage
EncodedMessage = Object.Content ([ReturnType])

Part | Description
Object | Evaluates to a WebMessage Object.
ReturnType | ReturnTypeConstants specifies the return value, either a String or Byte array.

Data Type

String or Byte Array

Remarks

When setting this property, the ReturnType parameters are ignored if provided. Setting this property causes a re-initialization of the object. By setting this property to "" (an empty string), the object is cleared of all content.

When reading this property, ReturnType defaults to msgString. The message is dynamically encoded when this property is read.

This property is commonly used to populate a Message object or to get an encoded message that may be saved or sent to an HTTP server.

Error Codes:

The Content property may return the following errors (Refer to the ErrorConstants topic for a complete list of error codes):

  • ptNoBufferSpace

  • ptFile

  • ptInvalidParam1

  • ptInvalidParam2


Cookies Property

Example

Collection of Cookie objects that are contained in the message.

Syntax

Object.Cookies

Part | Description
Object | Evaluates to a WebMessage Object.

Data Type

DartStreams Object

Remarks

For request messages, the Cookies property represents the Http cookies that are to be sent to the server.

For response messages, this Cookies property represents the cookies sent to the client from the server.


FilesToPost Property

Example

Set this property to fill it with files to Post.

Syntax

Object.FilesToPost = Files

Part | Description
Object | Evaluates to a WebMessage Object.
Files | Evaluates to a DartStreams Object.

Remarks

For Post messages, an error will be thrown if this property is not set and Body is not set. This method supersedes setting Body. This method is used by passing a Dartstreams filled with files to be posted.


Header Property

Example

The HttpHeader labels associated with this message.

Syntax

Object.Header

Part | Description
Object | Evaluates to a WebMessage Object.

Data Type

HttpHeaderFields Object

Remarks

For request messages, any changes made to the HttpHeaderFields object will be sent to the server. This property can be used to add additional headers such as those headers used to control caching.

For response messages, this objects represents the headers returned from the server.


KeepAlive Property

Example

Use this property to prevent the control from creating a new connection for each request.

Syntax

Object.KeepAlive

Part | Description
Object | Evaluates to a WebMessage Object.

Data Type

Boolean

Remarks

For requests that set the Version property to HTTP/1.1 or greater, this property controls whether a connection to the server is kept open after the request is completed.

Under HTTP/1.0, the connection is closed when the response is completely sent by the server. If multiple requests to the same server are required, the delay in establishing a new connection to a server for each request can significantly increase the time to request multiple objects.

In an effort to increase the efficiency of the HTTP protocol, HTTP/1.1 allows the client to specify that a connection shall remain open after the response is sent. This allows a single connection to handle more than one request from a client.

The default value for the KeepAlive property is TRUE.


Password Property

Example

Use this property to gain access to URLs that require authentication.

Syntax

Object.Password

Part | Description
Object | Evaluates to a WebMessage Object.

Data Type

String

Remarks

The Password property is used in conjunction with the Username property to authenticate a user when accessing protected URLs.

Both the Username and the Password property are only to be used in a request message. They are not filled in or used for a response message.

NOTE: The Password and Username property can only be used to verify users when HTTP Authentication is used. These properties have no effect when user authentication is accomplished by posting information back to the server. In this case use the Post method to send user information back to the server.

If only the Password or the Username property is provided, no authentication information will be sent with the request.

The Web Control currently only supports Basic (clear-text) and Digest (encoded) forms of HTTP Authentication as described in RFC 2617.


Status Property

Example

The response code from the last completed HTTP request.

Syntax

Object.Status

Part | Description
Object | Evaluates to a WebMessage Object.

Data Type

Long

Remarks

The Status property should be used to determine the result of a response message. This property is undefined and has no meaning for a request message.

The Status property is read only.


StatusText Property

Example

The human readable status from the last request.

Syntax

Object.StatusText

Part | Description
Object | Evaluates to a WebMessage Object.

Data Type

String

Remarks

The StatusText property should be used only to display extra response information to a user. This property is undefined and has no meaning for a request message.

The StatusText property is read only.


Url Property

Example

Specifies the name of the resource for the Command, Get, Head, Post and Put methods.

Syntax

Object.Url

Part | Description
Object | Evaluates to a WebMessage Object.

Data Type

String

Remarks

The Url property is the complete description of a resource to be acted upon. When this property is modified the UrlSecure, UrlPort, UrlHost, UrlPath, and UrlQueryString properties are updated. This can cause problems if not used correctly. For example, if the the Url is set to "localhost" and the UrlPort is set to "33", the Url property has the expected value.

WebASP1.Request.Url = "localhost"
WebASP1.Request.UrlPort = 33
' WebASP1.Request.Url now = "http://localhost:33"

If the Url port is set to 33 then the Url is set, the result may be unexpected.

WebASP1.Request.UrlPort = 33
WebASP1.Request.Url = "localhost"
' WebASP1.Request.Url now = "http://localhost"

Error Codes:

The Url property may return the following errors (Refer to the ErrorConstants topic for a complete list of error codes):

  • ptError (Invalid Url)


UrlHost Property

Example

Use the UrlHost property to specify the host of the Url property.

Syntax

Object.UrlHost

Part | Description
Object | Evaluates to a WebMessage Object.

Data Type

String

Remarks

The UrlHost property is automatically updated when the Url property is written to. In addition, if the UrlHost property is modified, the Url property will be updated to reflect the new value of the UrlHost property.

Error Codes:

The UrlHost property may return the following errors (Refer to the ErrorConstants topic for a complete list of error codes):

  • ptError (Invalid path value)


UrlPath Property

Example

Use the UrlPath property to specify the path of the requested resource.

Syntax

Object.UrlPath

Part | Description
Object | Evaluates to a WebMessage Object.

Data Type

String

Remarks

The UrlPath property is automatically updated when the Url property is written to. In addition, if the UrlPath property is modified, the Url property will be updated to reflect the new value of the UrlPath property.

Error Codes:

The UrlPath property may return the following errors (Refer to the ErrorConstants topic for a complete list of error codes):

  • ptError (Invalid path value)


UrlPort Property

Example

Use this property to specify the TCP port to which the request is to be sent.

Syntax

Object.UrlPort

Part | Description
Object | Evaluates to a WebMessage Object.

Data Type

Long

Remarks

The UrlPort property is automatically updated when the Url property is written to. In addition, if the UrlPort property is written to, the Url property is modified to indicate the new port being used.

Error Codes:

  • ptInvalidProperty (port must be between 1 and 65535)


UrlQueryString Property

Example

Use this property to specify the extra part of the Url Property when setting the Request object of the WebASP Control or read this property to get the query string value when using the WebResource Object.

Syntax

Object.UrlQueryString

Part | Description
Object | Evaluates to a PowerTCP Control.

Data Type

String

Remarks

When setting the Request object of the WebASP Contol, the UrlQueryString property is automatically updated when the Url property is written to. In addition, if the UrlQueryString property is modified, the Url property will be updated to reflect this modification.


UrlSecure Property

Example

Use this property to send the request over a secure connection.

Syntax

Object.UrlSecure

Part | Description
Object | Evaluates to a WebMessage Object.

Data Type

Boolean

Remarks

The UrlSecure property is automatically updated when the Url property is written to. In addition, if the UrlSecure property is modified, the Url property is updated to reflect the new value of the UrlSecure property.


UserAgent Property

UserAgent

Returns or sets a value that identifies the user agent in all communications with a server.

Syntax

Object.UserAgent

Part | Description
Object | Evaluates to a WebMessage Object

Data Type

String

Remarks

This property modifies the User-Agent header label that is sent in all requests to the server. The default value is "PowerTCP WebTool".


Username Property

Example

Use this property to gain access to URLs that require authentication.

Syntax

Object.Username

Part | Description
Object | Evaluates to a WebMessage Object.

Data Type

String

Remarks

The Username property is used in conjunction with the Password property to authenticate a user when accessing protected URLs.

Both the Username and the Password property are only to be used in a request message. For response messages, they are not filled in or used.

NOTE: The Password and Username property can only be used to verify users when HTTP Authentication is used. These properties have no effect when user authentication is accomplished by posting information back to the server. In this case use the Post method to send user information back to the server.

If only the Password or the Username property is provided, no authentication information will be sent with the request.

The Web control currently only supports Basic (clear-text) and Digest (encoded) forms of HTTP Authentication as described in RFC 2617.


Variables Property

Example

Collection of HttpVariable objects that are to be sent with the request.

Syntax

Object.Variables

Part | Description
Object | Evaluates to a WebMessage Object.

Data Type

String

Remarks

The Variables property is only used by the control during for the request of a Post method call. All other requests types will ignore the contents of this property. In addition, this property has no meaning for response messages, and as a result will never be filled in by the control.

Many times during a Post operation there is a need to send Name/Value pairs entered by a user back to the server. (For example, filling out an address request page.) The Variables property allows you to specify a name and value for each field of a form. The control will properly format each of the variables, along with any data, or files specified in the Body property into a proper message when the Post method is called.

NOTE: The Web Control will only accept variables that have a .Value of type string.


Version Property

Returns or sets a value that selects the version of the HTTP Protocol to use. Set this to webHTTP11 to use version 1.1 of the HTTP Protocol.

Syntax

Object.Version

Part | Description
Object | Evaluates to a WebMessage Object.

Data Type

WebVersionConstants

Remarks

The default value is webHTTP11.


WebVersionConstants

Enumerates the version of HTTP to use.

Value | Constant | Description
0 | webUnsupported | HTTP is not supported
1 | webHTTP10 | Use HTTP version 1.0
2 | webHTTP11 | Use HTTP version 1.1


WebPage Object

Properties Methods Example

A web page parsing object that returns common HTML values and conducts search and retrieval operations on the specified page.


MetaNames Property

Example

The meta names that are available on the web page.

Syntax

Object.MetaNames

Part | Description
Object | Evaluates to a WebPage Object.

Data Type

DartStrings

Remarks

Returns a collection of available meta names for the web page (ex: “Keywords” or “Description”).


PrimaryFrame Property

Example

The URL of the primary frame for the web page.

Syntax

Object.PrimaryFrame

Part | Description
Object | Evaluates to a WebPage Object.

Data Type

String

Remarks

If the current HTML page does not use frames, this value will be an empty string. The PrimaryFrame property will only work in cases where nested frames aren't used.


Resources Property

Example

A collection of WebResource objects.

Syntax

Object.Resources

Part | Description
Object | Evaluates to a WebPage Object.

Data Type

WebResources

Remarks

The WebResources collection is used to store all WebResources of a WebPage such as links, images, applets, etc. See WebResourceConstants topic for types of WebResources stored.


Source Property

Example

The HTML source from the page.

Syntax

Object.Source

Part | Description
Object | Evaluates to a WebPage Object.

Data Type

String

Remarks

Contains the HTML source for the Web page. This property must be set before any parsing or resource collecting can take place. See the Source Property Example for various examples of how to set this property.


Title Property

Example

The title for the current web page.

Syntax

Object.Title

Part | Description
Object | Evaluates to a WebPage Object.

Data Type

String

Remarks

The Title property contains the text included in the "TITLE" tag of an HTML page.


UrlHost Property

Example

The UrlHost property specifies the host URL of the value in the Source property.

Syntax

Object.Title

Part | Description
Object | Evaluates to a WebPage Object.

Data Type

String

Remarks

The UrlHost property needs to be manually updated to reflect the domain of the HTML data in the Source Property. This property is necessary to identify resources in HTML that use relative paths. If this value is left blank, the Get method in the WebResource object will not be able to download resources identified by just a relative path.

NOTE!!! The Get Method of the WebResource Object WILL NOT PROPERLY WORK if the UrlHost property has not been manually updated to reflect the domain name of the WebPage.Source property.


WebTables Property

Example

A collection of WebTable objects that represent all the tables on the web page.

Syntax

Object.WebTables

Part | Description
Object | Evaluates to a WebPage Object.

Data Type

WebTables

Remarks

This collection is used to store all the tables on a page, with every table represented as a Table object. It can be used to count the number of tables on a page, or to query the tables themselves for information.


Find Method

Example

Returns text or HTML source found between two tokens.

Syntax

Value = Object.Find (BeginToken, EndToken)

Part | Description
Object | Evaluates to a WebPage Object.
BeginToken | String. Sets the starting position for each search.
EndToken | String. Sets the ending position for each search.
Value | DartStrings collection of text or HTML source that is returned from the search.

Data Type

DartStrings

Remarks

The Find method performs a case sensitive search. As there may be multiple items that match the search characteristics, the DartStrings collection will be filled with every matching case. The text or HTML source that is returned does not include the two tokens. The Find method will attempt to search within the HTML <BODY></BODY> tags. If no such tags are found, the Find method assumes the file is a text file and searches all the text.

The Find method is quite flexible and can be used several different ways depending on the parameters specified. These are illustrated below using "X" and "Y" to represent any token.

Start Token | End Token | Find Method Actions
X | Y | Returns a Dartstrings collection filled with every matching case of text that occurs between the two tokens.
X | X | Returns a Dartstrings collection filled with every matching case of text that occurs between the two tokens.
null | X | Returns a Dartstring filled with the text that occurs before the first X.
X | null | Returns a Dartstring filled with the text that occurs after the last X.


MetaContent Method

Example

Returns all the metadata for a metaname.

Syntax

Value = Object.MetaContent (MetaName)

Part | Description
Object | Evaluates to a WebPage Object.
MetaName | String. The metaname of the content to be retrieved
Value | String. Text that is returned from the search.

Data Type

String

Remarks

The content for a matching metaname is returned from this search. The MetaNames collection can be used to iterate through the possible metanames that will return information. The MetaContent performs a case-sensitive search, so "Keywords" is different from "keywords".


Paragraphs Method

Example

Returns a collection of text blocks that meet a specified minimum number of characters.

Syntax

Value = Object.Paragraphs ([MinBlockSize])

Part | Description
Object | Evaluates to a WebPage Object.
MinBlockSize | Optional Integer. The minimum size of a block of text. Default is 120 characters.
Value | DartStrings. The information returned from the search.

Data Type

DartStrings

Remarks

This search returns a block of text as defined by the minimum character size and a carriage return or line feed that designates the end of a text block. Every block of text is stored as a string in the DartStrings collection. To remove HTML tags, use the Text method.


Text Method

Example

Returns the text from HTML source.

Syntax

Value = Object.Text (leavetokens, BeginToken, EndToken)

Part | Description
Object | Evaluates to a WebPage Object.
leavetokens | Boolean. Set if you want the tokens returned.
BeginToken | String. Sets the starting position.
EndToken | String. Sets the end position.
Value | String. Text with the HTML source stripped.

Data Type

String

Remarks

The Text method accepts any block of HTML source and will return the text with all the HTML tags removed. The Text method will not extract script from the source, this will have to be removed manually. If the tokens are used, the Text method will return all text except for the text between the tokens. This method can be used with a number of other methods in the WebPage object when just text is desired.


WebResource Object

Properties Methods Constants Example

An object that describes a WebResource on the page.


Url Property

Example

The URL of a WebResource.

Syntax

Object.Url

Part | Description
Object | Evaluates to a WebResource Object.

Data Type

String

Remarks

Example: www.dart.com/help/Chapter1.html?aaa=111;bbb=222


UrlAltText Property

Example

The alternative text that is provided for a WebResource.

Syntax

Object.UrlAltText

Part | Description
Object | Evaluates to a WebResource Object.

Data Type

String

Remarks

If this information is not available for the WebResource it is returned as an empty string.


UrlName Property

Example

The name of a WebResource.

Syntax

Object.UrlName

Part | Description
Object | Evaluates to a WebResource Object.

Data Type

String

Remarks

Example: Chapter1.html


UrlPath Property

Example

The relative URL of a WebResource.

Syntax

Object.UrlPath

Part | Description
Object | Evaluates to a WebResource Object.

Data Type

String

Remarks

Example: /help/Chapter1.html


UrlType Property

Example

The WebResource type.

Syntax

Object.UrlType

Part | Description
Object | Evaluates to a WebResource Object.

Data Type

WebResourceConstants

Remarks

Returns the WebResource type for a WebResource. If the WebResource type is undetermined, resUnknown will be returned. WebResource types include images, hyperlinks, applets, and other resources and are further illustrated here.


Get Method

Example

Initiates a download of the WebResource to a local directory.

Syntax

Value = Object.Get (LocalDirectory,Overwrite)

Part | Description
Object | Evaluates to a WebResource object.
LocalDirectory | String. The local directory used to store the downloaded WebResource.
Value | Boolean. Returns true if the transfer is successful.
Overwrite | Boolean. Set this to true if overwriting is desired.

Data Type

Boolean

Remarks

When a WebResource is downloaded it will be placed in the local directory, followed by the virtual directory for the WebResource. Make sure to set the WebPage UrlHost property to the page on which all WebResources are found before using this method or relative links will not work.

NOTE!!! The Get Method of the WebResource Object WILL NOT PROPERLY WORK if the UrlHost property has not been manually updated to reflect the domain name of the WebPage.Source property.


WebResourceConstants

Value | Constant | Description
0 | resUnknown | WebResource designated with an unknown tag.
1 | resA | WebResource designated with the <a> tag.
2 | resImg | WebResource designated with the <img> tag.
3 | resObject | WebResource designated with the <object> tag.
4 | resEmbed | WebResource designated with the <embed> tag.
5 | resApplet | WebResource designated with the <applet> tag.
6 | resMap | WebResource designated with the <map> tag.
7 | resArea | WebResource designated with the <area> tag.
8 | resBgsound | WebResource designated with the <bgsound> tag.
9 | resIframe | WebResource designated with the <iframe> tag.
10 | resFrame | WebResource designated with the <frame> tag.
11 | resBody | WebResource designated with the <body> tag.


WebResources Object

Properties Methods Example

A high-performance collection for rapid access to many WebResource objects. The WebResources object provides a simple way to enumerate through a list of WebResources that are found within a string of HTML source. This collection is written for rapid access to large quantities of Resources. It has been tested with thousands of resources, and will perform well under heavy load.


Item Method

Provides array subscript access to the collection.

Syntax

Value = Object.Item Index

Part | Description
Object | Object expression that evaluates to a PowerTCP control.
Index | Long. Specifies an item of the collection by position in the collection.
Value | String. Value containing requested item.

Error Codes

The Item method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1

  • ptNoBufferSpace


WebTable Object

Properties Methods Example

An object that describes an individual table located on an HTML page. Cell values can be referenced directly.


Caption Property

Example

Returns the caption for this table.

Syntax

Object.Caption

Part | Description
Object | Evaluates to a WebTable Object.

Data Type

String

Remarks

Read-only. The caption is returned as text including HTML tags To remove HTML tags, use the Text method.


ColumnCount Property

Example

Returns the number of columns in this table.

Syntax

Object.ColumnCount

Part | Description
Object | Evaluates to a WebTable Object.

Data Type

Integer

Remarks

Read-only. Column headings are not counted as columns.


RowCount Property

Example

Returns the number of rows in this table.

Syntax

Object.RowCount

Part | Description
Object | Evaluates to a WebTable Object.

Data Type

Integer

Remarks

Read-only. Row headings are not counted as rows.


Source Property

Example

Returns the HTML source for this table.

Syntax

Object.Source

Part | Description
Object | Evaluates to a WebTable Object.

Data Type

String

Remarks

Read-only. This property includes all the HTML source found between the tags for this table. Nested tables are not removed.


Summary Property

Example

Returns the summary for this table.

Syntax

Object.Summary

Part | Description
Object | Evaluates to a WebTable Object.

Data Type

String

Remarks

Read-only. The value of the Summary property is the text between the quotes after the summary attribute of a table.


Cell Method

Example

Returns the contents of the cell for the specified cell in this table.

Syntax

Value = Object.Cell (Row, Column)

Part | Description
Object | Evaluates to a WebTable object.
Row | Integer. The row number of the cell to query.
Column | Integer. The column number of the cell to query.
Value | String. The contents of cell

Data Type

String

Remarks

The cell contents are returned as HTML source. To remove HTML tags, use the Text method. Nested tables that may be included in the cell are discarded. Any values a nested table will contain can be accessed from the WebTables collection as a unique WebTable object. If the table has spanned cells (merged cells), all cells with the span attribute will return the same data.


WebTables Object

Properties Methods Example

A collection of WebTable objects. Tables provide a simple way to enumerate through tables found on a web page. No distinction is made for tables that are embedded within other tables (nested tables). If a table contains no data and is only used for formatting, that table will be ignored by this collection, and thus not included in the count. The WebTables object is accessed as a property of the WebPage object.


PowerTCP WebServer Tool

Support Licensing Distribution Certificate Manager Scalability Security Overview

Windows 95/98 Security Compatibility

Build web applications in any familiar software development environment. Use the WebServer Tool to add web-based access to existing compiled applications, or to provide any level of web-based processing for building complex web applications.

Control | Description
CertificateList Control | Present the user with an interface to select certificates
Service Control | Turn your Web Application into an NT service
WebServer Control | Web server on a control

Supporting Objects

Object | Description
Certificate Object | Digital certificate.
Certificates Object | Collection of Certificate Objects.
CertificateStore Object | Provides access to local system storage of digital certificates.
Cookie Object | Manages cookies.
Cookies Object | Collection of Cookie Objects.
DartStream Object | Manages file access and buffers.
HttpHeaderFields Object | Manages strings that represent the Request and Response header.
HttpVariable Object | Stores Session or Request variables.
HttpVariables Object | Collection of HttpVariable Objects.
Request Object | Decodes and presents an HTTP request as a simple object.
Response Object | Provides an easy way to build the response you wish to send to the client.
Session Object | Identifies and stores client information across multiple connections.
Sessions Object | Collections of Session Objects.

Certificate Management Support

The Certificate Manager Application, included with this product, provides a convenient utility for managing local security certificates.

Sample Projects

The following sample projects demonstrate how to use the WebServer Tool:

Project | Description
CookieTest | Demonstrates a method for testing if a client accepts cookies. Visual Basic 6.
MultiInterface | Demonstrates how to create an application that can serve a similar interface on both the Windows operating system and the Internet. This also includes a secondary Web Server that acts as a remote security control for the application. Visual Basic 6.
SOAPServer | Demonstrates how to build a SOAP Server using the WebServer Tool. Visual Basic 6, VC6, Delphi 5, and PB6
Web FAQ | Demonstrates a simple web-based database application that shows adding and presentation of answers to Frequently Asked Questions. Visual Basic 6.
Web Forum | Contains the source code for the same WebForum as on the Dart Web site. Visual Basic 6.
Web Server | Simple HTTP/HTTPS Server that displays static web pages. Visual Basic 6, VC6, Delphi5
Web Service | To demonstrate how to use the PowerTCP WebServer Tool to write a simple HTTP/HTTPS web server. When compiled, this application can be run as a Service using the PowerTCP NT Service Control. Visual Basic 6
XMLDatabase | Demonstrates how to use the WebServer Control to serve XML code. This sample requires ADO version 2.1 or higher and Microsoft's XML Parser v3 or higher. Please refer to the Readme file installed with the sample or the sample itself if you need to download the latest versions from Microsoft . Visual Basic 6.


Windows 95/98 Security Compatibility WebServer Tool

Windows 95/98 Security Compatibility

(Please note that if you are not using SSL-based security with the WebServer Tool, you can deploy your solution on any platform without the Microsoft Security Support update)

Until recently, the SSL/TLS Security Support Provider on the Windows 9x platforms was not fully implemented. Microsoft addressed this issue through a series of procedures we will explain below. For more in-depth information, please see http://support.microsoft.com/support/kb/articles/q276/2/45.asp.

The following steps must be incorporated before installing any secure-dependent products.

  1. Make sure you have the latest Dart update from http://www.dart.com/support.

  2. Install Internet Explorer 5.01 or higher with 128-bit encryption.

  3. Install Directory Service Client software for Windows 9x. This program can be found on any Windows 2000 CD in the \Clients\Win9x folder. The name of this application is DSCLIENT.EXE. If you do not have a Windows 2000 CD, please contact Microsoft Developer Support. For more information on this software, please see http://msdn.microsoft.com/library/periodic/period99/support.htm.

  4. Enable the SChannel Security Support Provider in the registry.

    • Start Registry Editor (Regedit.exe).

    • Locate the following key in the registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders

    • On the Edit menu, click Modify, and then modify the following registry value:

      • Value Name: Security Providers

      • Data Type: REG_SZ

      • Value: Append ",schannel.dll" (with comma, no quotes) to previous string.

Note: Certificates for use with the SSL/TLS protocols on Windows 95, 98, Me, and Windows NT 4.0 must be marked exportable. Windows 2000 SSL/TLS protocols do not have this requirement.


Request Object

Properties Example

Use the Request Object to get information about the current request. The requested file, variables and headers are parsed and presented as convenient properties.

The Request Object is compatible with the MS SOAP library (view example).


Body Property

Body of a request or response.

Syntax

Object.Body

Part | Description
Object | Evaluates to a Request Object or a Response Object.

Data Type

DartStream Object

Remarks

Read-only. When part of a Request Object, this property specifies the body of the request sent by the client. Generally, only PUT and POST requests contain data in this property.

When part of a Response Object, this property contains the body of the response that is to be sent back to the client. For GET requests, this property generally contains the requested file, or it contains an error message if the file is not found. For PUT and POST requests, this property contains a resulting HMTL page from the request. For HEAD requests, no Body is returned to the client.


Cookies Property

Collection of Cookie Objects.

Syntax

Object.Cookies

Part | Description
Object | Evaluates to a Request Object or a Response Object.

Data Type

Cookies Collection

Remarks

Read-only. When part of a Request Object, this property specifies the cookies sent by the client. When part of a Response Object, this property specifies the cookies to be sent to the client.

Note The cookie name "DartSession" is reserved for use by the WebServer Control. If a cookie of this name is added to the collection, an internally generated cookie of the same name replaces it. In addition, the "DartSession" cookie is removed from all request headers and does not appear in this collection.


FileName Property

Relative path and name of the requested document.

Syntax

Object.FileName

Part | Description
Object | Evaluates to a Request Object.

Data Type

String

Remarks

Read-only.

This property specifies the relative path of the requested document. When combined with the RootDirectory property, you can obtain the absolute path.


Files Property

Collection of DartStream Objects that represent the files sent with a request.

Syntax

Object.Files

Part | Description
Object | Evaluates to a Request Object.

Data Type

DartStreams Object

Remarks

Read-only.

This property contains objects only when a POST request includes the header Request.Header(httpContentType) = "multipart/form-data" and when files are included.

The Ref property of each DartStreams Object contains the variable name associated with each file. The FileName property of the DartStreams Object contains the relative path and name specified in the request, and the UniqueName property of the DartStreams Object contains the relative path and name with an optional extension (the extension is added if a file by the requested name already exists, but will reference the same file if no such file exists).

By default, the DeleteOnDestroy property for DartStreams Objects in this collection is set to True. Therefore, if the files are required to persist after the completion of the event, you must set DeleteOnDestroy to False.


Header Property

Collection of header fields associated with a request or response.

Syntax

Object.Header

Part | Description
Object | Evaluates to a Request Object or a Response Object.

Data Type

HttpHeaderFields Object

Remarks

Read-only.

The Body property allows you to alter the body of the transaction. When part of a Request Object, this property represents the header sent by the client. When part of a Response Object, this property specifies the header to send to the client. Refer to the Default Response Header topic for information on default values that are automatically generated by the WebServer control.

Do not add the status of the HTTP request to the header of the response. Instead, use the Status property and the StatusText property to specify the status of the request.

If an httpSetCookie header is added to this collection, a corresponding Cookie Object in the Cookies property is added (possibly replacing an existing object in the collection).


Password Property

Password sent with the request.

Syntax

Object.Password

Part | Description
Object | Evaluates to a Request Object.

Data Type

String

Remarks

Read-only.

If the authenticating type is BASIC, this property contains the password for the request. For DIGEST authentication types, check the Header property for information.

This property and the UserName property allow easy integration of custom Username/Password verification into web server applications.


Secure Property

Example

Indicates whether the request was sent over the secure or nonsecure connection.

Syntax

Object. Secure

Part | Description
Object | Evaluates to a Request Object.

Data Type

Boolean

Remarks

Read-only.

This property specifies if a request was made through a secure (SSL,TLS, or PCT) connection.


UrlQueryString Property

The query string of a resource.

Syntax

Object.UrlQueryString

Part | Description
Object | Evaluates to a Request Object.

Data Type

String

Remarks

An example value is: “aaa=111;bbb=222” if the actual URL is www.dart.com/help/Chapter1.html? aaa=111;bbb=222.


UserName Property

Username sent with the request.

Syntax

Object.UserName

Part | Description
Object | Evaluates to a Request Object.

Data Type

String

Remarks

Read-only. If the authenticating type is BASIC, this property contains the username for the request. For DIGEST authentication types, check the Header property for information.

This property and the Password property allow easy integration of custom Username/Password verification into web server applications.


Variables Property

Collection of variables defined as name/value pairs.

Syntax

Object.Variables

Part | Description
Object | Evaluates to a Request Object or a Session Object.

Data Type

HttpVariables Object

Remarks

Read-only.

This property contains a collection of:

  • Variables sent by the client when used as part of Request Object. The Value of client-generated variables only contains strings.

  • User-defined variables associated with the session when used as part of a Session Object. The Value in this case may contain any Variant type.


Version Property

HTTP version used in the request or response.

Syntax

Object.Version

Part | Description
Object | Evaluates to a Request Object or a Response Object.

Data Type

String

Remarks

Read-only.

The format of the version string is in the format of MajorVersion.MinorVersion (for example, "1.0" or "1.1").


Response Object

Use the Response Object to manage information being sent back to the client. It is automatically populated with information to fulfill the Request on entry to an event. If an error occurs while trying to load the requested file, the object is populated with a default error page. The contents of this object may be changed before it is sent to the client. Several default response header fields are automatically generated from Response.Body when the actual response is created.

The Response Object is compatible with the MS SOAP library (view example).


Delay Property

Signals the WebServer Control to not create and send the HTTP response after returning from the event.

Syntax

Object.Delay

Part | Description
Object | Evaluates to a Response Object.

Data Type

Boolean

Remarks

The default value is False.

This property is normally used only when scalability is desired. The Scalability topic discusses when this property might be useful. Refer to the Send method for more information.


Expires Property

Date and time after which this response should be considered invalid.

Syntax

Object.Expires

Part | Description
Object | Evaluates to a Response Object.

Data Type

Date

Remarks

When set to a value greater than 0, an "Expires:" header is added to the response with the specified date. This header notifies the client that a certain response is OK to be used from its cache for a given period of time.


Status Property

HTTP status included in the response.

Syntax

Object.Status

Part | Description
Object | Evaluates to a Response Object.

Data Type

HttpStatusConstants

Remarks

Use this property to create the status code returned to the client. These codes are explained in RFC 2616. When you set this property, StatusText is initialized to the standard textual value. If you want to define your own status code, set Status and StatusText to any desired value.


StatusText Property

Status textual message included in the response.

Syntax

Object.StatusText

Part | Description
Object | Evaluates to a Response Object.

Data Type

String

Remarks

This property is initialized when Status is set. It is returned to the client in the response. Status codes are explained in RFC 2616. If you want to define your own status code, set this property to your own custom value.


Send Method

Send an HTTP response when Delay is set to True. The Scalability topic discusses when this method might be useful.

Syntax

Object.Send

Part | Description
Object | Evaluates to a Response Object.

Remarks

If Delay is True, this method must be called at a later time to signal that the response may be sent. If not used to clear the response, resources accumulate, and communications over the connection halt.

To use this method for multi-threaded support, some additional programming is involved.


Session Object

Use the Session Object to manage information describing a client session. A session may persist over multiple connections and for a long period of time. A "per-session" cookie, described in the Id Property topic, is used to group connections into single sessions.

Note Session management does not work if the client browser does not support cookies or has cookie options disabled. In this case, a new session object is created for each connection. Use the Remove method to remove a session or set IdleTime to MaxIdleTime so it automatically expires.


Id Property

Unique identifier for the session over time and space.

Syntax

Object.Id

Part | Description
Object | Evaluates to a Session Object.

Data Type

String

Remarks

Read-only.

The ID is sent to the client in the form of a "per-session" cookie that is not stored. When the client makes subsequent requests, the ID is sent back to the server. This ID is then used to match a Session Object from the Sessions Object with a specific client.


IdleTime Property

Amount of time in minutes the session has been idle.

Syntax

Object.IdleTime

Part | Description
Object | Evaluates to a Session Object.

Data Type

Long

Remarks

This property returns the number of minutes since the last request for this session. This property can be reset to 0, allowing the session to stay idle in memory for longer than MaxIdleTime. The value of this property may also be increased to MaxIdleTime, forcing the session to be removed from the collection.

Note Time is rounded to the lowest minute, so a time of 4 minutes and 33 seconds becomes 4 minutes.


Item Method

Provides array subscript access into the collection.

Syntax

Value = Object.Item Index

Part | Description
Object | Evaluates to a Sessions Object.
Index | Long or String. Specifies a Session by position in the collection or by Id.
Value | Session Object requested.

Remarks

This method returns a Session from the collection. Index may be a long value between 1 and Count, or Index may be a string value specifying a Session ID to return.

Error Codes

The Item method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1 (Index is out of bounds or Id is not found)

  • ptNoBufferSpace


Remove Method

Remove a Session Object from the collection.

Syntax

Value = Object.Remove Index

Part | Description
Object | Evaluates to a Sessions Object.
Index | Long or String that specifies a Session by position in the collection or by Id.
Value | Session Object removed from the collection.

Remarks

This method removes a Session Object from the collection. Index may be a long value between 1 and Count, or Index may be a string value specifying a Session Id to remove.

Error Codes

The Remove method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptInvalidParam1 (Index is out of bounds or Id is not found)

  • ptNoBufferSpace


WebServer Control

Properties Methods Events Constants Example

Use the WebServer Control to build web-based applications from within Visual Basic or any other development environment that supports ActiveX controls. Now you can use the power of mainstream compiled languages to build robust web-based applications. The WebServer Control supports both non-secure and secure connections allowing highly sensitive data to be transferred without worry. Build integrated web-based applications containing dynamic content, or, with just two lines of code, build a simple web server to return static web pages.

Miscellaneous

Product | PowerTCP WebServer Tool
Prog ID | Dart.WebServer.1
File | DartWebServer.dll
Dependencies | DartSock.dll, DartServer.dll, DartSecure2.dll, DartWebUtil.dll, DartCertificate.dll
Threading | Apartment Model
Licensed | Yes


WebServer Control Usage

WebServer Usage

The following sections illustrate uses for the WebServer Control:

Simple Traditional Web Server

When your application starts, execute the following lines of code. HTML documents you put in the C:\WebPub directory are automatically accessed and sent to client browsers requesting them.

' establish the root directory for all web documents.

WebServer1.RootDirectory = "C:\WebPub"

' establish the location for the log.

WebServer1.LogDirectory = "C:\WebLog"

' start a non-secure connection on 80

WebServer1.Start , -1

Events fire as pages are requested or posted, but you do not have to write any code because the default operation is to send out requested pages.

Dynamic Web Server

The previous code is still required to start the WebServer, but additional code is required to build the dynamic web pages in memory. This occurs very quickly, since no disk access is required:

Private Sub WebServer1_Get(ByVal Session As DartWebServerCtl.ISession, ByVal Request As DartWebServerCtl.IRequest, ByVal Response As DartWebServerCtl.IResponse)

If Request.FileName = "helloworld.dwp" Then

Response.Body.Clear

Response.Body.Write "<HTML><BODY>"

Response.Body.Write "<H1> Hello World!</H1>"

Response.Body.Write "</BODY></HTML>"

Response.Status = httpOK

End If

End Sub

Default headers are automatically constructed if you do not provide them.


WebServer Control Comparison

WebServer Control Overview

Traditionally, web servers were basic software applications that served up documents (usually written in HTML, or hyper-text markup language) for browser viewing. As time went on, web servers added CGI and scripting support, so documents could be created from dynamic data sources. Now, companies want to host full-featured applications on the web.

Instead of starting with a large web server and fitting an application into it, use the WebServer Control to build an application in your development environment. The following table highlights the major differences between the WebServer Control and traditional web servers:

Feature | PowerTCP WebServer | Other Web Servers
Automatically accept connections, manage HTTP protocol details, clean up. | Yes. Add the WebServer Control to your project and control it programmatically. | Yes. Configure web servers to operate as desired.
Automatically serve up requested document files. | Yes. This is default behavior. | Yes. This is default behavior.
Web Application development support – flexibility and completeness. | Yes. Use all the power of Visual Basic, Visual C++, etc. to create dynamic content. | Yes, but CGI and scripting techniques are more limiting than compiled applications.
Web Application development support – productivity. | Exceptional. Compiled environments have the most complete development and debugging environments. | Fair to good. Integrated development environments are uneven (Visual InterDev, for example, is dim when compared to Visual Basic).
Scalability | Fair. The WebServer Control operates on a single thread. This is normally adequate for Intranet use, but slow individual pages can impact pending connections. | Very good. IIS, for example, processes each ASP document on its own thread so that slow individual pages do not slow down the whole system.
Integrated HTML Editing Support | Little. Any editor can be used to create HTML templates, and the template can be automatically loaded off disk, but it's ultimately up to the programmer to build the final HTML page. | Good. Visual InterDev, for example, has an integrated HTML editor.
Deployment | Superior. All run-time support can be distributed so application runs standalone. | Sometimes good, but always requires run-time support (an installed server that is compatible with your CGI or scripting code).
Integration with other applications. | Superior. Can be used to add a Web interface to any software product. | Limited. Requires run-time Web Server support that makes tight integration impractical.
Security. | Superior. Full support for HTTP/S, and you can easily manage your own custom security access. | Very good with HTTP/S, but custom security access is not as flexible.

To summarize, the WebServer Control is particularly well-suited for:

  • Adding a web servers interface to any existing application.

  • Creating any web application that benefits from the power of traditional compiled languages.

  • Creating any web application that needs to operate as a stand-alone application.

  • Applications with relatively small HTML manipulation needs when compared to computational needs.


DefaultFiles Property

Collection of default filenames.

Syntax

Object.DefaultFiles

Part | Description
Object | Evaluates to a WebServer Control.

Data Type

DartStrings Object

Remarks

Read-only.

This property specifies a collection of filenames to look for when the file name is not specified in the URL. This is an ordered collection with each filename in the collection being checked for existence in the URL directory and the first filename found is used. This property applies to the RootDirectory and all subdirectories.

Only filenames without path information are allowed. For example, "Index.html" is allowed, but "Products\Index.html" is an invalid collection entry.

This property defaults to four strings (in the following order) and does not usually require any modification:

  1. default.htm

  2. index.htm

  3. default.html

  4. index.html


LocalSecureAddress Property

Returns the local host address being used for accepting secure connections. The format is dot notation (for example, nnn.nnn.nnn.nnn). A non-empty value indicates the WebServer Control is accepting secure HTTP requests.

Syntax

Object.LocalSecureAddress

Part | Description
Object | Evaluates to a WebServer Control.

Data Type

String

Remarks

Read-only.

LocalSecurePort identifies the corresponding local port in use.


LocalSecurePort Property

Returns the port number being used for accepting secure connections. A non-zero value indicates the WebServer Control is accepting secure HTTP requests.

Syntax

Object.LocalSecurePort

Part | Description
Object | Evaluates to a WebServer Control.

Data Type

Long

Remarks

Read-only.

Values are between 0 and 65,535. LocalSecureAddress identifies the corresponding host address in use.


LogDirectory Property

Directory for daily log files. The default value is an empty string.

Syntax

Object.LogDirectory

Part | Description
Object | Evaluates to a WebServer Control.

Data Type

String

Remarks

This property controls if and where daily log files are created. When set to an empty string or the specified directory does not exist, logging of requests disabled. When a valid directory is specified, a new log file is created for each day in the specified directory. The file naming convention is as follows:

DARTDDMMYYYY.log

where:

  • DD – Two digit day

  • MM – Two digit month

  • YYYY – Four digit year. Y2K-compliant

For example, a filename of a log file created on February 13, 2001 would be:

DART13022001.log

The log file format is in the form outlined by the W3C Extended Log File Format. Each entry includes the time, requesting IP address, method, URL, and response code of the transaction. For example:

15:10:00 192.52.109.240 GET /somepage.html 200

means at 3:10pm a client at 192.52.109.240 requested the "somepage.html" file. The method of request was a GET, and the server responded with a status of 200(OK).


MaxIdleTime Property

Amount of time a session can remain idle before expiring.

Syntax

Object.MaxIdleTime

Part | Description
Object | Evaluates to a WebServer Control.

Data Type

Long

Remarks

The default value is 20 (minutes). This is a design-time property.

When set to 0, sessions never expire and the Remove method or the Clear method must be used to destroy sessions.

A session is considered idle when no session connections are being processed. IdleTime always increases and is automatically reset to 0 as each connection is closed. The SessionEnd event fires if IdleTime ever exceeds MaxIdleTime.


PlaceCookies Property

Controls whether cookies are set. Only affects the automatic Dart Cookies.

Syntax

Object.PlaceCookies

Part | Description
Object | Evaluates to a WebServer Control.

Data Type

Boolean

Remarks

Defaults to True. When set to True, sends a cookie with responses


PutLength Property

Controls whether the Content-Length is inserted in the header.

Syntax

Object.PutLength

Part | Description
Object | Evaluates to a WebServer Control.

Data Type

Boolean

Remarks

Defaults to True. When set to True, places the content-length in the header. This is a non-standard header, but Internet Explorer needs this value to know when it’s done loading a page.


RootDirectory Property

Root directory for web pages.

Syntax

Object. RootDirectory

Part | Description
Object | Evaluates to a WebServer Control.

Data Type

String

Remarks

The default value is an empty string.

Specifies the starting directory of your Web Page hierarchy. All requests will be relative to this directory. For example, if a client requests the page "/test/somepage.html" and RootDirectory is "C:\WebPub" then the absolute path of the request is "C:\WebPub\test\somepage.html". The client cannot access files and directories above this root directory.

For security reasons, you must set this property to a valid directory name before calling Start; otherwise, a ptFile error occurs.


SecureCount Property

Number of secure connections currently open.

Syntax

Object.SecureCount

Part | Description
Object | Evaluates to a WebServer Control.

Data Type

Long

Remarks

Read-only.

This number may be greater than the number of Session Objects, since a single HTTP Client may have more than one connection to the server at the same time.


Sessions Property

Collection of active Session Objects.

Syntax

Object.Sessions

Part | Description
Object | Evaluates to a WebServer Control.

Data Type

Sessions Object

Remarks

Read-only.

Use the MaxIdleTime property to control how long sessions remain active.


Pause Method

Stop the server from accepting new connections, while allowing established connections and sessions to persist.

Syntax

Object.Pause

Part | Description
Object | Evaluates to a WebServer Control.

Remarks

This method stops the web server from listening and accepting new connections. Existing connections can continue making requests. IdleTime will continue to increase.

Use Stop to stop the server from listening and close all open connections.


Start Method

Start processing HTTP/HTTPS requests.

Syntax

Object.Start [ LocalPort ] [ , LocalSecurePort ] [ , LocalAddress ] [ , LocalSecureAddress ] [ , Backlog ] [ , SecureBacklog ]

Part | Description
Object | Evaluates to a WebServer Control.
LocalPort | Optional Long between -1 and 65535, inclusive. Specifies the non-secure port for accepting connections. Defaults to the well-known HTTP Port 80.
LocalSecurePort | Optional Long between -1 and 65535, inclusive. Specifies the secure port for accepting connections. Defaults to the well-known HTTPS Port 443.
LocalAddress | Optional String. Interface address to use in dot notation for non-secure communications. Not usually specified.
LocalSecureAddress | Optional String. Interface address to use in dot notation for secure communications. Not usually specified.
Backlog | Optional Long. Maximum length to which the queue of pending non-secure connections may grow. Defaults to the maximum number allowed.
SecureBacklog | Optional Long. Maximum length to which the queue of pending secure connections may grow. Defaults to the maximum number allowed.

Remarks

This method directs the server to start accepting and processing HTTP Requests.

LocalPort specifies the port on which the server should accept non-secure (HTTP) requests, and defaults to 80 if unspecified. Use –1 to disable non-secure service.

LocalSecurePort specifies the port on which the server should accept secure (HTTPS) requests, and defaults to 433 if unspecified. Use –1 to disable secure service. If enabled, you must initialize the Certificate property before this method is called, or a ptNoCertificate error is generated.

Error Codes

The Start method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAddressInUse

  • ptFile (RootDirectory property was not set or does not exist)

  • ptInvalidParam1 (LocalPort is not a valid port number)

  • ptInvalidParam2 (LocalSecurePort is not a valid port number)

  • ptNetworkDown

  • ptNoBufferSpace

  • ptNoCertificate (HTTPS requested, but the Certificate property is not initialized)


Stop Method

Stop the server from accepting new connections and immediately close existing client connections.

Syntax

Object.Stop

Part | Description
Object | Evaluates to a WebServer Control.

Remarks

This method stops the server from listening and accepting connections on both the non-secure and secure ports. In addition, all existing client connections are immediately terminated, and the LocalPort and LocalSecurePort properties are set to 0.

Calling this method does not remove sessions from the Sessions Object. The IdleTime property of existing sessions is not updated while the WebServer Control is stopped. Use the Remove method or the Clear method to remove all or individual sessions.

Error Codes

The Stop method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAbort

  • ptBlocked

  • ptNetworkDown

  • ptNotConnected

  • ptTimeout


Error Event

Fires whenever an error condition occurs.

Syntax

Private Sub Object_Error ( [ Index As Integer , ] Session As Session, Number As ErrorConstants, Description As String )

Part | Description
Object | Evaluates to a WebServer Control.
Index | Integer. Array index if the object is part of an array.
Session | Session Object associated with the event.
Number | ErrorConstants value.
Description | String. ErrorConstants description.

Remarks

See the appropriate method and property description for a list of errors that may be generated by each.

Some browsers, notably IE 5.0, abort the TCP connection if the response header indicates the content is the same as that in the local cache. The Error event reports a ptConnectionAborted error. This is normal behavior. It is also normal to see a ptConnectionAborted or ptConnectionReset error if Version = "1.1" and the client browser is shut down.

It is possible for an error to occur that is not associated with a session. In this case, Session will not reference an existing object.


Get Event

Fires when a GET request is received. By default, file information and content is sent back to the client. Place code within this event to modify the default response.

Syntax

Private Sub Object_Get ( Session As Session, Request As Request, Response As Response )

Part | Description
Object | Evaluates to a WebServer Control.
Session | Session Object associated with the client.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

A GET request indicates that a file should be returned. Header fields and the requested file are sent in the response to this request.

Request.FileName is the relative path and name of the file specified in the request. If found on the local system, Response.Body.FileName is usually set to the path and name and Status is set to httpOK (exception: if the request includes an httpIfModifiedSince header field and the file has not been modified, then Response.Body.FileName is left empty and Status is set to httpNotModified). If the file is not found then Status is set to httpNotFound.

Variable data received as part of the URL is parsed and stored in Request.Variables.

Response.Body, Response.Status, Response.StatusText, and Response.Cookies may be modified before returning from this event, and the modified information is returned to the client. To temporarily "redirect" the browser to another location, set Response.Status to httpFound and add an httpLocation header field to Response.Header to identify the new URL to be used. See RFC 2616 for more information about constructing responses.

You can add header fields to Response.Header. Refer to the Default Response Header topic for information on the default header fields.

The Session Object contains session data associated with the client making the request.

Note Some browsers, notably IE 5.0, abort the TCP connection if the response header indicates the content is the same as that in the local cache. A ptConnectionAborted error will be reported to the Error event. This is normal behavior.


Head Event

Fires when a HEAD request is received. By default, header information is sent back to the client. Place code within this event to modify the default response.

Syntax

Private Sub Object_Head ( Session As Session, Request As Request, Response As Response )

Part | Description
Object | Evaluates to a WebServer Control.
Session | Session Object associated with the client.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

A HEAD request indicates that information about a file should be returned. Only headers are returned to the client in the response to this request.

Request.FileName is the relative path and name of the file specified in the request. If found on the local system, Response.Body.FileName is set to the absolute path and name and Status is set to httpOK. If the file is not found then Status is set to httpNotFound. Response.Body is used to construct the "Content-Length" and "Last-Modified" header fields, but the body is not sent as part of the response.

Variable data received as part of the URL is parsed and stored in Request.Variables.

You can add header fields to Response.Header. Refer to the Default Response Header topic for information on what the response header will default to. See RFC 2616 for more information about constructing responses.

The Session Object contains session data associated with the client making the request.


Post Event

Fires when a POST request is received. By default, a status of "Forbidden" is returned. Place code within this event to modify the default response.

Syntax

Private Sub Object_Post ( Session As Session, Request As Request, Response As Response )

Part | Description
Object | Evaluates to a WebServer Control.
Session | Session Object associated with the client.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

A POST request indicates that posted data should be processed by the server and optionally, HTML content may be returned. The server determines the actual function performed by the POST method. Some uses may be:

  • Annotation of existing resources

  • Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles

  • Providing a block of data, such as the result of submitting a form, to a data-handling process

  • Extending a database through an append operation

Request.FileName is the relative path and name of the file specified in the URL that is meant to process the posted information. Request.Body contains the data being posted.

Variable data received as part of the request, both in the URL and in Request.Body, is parsed and stored in Request.Variables (when you design your form, make sure the same name is not used for both a URL parameter and a field name on the form). In addition, if Request.Header(httpContentType) = "multipart/form-data", then any file that is part of the post is added to Request.Files.

Response.Status defaults to httpForbidden and Response.Body defaults to an HTML page containing "Forbidden." If you process this request, then Response.Status should normally be set to:

  • httpOK, if no Universal Resource Identifier (URI) is created and Response.Body describes the result.

  • httpCreated, if a URI is created and Response.Header(httpLocation) refers to the result page.

  • httpNoContent, if no URI is created and Response.Body does not describe the result.

The response page may be identified by Request.FileName.

Response.Header and Response.Cookies may also be changed before returning from this event, and the new information is returned to the client. Refer to the Default Response Header topic for information on the default header fields. See RFC 2616 for more information about constructing responses.

The Session Object contains session data associated with the client making the request.


Put Event

Fires when a PUT request is received. By default, a status of "Forbidden" is returned. Place code within this event to modify the default response.

Syntax

Private Sub Object_Put ( Session As Session, Request As Request, Response As Response )

Part | Description
Object | Evaluates to a WebServer Control.
Session | Session Object associated with the client.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

A PUT request indicates the file should be saved or processed. This is particularly useful as an FTP alternative because the file can be transferred over a secure connection.

Request.FileName is the destination relative path and name for the file being sent. Request.Body contains the file sent by the client, and Request.Body.FileName defaults to the destination absolute path and name.

Variable data sent as part of the URL is parsed and stored in Request.Variables property.

Response.Status defaults to httpForbidden and Response.Body defaults to an HTML page containing "Forbidden." If you process this request, then Response.Body should be cleared and Response.Status should normally be set to:

  • httpOK, if the existing file is there and the server replaces the contents of the file with the contents of the request (excluding the header). Response.Body describes the result that may be shown by the browser.

  • httpCreated, if no existing file is present and a new one is created. The contents of the request becomes the contents of the file (excluding the header). Response.Body describes the result that may be shown by the browser.

  • httpNoContent, if the request was processed but Response.Body does not describe the result.

Response.Header and Response.Cookies may be changed before returning from this event, and the new information is returned to the client. Refer to the Default Response Header topic for information on the default header fields. See RFC 2616 for more information about constructing responses.

The Session Object contains session data for the session that is associated with the client making the request.


Request Event

Fires when an unknown request is received.

Syntax

Private Sub Object_Request ( Method As String, Session As Session, Request As Request, Response As Response )

Part | Description
Object | Evaluates to a WebServer Control.
Method | String. Contains the requested method.
Session | Session Object associated with the client.
Request | Request Object. Contains information about the request.
Response | Response Object. Contains the response to send to the client.

Remarks

This event fires when the request type is not HEAD, GET, POST, or PUT. The following are examples of other types of requests:

  • DELETE

  • TRACE

  • OPTIONS

  • CONNECT

See RFC 2616 for further information on what is the expected operation for these types of methods. This event also allows for proprietary methods to be added to your sever implementation.

Request.FileName is the relative path and name of the file specified in the request.

Variable data received as part of the URL is parsed and stored in Request.Variables.

Response.Status defaults to httpNotImplemented, but may be changed to another value. Response.Body, Response.Header, Response.Status, Response.StatusText and Response.Cookies may be changed before returning from this event, and the new information is returned to the client. Refer to the Default Response Header topic for information on the default header fields. See RFC 2616 for more information about constructing responses.

The Session Object contains session data for the session that is associated with the client making the request.


SessionEnd Event

Fires before a session is destroyed.

Syntax

Private Sub Object_SessionEnd ( Session As Session )

Part | Description
Object | Evaluates to a WebServer Control.
Session | Session Object about to be destroyed.

Remarks

This event fires when Session.IdleTime exceeds the MaxIdleTime property of the WebServer Control. The object remains in the Sessions Collection until returning from this event; this allows you to reset Session.IdleTime to a new value, such as 0, to prevent destruction of the object.


SessionInit Event

Fires after a new session is created.

Syntax

Private Sub Object_SessionInit ( Session As Session )

Part | Description
Object | Evaluates to a WebServer Control.
Session | Session Object associated with the client.

Remarks

A new Session is created when either a cookie identifying the session is not sent with a request or the session id sent in the request can not be found in the Sessions Collection.

If the client has disabled cookie support, then all requests made generate a new session; therefore, this event fires before each protocol-specific request event.

Use this event to initialize session data.


PowerTCP Winsock Tool

PowerTCP Winsock Tool (version 2)

Support Licensing Distribution

The Winsock Tool is a complete set of basic building blocks with controls for TCP, UDP, Daemon, DNS, Ping, and RAS. Superior buffer management, the use of variants supporting String and Byte–array data, and optional blocking use highlight the ease of use of the this tool.

Users may have different needs when implementing even a basic protocol: blocking vs. non–blocking programming operation, debugging features, use from VB Script and VBA environments, buffering needs, etc. Use the Winsock Tool to simplify tasks in any application.

Controls

Control | Description
Daemon Control | Accept connections
DNS Control | Look up names, addresses, mail servers
Ping Control | Verify a host is reachable
RAS Control | Control system dial-up services
TCP Control | Manage streams of data
UDP Control | Send and receive user datagrams and raw datagrams

Supporting Objects

Object | Description
DartStream Object | Manages file access and buffers.
DartStrings Object | Manages collections of strings. This object is used in many PowerTCP controls and formatting objects.
PhoneBookEntry Object | Holds one phone book entry from a RAS phonebook.
PhoneBookEntries Object | Manages a collection of PhoneBookEntry Objects.
System Object | Exposes such Winsock information as local host name and address. Most of the sample applications use this object in the About box to display system information.

Sample Projects

The following sample projects demonstrate how to use the Winsock Tool:

Project | Description
DartChat | Demonstrates how the Multicast capability of the UDP Control can be used to make a simple chat program. Visual Basic and Visual C++.
DNS Client | Demonstrates forward name lookup (name to address), reverse name lookup (address to name), and mail server lookup (email address to mail server address). Visual Basic 5/6, Visual C++, PowerBuilder, and Delphi.
Ping Client | Demonstrates how the Ping Control is used to reach any host on the Internet. Visual Basic 5/6, Visual C++, PowerBuilder, and Delphi.
Ras Client | Demonstrates a simple application that connects to a RAS server. Visual Basic 5/6, Visual C++, PowerBuilder, Delphi, and C++ Builder.
TCP Blaster | A simple Client/Server application, written using blocking operation, that uses all three methods for receiving data: Receive, Search, and Fill. Visual Basic 5/6, Visual C++, PowerBuilder, Delphi, and C++ Builder.
TCP Client | Demonstrates a simple TCP Client application written using non-blocking operation. Visual Basic 5/6, Visual C++, PowerBuilder, Delphi, and C++ Builder.
UDP Client | Demonstrates a simple UDP Client application written using non-blocking operation. Visual Basic 5/6, Visual C++, PowerBuilder, Delphi, and C++ Builder.
Web Alive | Compares the download performance of any 2 web pages. Useful for comparing the relative performance of mirrored Web Servers. Visual Basic 5/6.
Web Server | Demonstrates a simple multi-threaded Web Server application that serves up HTML pages stored in local files. Visual Basic 5/6, Visual C++.

Online ASP Samples

These ASP samples demonstrate the use of the Web Tool on the Internet. You must have an active Internet connection to view these Samples.

Sample

Description

DNS on the Web

The DNS Control resolves the Email address, host name, or dot address you enter.

Ping on the Web

The Ping Control contacts any host on the Internet.

Stock Quotes on the Web

The TCP Control accesses Yahoo's stock quote service. What is the current value of your portfolio.

Email Address Verification on the Web

TCP and DNS Controls verify the validity of any email address.


DNS Control

Properties Methods Events Example

Use the DNS Control to access Domain Name Servers. The GetAddress method resolves a host name to a dot address. The GetName method resolves a dot address to a host name (reverse lookup). The GetMailServer method resolves an email address to a mail server dot address.

Miscellaneous

Product | PowerTCP Winsock Tool
Prog ID | Dart.Dns.1
File | DartUtil.dll
Dependencies | DartSock.dll
Threading | Apartment Model
Licensed | Yes


DNS Control Usage

The DNS control can operate:

  • Transparently in the background while the user of your application is doing other tasks

  • Interactively with the user

Simple methods are provided to perform the following tasks:

  • Forward Lookup. GetAddress resolves a name to an address.

  • Reverse Lookup. GetName resolves an address to a name.

  • MX Lookup. GetMailServer resolves an email address to the mail server address responsible for that mail domain.

Transparent Use

For transparent use, the control should operate in the background with minimal system impact. Non-blocking operation provides transparency using communication events that will not affect the user interface.

This VB example shows how a mail server address is retrieved when a user clicks a button.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' use non-blocking behavior

Dns1.Timeout = 0

Dns1.ServerName = "Dns1.nameserver.com"

Dns1.GetMailServer "test@dart.com"

' pick up this operation in the Response Event

OnError:

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Private Sub Dns1_Response()

' we can now do something with the response

' for this example just store the returned

' servers into a list box

Dim i As Integer

For i = 1 To Dns1.Names.Count

List1.AddItem Dns1.Names(i)

Next i

End Sub

Interactive Use

For interactive applications, transparency is not as important and blocking operation may be acceptable, as shown in the following VB example.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim i As Integer

' Use the Timeout property to establish blocking behavior

Dns1.Timeout = 1000

' Specify the address of the server to connect to

Dns1.ServerName "Dns1.nameserver.com"

' get the mail server for the address

Dns1.GetMailServer "test@dart.com"

' all done, fill our list now

For i = 1 To Dns1.Names.Count

List1.AddItem Dns1.Names(i)

Next i

OnError:

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Addresses Property

Collection of addresses in dot notation (nnn.nnn.nnn.nnn) returned by the Domain Name Server.

Syntax

Object.Addresses

Part | Description
Object | Evaluates to a DNS Control.

Data Type

DartStrings Object

Remarks

Read-only. This property contains the resolved address for the name used in the GetAddress method. This collection contains multiple entries if the result from the GetMailServer method includes multiple mail servers.


Id Property

Sets the Dns request ID included with the request.

Syntax

Object.Id

Part | Description
Object | Evaluates to a DNS Control.

Data Type

Long

Remarks

This property is used to set an identifier for the Dns request packet. It is updated from the response packet when it is received.


Names Property

Collection of names returned by the Domain Name Server.

Syntax

Object.Names

Part | Description
Object | Evaluates to a DNS Control.

Data Type

DartStrings Object

Remarks

Read-only.

This property contains the resolved name for the address used in the GetName method; it may contain more than one entry if the result from the GetMailServer method includes multiple mail servers.


ServerName Property

Domain Name Server to use for queries.

Syntax

Object.ServerName

Part | Description
Object | Evaluates to a DNS Control.

Data Type

String


ServerPort Property

Domain Name Server port for queries.

Syntax

Object.ServerPort

Part | Description
Object | Evaluates to a DNS Control.

Data Type

Long

Remarks

The default value is 53, and should not be changed in most cases.


GetAddress Method

Resolve a host name to a dot address.

Syntax

Object.GetAddress Name

Part | Description
Object | Evaluates to a DNS Control.
Name | String. Name to resolve, such as ftp.dart.com.

Remarks

This method performs a forward lookup of a host name to get an address. If the Domain Name Server is able to resolve Name to an address, the Addresses property has a count of one.

Error Codes

The GetAddress method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAddressNotAvailable

  • ptBlocked

  • ptFormatError

  • ptMessageSize

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotFound

  • ptNotImplemented

  • ptNotInitialized

  • ptOperationRefused

  • ptProtocol

  • ptServerError

  • ptTimeout


GetMailServer Method

Example

Get the mail server (or servers) responsible for receiving mail for a given email address.

Syntax

Object.GetMailServer EmailAddress

Part | Description
Object | Evaluates to a DNS Control.
EmailAddress | String. Email address or domain name.

Remarks

This method returns the mail server for the provided domain or email address. The result of the query may include multiple mail servers. If more than one is found, the most preferred server is first in the list and the least preferred is at the end of the list.

This method populates the Names and Addresses properties. There is a one-to-one correlation between Names and Addresses (for example, Dns1.Addresses(3) is the address for Dns1.Names(3)).

The GetMailServer method may return an empty collection. This could mean one of the following:

  • The host does not have any mail exchanger (MX) or address (A) records in the DNS.

  • The host has valid MX records, but none of the mail exchangers listed have valid A records.

  • There was a transient error with the DNS that caused one of the above to appear to be true.

Error Codes

The GetMailServer method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAddressNotAvailable

  • ptBlocked

  • ptFormatError

  • ptMessageSize

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotFound

  • ptNotImplemented

  • ptNotInitialized

  • ptOperationRefused

  • ptProtocol

  • ptServerError

  • ptTimeout


GetName Method

Resolve a dot address to a host name.

Syntax

Object.GetName Address

Part | Description
Object | Evaluates to a DNS Control.
Address | String. Address to resolve in dot notation (nnn.nnn.nnn.nnn).

Remarks

This method performs a reverse lookup of an address to get the name. If the Domain Name Server is able to resolve Address to a name, the Names property will have a count of one.

Error Codes

The GetName method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAddressNotAvailable

  • ptBlocked

  • ptFormatError

  • ptMessageSize

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotFound

  • ptNotImplemented

  • ptNotInitialized

  • ptOperationRefused

  • ptProtocol

  • ptServerError

  • ptTimeout


Response Event

Fires after the Id, Addresses,and Names properties are updated with the contents of a DNS response.

Syntax

Private Sub Object_Response ( [ Index As Integer ] )

Part | Description
Object | Evaluates to a DNS Control.
Index | Integer. Array index if the object is part of an array.

Remarks

When Timeout is 0 (non-blocking) this event is used to process DNS query results. The Id property can be used to associate the response with a specific request.


PhoneBookEntries Object

Manages a collection of PhoneBookEntry Objects. All phonebook entries for a RAS phonebook are held in one collection. Automatic iteration is supported.


FileName Property

The filename of the phonebook in use. Set this property to clear all entries and load the specified phonebook. The default value is "".

Syntax

Object.FileName

Part | Description
Object | Evaluates to a PhoneBookEntries Object.

Data Type

String

Remarks

Windows NT stores RAS phonebooks in files with .pbk extension. When set to "", the default system phonebook file loads. Under Windows NT, the default system phonebook file is the one selected by the user in the User Preferences property sheet of the Dial-Up Networking dialog box. Under Windows 95 and Windows 98, the RAS phonebook is stored in the system registry and this property is ignored.


Selected Property

Name of the highlighted phonebook entry in the combo box.

Syntax

Object.Selected

Part | Description
Object | Evaluates to a PhoneBookEntries Object.

Data Type

String

Remarks

The Visible property and the Enabled property must to be set to True for this property to return a value. When the user selects an entry name in the combo box, this property indicates that selection.

Error Codes

The Selected property may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

rasBadEntryName (invalid entry name was set)


Add Method

Invoke system dialog boxes to create a new RAS phonebook entry.

Syntax

Object.Add

Part | Description
Object | Object expression that evaluates to a PhoneBookEntries Object.

Remarks

The new phonebook entry is placed into the system phonebook. After creating a new phonebook entry, the object is refreshed.

Error Codes

The Add method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

rasCorruptPhoneBook


PhoneBookEntry Object

Properties Methods

Holds one phonebook entry from a RAS phonebook.


CallbackNumber Property

Callback number the remote communications server uses to call back.

Syntax

Object.CallbackNumber

Part | Description
Object | Evaluates to a PhoneBookEntry Object.

Data Type

String

Remarks

Read-only.


Domain Property

Domain name to use to authenticate the user.

Syntax

Object.Domain

Part | Description
Object | Evaluates to a PhoneBookEntry Object.

Data Type

String

Remarks

Read-only.


Name Property

Phonebook entry name.

Syntax

Object.Name

Part | Description
Object | Evaluates to a PhoneBookEntry Object.

Data Type

String

Remarks

Read-only.


Password Property

Password to use when initiating a connection.

Syntax

Object.Password

Part | Description
Object | Evaluates to a PhoneBookEntry Object.

Data Type

String

Remarks

Read-only.


PhoneNumber Property

The PhoneBook Entry phone number to dial.

Syntax

Object.PhoneNumber

Part | Description
Object | Evaluates to a PhoneBookEntry Object.

Data Type

String


User Property

Login name to use when initiating a connection.

Syntax

Object.User

Part | Description
Object | Evaluates to a PhoneBookEntry Object.

Data Type

String

Remarks

Read-only.


Edit Method

Invoke system dialog boxes to edit a phonebook entry.

Syntax

Object.Edit

Part | Description
Object | Object expression that evaluates to a PhoneBookEntry Object.

Remarks

The PhoneBookEntries Object is refreshed after the entry is edited.

Error Codes

The Edit method may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

rasCorruptPhoneBook


Ping Control

Properties Methods Events Example

Use the Ping Control to determine if a host is reachable.

Miscellaneous

Product | PowerTCP Winsock Tool
Prog ID | Dart.Ping.1
File | DartUtil.dll
Dependencies | DartSock.dll
Threading | Apartment Model
Licensed | Yes


Ping Control Usage

The Ping control can operate:

  • Transparently in the background while the user of your application is doing other tasks.

  • Interactively with the user.

Transparent Use

For transparent use, the control should operate in the background with minimal system impact. Non-blocking operation provides transparency using communication events that will not affect the user interface.

This VB example shows how a to determine if a server is able to send and receive data.

Complete the following steps:

  1. Add a Ping Control, two labels, and a command button to the form.

  2. Paste the code below into the Code window.

  3. Click the command button.

Private Sub Command1_Click()

' use non-blocking behavior

Ping1.Timeout = 0

Ping1.Ping "www.dart.com"

' We will pick this operation up in the

' Response event

End Sub

Private Sub Ping1_Response()

' We can now do something with the response

' For this example just report that we got a

' response and how long it took

' Label1 is the delay and Label2 is the status

Label1.Caption = Ping1.Delay

Label2.Caption = "OK"

End Sub

Interactive Use

For interactive applications, transparency is not as important and blocking operation may be acceptable.

This VB example shows how a to determine if a server is able to send and receive data.

Complete the following steps:

  1. Add a Ping Control, two labels, and a command button to the form.

  2. Paste the code below into the Code window.

  3. Click the command button.

Private Sub Command1_Click()

' Use the Timeout property to establish blocking behavior

Ping1.Timeout = 3000

' Specify the address of the server to connect to

Ping1.Ping "www.dart.com"

' We can now report the result to the user

Label1.Caption = Ping1.Delay

Label2.Caption = "OK"

End Sub


Data Property

Optional data that is sent and returned with each ping request.

Syntax

Object.Data

Part | Description
Object | Evaluates to a Ping Control.

Data Type

Byte array

Remarks

Maximum size of array is 4096 bytes.

Data is appended to the end of a ping request and returned back with any response. Use this property to store any per request specific information.


Delay Property

Time between sending the ping request and receiving the response (round-trip time in milliseconds).

Syntax

Object.Delay

Part | Description
Object | Evaluates to a Ping Control.

Data Type

Long

Remarks

Read-only.

This property is updated each time a server response is received.

Note The first request to a RemoteName may take longer than subsequent requests to the same RemoteName if a dot address is not used, because of the time used for host name resolution.


Id Property

Sets the ping request ID included with the request.

Syntax

Object.Id

Part | Description
Object | Evaluates to a Ping Control.

Data Type

Long

Remarks

This property is used to set an identifier for the ping request packet. This property is useful in non-blocking mode when you send a ping request on a specified interval to determine if any request went unanswered. It is updated from the response packet when it is received.


Ping Method

Determine if a host is reachable.

Syntax

Object.Ping RemoteName

Part | Description
Object | Evaluates to a Ping Control.
RemoteName | String. Name of the server to query. May either be an address in dot notation (nnn.nnn.nnn.nnn) or a name, such as host.dart.com.

Remarks

The Id and Data properties are used to construct the request, and are updated when a response is received.

Error Codes

The Ping method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAddressNotAvailable

  • ptBlocked

  • ptMessageSize

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotInitialized

  • ptProtocol

  • ptTimeout


Response Event

Fires after the Id, Delay, and Data properties are updated with the contents of a ping response.

Syntax

Private Sub Object_Response ( [ Index As Integer ] )

Part | Description
Object | Evaluates to a Ping Control.
Index | Integer. Array index if the object is part of an array.

Remarks

When Timeout is 0 (non-blocking) this event is used to process ping request results. The Id property can be used to associate the response with a specific request.


RAS Control

Properties Methods Events Constants

Use the RAS Control to establish a Remote Access Server (RAS) connection to a remote communications server. If the user of your application is not directly connected to the Internet, you can use the RAS Control to provide the same automatic dial-up features that are available in Internet Explorer and Outlook Express. This control provides an object model for phonebook access, methods for establishing and closing dialup connections, and functionality for RAS phonebook management. A combo box is provided as a visual interface to the RAS phonebook for configuration purposes.

Note RAS Service must be installed.

Miscellaneous

Product | PowerTCP Winsock Tool
Prog ID | Dart.Ras.1
File | DartRas.dll
Dependencies | RAS Service Installed, DartSock.dll
Threading | Apartment Model
Licensed | Yes


RAS Control Usage

When initialized, the default system RAS phonebook is loaded into the control’s PhoneBook property. This property is a PhoneBookEntries collection of PhoneBookEntry Objects.

Use the RAS Control on an option or setup form to give your users the ability to choose a RAS phonebook entry. Phonebook entry names from all phonebook entries in the PhoneBook property are shown in the control’s combo box. The highlighted entry is read from the Selected property of the PhoneBook property. When saving application settings, simply store the entry name from this property to establish a connection later.

Establish a RAS connection with a phonebook entry with the ConnectEntry method. Connect without using the phonebook with the Connect method. Obtain status on establishing the connection by checking the State property.

Gracefully close a connection with the Close method. Abort a connection or a blocked method call with the Abort method. The connection is automatically closed when the control is unloaded (unless you set the Handle property to 0, in which case the connection will persist after the control is destroyed).

Provide your users the ability to create new phonebook entries with the Add method. Edit existing entries with the Edit method. Both methods use operating system dialog boxes. The PhoneBook property is refreshed after these methods are used.


BackColor Property

Returns or sets the background color of the control.

Syntax

Object.BackColor

Part | Description
Object | Evaluates to a RAS Control.

Data Type

Long value or constant that specifies an RGB color.

Remarks

The default value is the system color for window background.

Reference the standard Windows controls documentation for information on color usage.


Enabled Property

Determines if the control can respond to mouse and keyboard input. The default value is True.

Syntax

Object.Enabled

Part | Description
Object | Evaluates to a RAS Control.

Data Type

Boolean

Remarks

When set to True, the combobox can capture the focus. When set to False, the combobox is dimmed and cannot capture the focus.


Font Property

Font used by the control. The default font is the ambient font set in the container.

Syntax

Object.Font

Part | Description
Object | Evaluates to a RAS Control.

Data Type

Font


ForeColor Property

Foreground color for the control (text color within the combo box).

Syntax

Object.ForeColor

Part | Description
Object | Evaluates to a RAS Control.

Data Type

Long value or constant that specifies an RGB color

Remarks

The default value is the system color for window text.

Reference the standard Windows controls documentation for information on color usage.


Handle Property

Handle for the RAS connection.

Syntax

Object.Handle

Part | Description
Object | Evaluates to a RAS Control.

Data Type

Long

Remarks

When the State property is rasConnected, this property returns a positive number that is a handle to the connection. If not connected, this property returns 0.

Set this value to 0 if you need to destroy the RAS Control and leave the connection active. If the control is destroyed while this property is positive, the connection is closed as the control is unloaded.

Error Codes

The Handle property may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

rasInvalidProperty (attempt was made to set an inactive or nonexistent value)


PhoneBook Property

Holds a complete RAS phonebook as a PhoneBookEntries Object.

Syntax

Object.PhoneBook

Part | Description
Object | Evaluates to a RAS Control.

Data Type

PhoneBookEntries Object

Remarks

Read-only.


State Property

Provides status information to the user interface. The State event fires to signal that this property has changed.

Syntax

Object.State

Part | Description
Object | Evaluates to a RAS Control.

Data Type

StateConstants

Remarks

Read-only.


Visible Property

Determines whether the control is visible.

Syntax

Object.Visible

Part | Description
Object | Evaluates to a RAS Control.

Data Type

Boolean

Remarks

The default value is True.


Close Method

Terminate the RAS connection and release all system resources.

Syntax

Object.Close

Part | Description
Object | Object expression that evaluates to a RAS Control.

Remarks

This method immediately sets the State to rasClosing. When resources are finally released, the State is rasClosed.

If Timeout is greater than 0, this method attempts to gracefully close the connection within the timeout period. If the operation completes within the timeout period, this method returns successfully. If the operation does not complete within the timeout period, then a ptTimeout error is generated.

If Blocked and you wish to cancel the blocking method and release resources, use the Abort method. Using the Close method when another method is blocking results in a ptBlocked error.

Error Codes

The Close method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • rasAbort (the blocking method was aborted).

  • rasBlocked (already executing a blocked method call)

  • rasTimeout (the method timed out)

Additionally, any ErrorConstants error code can be generated when Timeout is greater than 0.


Connect Method

Establish a remote access connection to a remote communications server without using a RAS phonebook entry. The RAS system uses the first available connection device. Use the ConnectEntry method to establish a connection using a RAS phonebook entry.

Syntax

Object.Connect PhoneNumber, User, Password [ , Domain ] [ , CallbackNumber ]

Part | Description
Object | Object expression that evaluates to a RAS Control.
PhoneNumber | String. Phone number to dial to the remote communications server.
User | String. Login name of the user on the server.
Password | String. Password of the user on the server.
Domain | Optional String. Domain on the server for user authentication.
CallbackNumber | Optional String. Phone number the server should use to call back to.

Remarks

If Domain is not specified, the remote communications server’s domain is used to perform User authentication.

If CallbackNumber is specified, callback is performed only if the local RAS system has callbacks enabled and the remote communications server has Set By Caller callback permission enabled for the User.

This method blocks if Timeout is greater than 0. The Blocked property can be checked to verify the control is not busy executing another method.

When called, State immediately changes to rasConnecting and eventually changes to rasConnected when the connection is formed. The State property can be checked in the body of the State event or polled off a timer. If a positive Timeout is used then the absence of an error indicates the connection was successful.

Error Codes

Any ErrorConstants error code may be generated. The Error event fires before returning the error to the container's Error object.


ConnectEntry Method

Establish a RAS connection to a remote communications server by naming a phonebook entry. Specify the Name of the loaded PhoneBookEntry Object you want to dial. All required parameters are fetched from the phonebook entry. Use the Connect method to establish a connection without the phonebook.

Syntax

Object.ConnectEntry Name [ , User ] [ , Password ] [ , Domain ]

Part | Description
Object | Object expression that evaluates to a RAS Control.
Name | String. Phonebook entry name.
User | Optional String. Login name of the user on the remote communications server.
Password | Optional String. Password of the user on the server.
Domain | Optional String. Domain on the server for user authentication.

Remarks

Specify User, Password, and Domain to override the phonebook entry. This is useful when the user has just created a phonebook entry and default values do not exist yet. Upon success, these parameters are saved in the phonebook entry.

This method blocks if Timeout is greater than 0. The Blocked property may be checked to verify the control is not busy executing another method.

When called, State immediately changes to rasConnecting and eventually changes to rasConnected when the connection is established. The State property can be checked in the body of the State event or polled off a timer. If a positive Timeout is used, then the absence of an error indicates the connection was successful.

Error Codes

Any ErrorConstants error code may be generated. The Error event fires before returning the error to the container's Error object.


Error Event

Fires when the RAS Control encounters an error.

Syntax

Private Sub Object_Error ( [ Index As Integer , ] Number As ErrorConstants, Description As String )

Part | Description
Object | Evaluates to a RAS Control.
Index | Integer. Array index if the object is part of an array.
Number | ErrorConstants value.
Description | String. ErrorConstants description.

Remarks

Any method can generate an error, and some errors are asynchronously generated. For this reason, robust applications must use this event to respond to run-time errors.

Some environments, such as IIS Active Server Pages, do not support event handling. In this case a positive Timeout forces all errors to be passed back to the container using an Error object that is initialized by each PowerTCP method used.


State Event

Fires when the State property has changed.

Syntax

Private Sub Object_State ( [ Index As Integer ] )

Part | Description
Object | Evaluates to a RAS Control.
Index | Integer. Array index if the object is part of an array.

Remarks

The Connect method or the ConnectEntry method will normally cause the State property to transition from rasClosed to rasConnecting, then to multiple intermediate states, and finally (if no errors occur) to rasConnected at which time communications activity commences. The Close method causes the State property to transition from rasConnected to rasClosing to rasClosed. As each transition occurs, this event fires to notify the application that a change in state has completed.

WARNING Calling the Close method with a positive Timeout from within the State event is not allowed and will cause unpredictable results.


ErrorConstants

Errors are reported to the application with the error object and by firing the Error event. The following values enumerate the Error numbers that can be reported to the client when a RAS Control method is invoked:

Value | Constant | Description
10060 | rasTimeout | Timed out. A connection attempt failed because the connected party did not properly respond after a period of time, or an established connection failed because connected host has failed to respond. Alternatively, a blocked method failed to return within the period specified by the Timeout property.
11103 | rasAbort | The Abort method was called.
12001 | rasInvalidParam1 | Parameter #1 is invalid.
12002 | rasInvalidParam2 | Parameter #2 is invalid.
12003 | rasInvalidParam3 | Parameter #3 is invalid.
12009 | rasInvalidProperty | Invalid property assignment.
12011 | rasBlocked | User thread is blocking in another method.
20200 | rasBadEntryName | The Selected property was set to an invalid phonebook entry name.
20201 | rasCantLoadRasLib | Cannot load the RAS library RASAPI32.DLL.
20602 | rasPortAlreadyOpen | Port already in use. You already performed a successful Connect method, or ConnectEntry method, and have not invoked Close method prior to a new Connect method call.
20604 | rasWrongInformation | The wrong information was specified.
20605 | rasCannotSetPort | Cannot set the RAS port at this time.
20606 | rasPortNotConnected | The RAS port is not connected.
20608 | rasInvalidDevice | The RAS device is invalid. The device specified in a phonebook entry is invalid.
20608 | rasInvalidDeviceType | The RAS device type is invalid. The device type specified in a phonebook entry is invalid.
20611 | rasRouteUnavailable | The route is not available. The routed path to the RAS device or the routed path to the external communications server is not available in a phonebook entry.
20612 | rasRouteUnallocated | The route is not allocated. The routed path to a RAS device or the routed path to the external communications server is not properly configured in a phonebook entry.
20613 | rasInvalidCompression | Invalid compression specified. The compression type specified in a phonebook entry is invalid.
20614 | rasOutOfBuffers | Out of buffer space.
20615 | rasCantFindPort | Cannot find the port.
20616 | rasAsyncRequestPend | An asynchronous request is pending. Cannot invoke a new Connect method call until a prior Connect method, or Close method has completed.
20617 | rasAlreadyClosing | The port or device is already closing. Cannot invoke a new Close method call until a prior Close method has completed.
20618 | rasPortIsNotOpen | The RAS port is not open.
20619 | rasPortIsClosed | The RAS port is already closed. Cannot invoke a Close method call on an already closed port.
20620 | rasNoEndPoints | No end points exist.
20621 | rasCannotOpenPhoneBook | Cannot open a specified phonebook file. The FileName property was set to a file that cannot be opened.
20622 | rasCannotLoadPhoneBook | Cannot load a specified phonebook file. The FileName property was set to a file that cannot be read.
20623 | rasCannotFindPhoneBookEntry | Cannot find a specified phonebook entry.
20624 | rasCannotWritePhoneBook | Cannot write a specified phonebook file.
20625 | rasCorruptPhoneBook | The phonebook has invalid information and is corrupt.
20626 | rasInvalidString | An invalid string was loaded.
20627 | rasCannotFindKey | Cannot find an encryption key specified in a phonebook entry.
20628 | rasPortWasClosed | The RAS port was closed.
20629 | rasClosedRemote | The connection was closed by the remote communications server.
20630 | rasHardwareFailure | The connection was closed due to hardware failure.
20631 | rasClosedUser | The connection was closed by the user.
20633 | rasPortNotAvailable | The RAS port is already in use or is not configured for Remote Access dial out.
20634 | rasCannotRegister | Cannot register your computer on the network on the remote communications server.
20635 | rasUnknownError | Unknown error.
20636 | rasWrongDevice | The wrong device is attached to the port.
20638 | rasDeviceTimeout | The RAS device has timed out.
20639 | rasCannotGetLANA | No asynchronous net is available.
20640 | rasNetbiosError | A NetBIOS error has occurred.
20641 | rasServerOutOfResources | The server cannot allocate NetBIOS resources needed to support the client.
20642 | rasNameExists | One of your NetBIOS names is already registered on the network on the remote communications server.
20643 | rasServerGeneralNetFailure | A network adapter at the server failed.
20644 | rasMsgAliasNotAdded | You will not receive network message popups.
20645 | rasAuthInternal | Internal authentication error.
20646 | rasRestrictedLogonHours | The account with specified user login name is not permitted to log in at this time of day.
20647 | rasAccountDisabled | The account on the remote Internet Server with specified user login has been disabled.
20648 | rasPasswordExpired | The account on the remote Internet Server with specified user login has an expired password.
20649 | rasNoDialinPermission | The account on the client machine does not have Remote Access permission.
20650 | rasServerNotResponding | The Remote Access server is not responding.
20651 | rasDeviceError | Your modem (or other connecting device) has reported an error.
20652 | rasUnrecognizedDeviceResponse | Unrecognized response from the RAS device.
20653 | rasMacroNotFound | A macro required by the RAS device was not found in the device .INF file section.
20654 | rasMacroNotDefined | A command or response in the RAS device .INF file section refers to an undefined macro.
20655 | rasMessageMacroNotFound | The <message> macro was not found in the device .INF file section.
20656 | rasDefaultOffMacroNotFound | The <defaultoff> macro in the device .INF file section contains an undefined macro.
20657 | rasDeviceINFNotOpen | The device .INF file could not be opened.
20658 | rasDeviceNameTooLong | The device name in the device .INF or media .INI file is too long.
20659 | rasDeviceNameNotFound | The media .INI file refers to an unknown device name.
20660 | rasNoResponses | The device .INF file contains no responses for the command.
20661 | rasNoCommandFound | The device .INF file contains no responses for the command.
20662 | rasWrongKeySpecified | Attempted to set a macro not listed in device .INF file section.
20663 | rasUnknownDeviceType | The media .INI file refers to an unknown device type.
20664 | rasUnableAllocateMemory | Cannot allocate memory.
20665 | rasPortNotConfigured | The port is not configured for Remote Access.
20666 | rasDeviceNotReady | Your modem (or other connecting device) is not functioning.
20667 | rasErrorReadingINIfile | Cannot read the media .INI file.
20668 | rasNoConnection | The connection dropped.
20669 | rasBadUsageInINIfile | The usage parameter in the media .INI file is invalid.
20670 | rasErrorReadingSectionname | Cannot read the section name from the media .INI file.
20671 | rasErrorReadingDeviceType | Cannot read the device type from the media .INI file.
20672 | rasErrorReadingDeviceName | Cannot read the device type from the media .INI file.
20673 | rasErrorReadingUsage | Cannot read the usage from the media .INI file.
20674 | rasErrorReadingMaxConnectBPS | Cannot read the maximum connection BPS rate from the media .INI file.
20675 | rasErrorReadingMaxCarrierBPS | Cannot read the maximum carrier BPS rate from the media .INI file.
20676 | rasLineBusy | The line is busy.
20677 | rasVoiceAnswer | A person answered instead of a modem.
20678 | rasNoAnswer | There is no answer.
20679 | rasNoCarrier | No carrier is detected.
20680 | rasNoDialtone | There is no dial tone.
20681 | rasErrorInCommand | General error reported by RAS device.
20682 | rasErrorWritingSectionname | Error writing section name.
20683 | rasErrorWritingDeviceType | Error writing device type.
20684 | rasErrorWritingDeviceName | Error writing device name.
20685 | rasErrorWritingMaxConnectBPS | Error writing max connect BPS.
20686 | rasErrorWritingMaxCarrierBPS | Error writing max carrier BPS.
20687 | rasErrorWritingUsage | Error writing usage.
20688 | rasErrorWritingDefaultOff | Error writing default off.
20689 | rasErrorReadingDefaultOff | Error reading default off.
20690 | rasEmptyIniFile | Error due to empty .INI file.
20691 | rasAuthenticationFailure | Access denied because login name and/or password is invalid on the domain on the remote communications server.
20692 | rasErrorPortOrDevice | Hardware failure in port or attached device.
20693 | rasNotBinaryMacro | Error not binary macro.
20694 | rasDCBNotFound | Error DCB not found.
20695 | rasStateMachinesNotStarted | Error state machines not started.
20696 | rasStateMachinesAlreadyStarted | Error state machines already started.
20697 | rasPartialResponseLooping | Error in partial response looping.
20698 | rasUnknownResponseKey | A response keyname in the device .INF file is not in the expected format.
20699 | rasReceiveBufferFull | The RAS device response caused buffer overflow.
20700 | rasCommandTooLong | The expanded command in the device .INF file is too long.
20701 | rasUnsupportedBPS | The device moved to a BPS rate not supported by the COM driver.
20702 | rasUnexpectedResponse | Device response received when none expected.
20703 | rasInteractiveModeError | The Application does not allow user interaction. The connection requires interaction with the user to complete successfully.
20704 | rasBadCallbackNumber | The callback number is bad.
20705 | rasInvalidAuthState | The authentication state is invalid.
20706 | rasErrorWritingInitBPS | Error writing initial BPS.
20707 | rasX25Diagnostic | X.25 diagnostic indication.
20708 | rasAccountExpired | The account has expired.
20709 | rasErrorChangingPassword | Error changing password on domain. The password may be too short or may match a previously used password.
20710 | rasOverrun | Serial overrun errors were detected while communicating with your modem.
20711 | rasRasManCannotInit | RasMan initialization failure. Check the event log.
20712 | rasBiplexPortNotAvailable | Biplex port initializing. Wait a few seconds and redial.
20713 | rasNoActiveISDN | No active ISDN lines are available.
20714 | rasNoISDNChannels | No ISDN channels are available to make the call.
20715 | rasTooManyLineErrors | Too many errors occurred because of poor phone line quality.
20716 | rasBadIPConfiguration | The Remote Access IP configuration is unusable.
20717 | rasNoIPAddresses | No IP addresses are available in the static pool of Remote Access IP addresses.
20718 | rasPPPTimeout | Timed out waiting for a valid response from the remote PPP peer.
20719 | rasPPPRemoteTerminated | PPP terminated by remote machine.
20720 | rasPPPNoProtocolsConfigured | No PPP control protocols configured.
20721 | rasPPPNoResponse | Remote PPP peer is not responding.
20722 | rasPPPInvalidPacket | The PPP packet is invalid.
20723 | rasPhoneNumberTooLong | The phone number including prefix and suffix is too long.
20724 | rasIPXNoDialoutConfigured | The IPX protocol cannot dial-out on the port because the machine is an IPX router.
20725 | rasIPXNoDialinConfigured | The IPX protocol cannot dial-in on the port because the IPX router is not installed.
20726 | rasIPXDialoutAlreadyActive | The IPX protocol cannot be used for dial-out on more than one port at a time.
20727 | rasErrorAccessingTCPCFG | Cannot access TCPCFG.DLL.
20728 | rasNoIPRasAdapter | Cannot find an IP adapter bound to Remote Access.
20729 | rasSLIPRequiresIP | SLIP cannot be used unless the IP protocol is installed.
20730 | rasRegNotComplete | Computer registration is not complete.
20731 | rasProtocolNotConfigured | The protocol is not configured.
20732 | rasPPPNotConverging | The PPP negotiation is not converging.
20733 | rasPPPRejected | The PPP control protocol for this network protocol is not available on the server.
20734 | rasPPPLCPTerminated | The PPP link control protocol terminated.
20735 | rasPPPRequiredAddrRejected | The requested address was rejected by the server.
20736 | rasPPPNCPTerminated | The remote communications server computer terminated the control protocol.
20737 | rasPPPLoopbackDetected | Loopback detected.
20738 | rasPPPNoAddrAssigned | The remote communications server did not assign an address.
20739 | rasCannotUserLogonCredentials | The authentication protocol required by the remote server cannot use the Windows NT encrypted password. Redial, entering the password explicitly.
20740 | rasTAPIconfig | Invalid TAPI configuration.
20741 | rasNoLocalEncryption | The local computer does not support the required encryption type.
20742 | rasNoRemoteEncryption | The remote communications server computer does not support the required encryption type.
20743 | rasRemoteRequiresEncryption | The remote computer requires encryption.
20744 | rasIPXNetNumberConflict | Cannot use the IPX network number assigned by remote server. Check the event log.
20745 | rasInvalidSMM | Error invalid SMM.
20746 | rasSMMUnitialized | SMM is uninitialized.
20747 | rasNoMACforPort | No MAC for port.
20748 | rasSMMTimeout | SMM timeout.
20749 | rasBadPhoneNumber | Bad phone number.
20750 | rasWrongModule | Wrong Module (?).
20751 | rasInvalidCallbackNumber | Invalid callback number. Only the characters 0 to 9, T, P, W, (, ), -, @, and space are allowed in the number.
20752 | rasHangupFailed | The connection could not be closed because it was created by the Multi-Protocol Router.
20753 | rasNoLocalEncryption | The local computer does not support the required encryption type.


StateConstants

Enumerates values of the State property.

Value

Constant

Description

0

rasOpenPort

Opening port. The communication port is about to be opened.

1

rasPortOpened

Port is opened. The communication port has been opened successfully.

2

rasConnectDevice

Connecting to RAS device. A device is about to be connected.

3

rasDeviceConnected

Connected to the RAS device. A device has connected successfully. For a simple modem connection, rasConnectDevice and rasDeviceConnected will be set only once. For a dial-up X.25 PAD connection, the pair will be called first for the modem, then for the PAD. If a preconnect switch is configured, the pair will be called for the switch before any other devices connect. Likewise, the pair will be called for a postconnect switch after any other devices connect. Windows 95: Note that Windows 95 does not currently support multistage connections such as the X.25 PAD connection described earlier.

4

rasAllDevicesConnected

All devices connected. All devices in the device chain have successfully connected. At this point, the physical link is established.

5

rasAuthenticate

Authenticate. The authentication process is starting. Remote access does not allow the remote client to generate any traffic on the LAN until authentication has been successfully completed. Remote access authentication on a Windows NT or Windows 95 server consists of:

  1. Validating the user name/ password on the specified domain.

  2. Projecting the client onto the LAN. This means that the remote access server does what is necessary to send and receive data on the LAN on behalf of the client. For example, the remote access server might need to add a NetBIOS name that corresponds to the client's computer name.

  3. Call-back processing in which the client hangs up and the server calls back. (The user needs special permissions on the remote access server for this.)

  4. Calculating the link speed. This is necessary to correctly set transport time-outs to match the relatively slow speed of the remote link.

6

rasAuthNotify

Authentication is in progress. An authentication event has occurred. This state may repeat itself if progressing smoothly and may be followed by one of the more specific authentication states.

7

rasAuthRetry

Authentication is retrying. The client has requested another validation attempt with a new user name/password/domain. This state does not occur in Windows NT version 3.1.

8

rasAuthCallback

Authenticate callback. The remote access server has requested a callback number. This occurs only if the user has "Set By Caller" callback privilege on the remote communications server.

9

rasAuthChangePassword

Authenticate Changed Password. The client has requested to change the password on the account. This state does not occur in Windows NT version 3.1.

10

rasAuthProject

Authenticate project. The projection phase is starting.

11

rasAuthLinkSpeed

Authenticate link speed. The link speed calculation phase is starting.

12

rasAuthAck

Authenticate acknowledgement. An authentication request is being acknowledged.

13

rasReAuthenticate

Re-Authenticate. Re-authentication (after callback) is starting.

14

rasAuthenticated

Authentication complete. The client has successfully completed authentication.

15

rasPrepareCallback

Prepare for callback. The line is about to disconnect in preparation for callback.

16

rasWaitModemReset

Waiting for modem reset. The client is delaying in order to give the modem time to reset itself in preparation for callback.

17

rasWaitForCallback

Prepare for callback. The client is waiting for an incoming call from the remote communications server.

18

rasProjected

Projected. This state occurs after the rasAuthProject state.

19

rasStartAuth

Start authentication. Windows 95 only: Indicates that user authentication is being initiated or retried.

20

rasCallbackComplete

Callback complete. Windows 95 only: Indicates that the client has been called back and is about to resume authentication

21

rasLoginNetwork

Login to network. Windows 95 only: Indicates that the client is logging on to the network.

4096

rasInteractive

Interactive. This state corresponds to the terminal state supported by RASPHONE.EXE. This state does not occur in Windows NT version 3.1.

4097

rasRetryAuth

Retry Authentication. This state corresponds to the retry authentication state supported by RASPHONE.EXE. This state does not occur in Windows NT version 3.1.

4098

rasCallbackSetCaller

Callback set by caller. This state corresponds to the callback state supported by RASPHONE.EXE. This state does not occur in Windows NT version 3.1.

4099

rasPasswordExpired

Password expired. This state corresponds to the change password state supported by RASPHONE.EXE. This state does not occur in Windows NT version 3.1.

8192

rasConnected

The connection is complete.

8193

rasClosed

The connection is closed.

8195

rasConnecting

Starting a connection. This is immediately set upon invoking the Connect method or the ConnectEntry method.

8198

rasClosing

The connection is closing. This state is immediately set by the Close method.

8199

rasAborting

The connection is aborting. Releasing resources as quick as possible.


System Object

Provides Windows Sockets system information through a simple object interface.


Addresses Property

A collection of local IP addresses in dot notation (for example, 204.7.222.1). Systems may have multiple Network Interface Cards and RAS interfaces configured that will appear in this list.

Syntax

Object.Addresses

Part | Description
Object | Evaluates to a System Object.

Data Type

DartStrings Object

Remarks

Read-only.


Description Property

String containing a description of the Windows Sockets implementation including vendor information.

Syntax

Object.Description

Part | Description
Object | Evaluates to a System Object .

Data Type

String

Remarks

Read-only.


MajorVersion Property

Integer containing major version of Windows Sockets.

Syntax

Object.MajorVersion

Part | Description
Object | Evaluates to a System Object .

Data Type

Integer

Remarks

Read-only.


MinorVersion Property

Integer containing the minor version of Windows Sockets.

Syntax

Object.MinorVersion

Part | Description
Object | Evaluates to a System Object .

Data Type

Integer

Remarks

Read-only.


Name Property

Name of the default IP interface or local host. A typical value would be "eagle3", which might be appended to a domain name to form "eagle3.dart.com".

Syntax

Object.Name

Part | Description
Object | Evaluates to a System Object.

Data Type

String

Remarks

Read-only.

This is provided for informational purposes, and is not needed for most applications.


Status Property

String containing relevant status or configuration information about the Windows Sockets provider.

Syntax

Object.Status

Part | Description
Object | Evaluates to a System Object .

Data Type

String

Remarks

Read-only.


UDP Control

Properties Methods Events Constants Example

Use the UDP Control to send and receive User Datagrams and raw IP Datagrams.

Miscellaneous

Product | PowerTCP Winsock Tool
Prog ID | Dart.Udp.1
File | DartSock.dll
Dependencies | None
Threading | Apartment Model
Licensed | Yes


UDP Control Usage

The following Visual Basic code snippet shows how to use two UDP controls, loaded onto the same form, to send datagrams to/from each other. This code illustrates the use of the Timeout property to wait for an acknowledgment before proceeding to the next step.

Private Sub Form_Load()

' Open both ports on load

Client.Open ' ephemeral port will be automatically assigned

Server.Open 7 ' well-known echo port assigned

Label1.Caption = "Port " & Client.LocalPort & " open on " & Client.LocalAddress

Label2.Caption = "Port " & Server.LocalPort & " open on " & Server.LocalAddress

End Sub

Private Sub Form_Unload()

' clean-up (not really necessary, because PowerTCP automatically releases resources)

Client.Close

Server.Close

End Sub

Private Sub Command1_Click()

Dim i As Integer

Dim Time As Single

Dim Count As Long, TotalCount As Long

' set Time for performance measurement

Time = Timer

Count = 0

' blast datagrams

For i = 1 To 100

' use broadcast address (could also use Server.LocalAddress)

Count = Count + Client.Send("E.T. Phone Home", "255.255.255.255", 7)

Next i

' set Timeout so we will block while waiting for datagrams to come back

Client.Timeout = 1000

TotalCount = Count

Dim s As String

While Count > 0

Count = Count - Client.Receive(s)

Wend

' print out performance

Label1.Caption = Count & " bytes in " & Timer - Time & " seconds"

' Not much to it!

End Sub

Private Sub Server_Receive()

' echo packet back to origin

Dim ba() As Byte ' Byte array is more efficient that a String

Dim Address As String, Port As Long, CountIn As Long, CountOut As Long

' ba will be expanded to hold the datagram, Address will be updated, as will Port

CountIn = Server.Receive(ba, Address, Port)

' just send it back...all the parameters are PERFECT!

CountOut = Server.Send(ba, Address, Port)

End Sub


UDP Protocol Overview

Protocol Overview

UDP provides basic datagram service between two TCP/IP hosts. Whereas TCP provides a reliable stream of data, UDP sends and receives datagrams or blocks of data. UDP is used as transport for the Trivial File Transfer Protocol (TFTP), Simple Network Management Protocol (SNMP), Network Time Protocol (NTP), and others.

UDP enhances IP by providing a header that is used to route packet data to the application that binds itself to the addressed port number. UDP routes data between matching applications on TCP/IP hosts.

UDP provides an unreliable transfer of data. Unlike TCP, your application is not guaranteed that packets will find their way to their ultimate destination. For this reason, most protocols that use UDP utilize acknowledgments.

UDP is a block-oriented protocol. A block of data, if successfully sent and received, arrives as a block of data exactly the same size as that sent. The IP layer takes care of reassembling any packets that may have been fragmented into smaller packets during its transmission. A checksum is used for packet data and corrupted packets are discarded.

UDP system buffering provides simultaneous two-way (full-duplex) data transfer.

Typical Applications

Unlike TCP, which must establish a connection, UDP is quick to set up, easy to use, light on system resources, and simple to program. UDP also can broadcast packets to all computers on a network segment, something TCP cannot do. For these reasons UDP is often used for:

  • Software licensing applications

  • Communications with network devices like routers (that have no need to support TCP)

  • Applications that use packet broadcasting techniques to discover information

  • Simple request/reply protocols, such as Simple Network Management Protocol and Network Time Protocol


DontEcho Property

Disables the local echoing of multicast packets sent by the control.

Syntax

Object.DontEcho

Part | Description
Object | Evaluates to a UDP Control.

Data Type

Boolean

Remarks

The default value is False.

For sockets that have joined a multicast group, the default behavior is to receive a copy of all packets sent by the control to the multicast group you have previously joined. Setting this property to True stops the local echo of those packets sent by you.

Windows95 Note The Winsock2 update is necessary to use multicast sockets. Refer to PowerTCP Distribution for more information.

Error Codes

The DontEcho property may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptOptionNotSupported


MaxSubnets Property

Maximum number of subnets a multicast packet is allowed to travel.

Syntax

Object.MaxSubnets

Part | Description
Object | Evaluates to a UDP Control.

Data Type

Long

Remarks

The default value is 1.

Windows95 Note The Winsock2 update is necessary to use multicast sockets. Refer to PowerTCP Distribution for more information.

Error Codes

The MaxSubnets property may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptOptionNotSupported


Protocol Property

The datagram protocol to use.

Syntax

Object.Protocol

Part | Description
Object | Evaluates to a UDP Control.

Data Type

DgProtocolConstants

Remarks

The defaults value is ptUdp (User Datagram Protocol).

When the Open method opens a local datagram port, this property specifies the protocol to use. The protocol cannot be set after the socket is open.

Most applications use the default value, ptUdp, which specifies the User Datagram Protocol. The other values use sockets of type SOCK_RAW, which indicate that IP packets will be sent and received using the conventions established by the vendor of the TCP/IP system software.

For sockets of type SOCK_RAW, the system may allow the user to build and send his own IP headers by using the socket option IP_HDRINCL. You can enable this option by setting the UserHeaders property to True.

Windows95 Note The Winsock2 update is necessary to use sockets of type SOCK_RAW (Protocol not ptUdp). Refer to the PowerTCP Distribution topic for more information.

Error Codes

The Protocol property may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptOptionNotSupported


UserHeaders Property

Enables the use of user-defined IP headers.

Syntax

Object.UserHeaders

Part | Description
Object | Evaluates to a UDP Control.

Data Type

Boolean

Remarks

For sockets of type SOCK_RAW (Protocol is not ptUdp), the system may allow users to build and send their own IP headers using the socket option IP_HDRINCL. Enable this option setting this property to True after the Open method is used.

Windows95 Note The Winsock2 update is necessary to use sockets of type SOCK_RAW. Refer to the PowerTCP Distribution topic for more information.

Error Codes

The UserHeaders property may generate the following error code (refer to the ErrorConstants topic for a complete list of error codes):

ptOptionNotSupported


Join Method

Join a multicast group.

Syntax

Object.Join Address

Part | Description
Object | Object expression that evaluates to a UDP Control.
Address | String or Byte array. Contains the IP Address of the group in the form of nnn.nnn.nnn.nnn.

Remarks

Multicast groups are specified as an IP Address within a specified range of addresses. This group of addresses, also know as class D IP Addresses, are in the range from 224.0.0.0 through 239.255.255.255. In order to receive packets sent to a multicast group, you must first join the group using this method.

Error Codes

The Join method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptNetworkDown

  • ptNotInitialized

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected (Open method was not used first)


Receive Method

Receive a datagram into a buffer.

Syntax

[ Count = ] Object.Receive Data [ , RemoteAddress ] [ , RemotePort ]

Part | Description
Object | Object expression that evaluates to a UDP Control.
Data | Undimensioned Byte array, String, or DartStream Object. Will contain a copy of the datagram.
RemoteAddress | Optional String. Will be filled with the source address.
RemotePort | Optional Long. Will be filled with the source port. Only used if Protocol is ptUdp.
Count | Long.

Remarks

The Open method must be used to open a socket prior to using this method (the LocalPort property must not be 0).

The number of Unicode characters or bytes copied into Data. When Data is a String, all bytes are converted to 16-bit Unicode characters according to the default ANSI code page. If the code page is not ASCII, multi-byte characters may convert to single Unicode characters. The Byte array or String is resized to this value.

Error Codes

The Receive method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptNetworkReset

  • ptNotConnected (Open method was not used first)

  • ptNotInitialized

  • ptTimeout


Send Method

Send a datagram to the specified remote address and port.

Syntax

[ Count = ] Object.Send Data, RemoteName [ , RemotePort ] [ , LimitCount ] [ , DontRoute ]

Part | Description
Object | Object expression that evaluates to a UDP Control.
Data | String or Byte array. Contains the data to be sent.
RemoteName | String. Specifies the destination dot address or name.
RemotePort | Optional Long. Specifies the destination port. Required if Protocol is ptUdp.
LimitCount | Optional Long. Specifies the size of the datagram in octets. This can be used to override the length of the Data parameter.
DontRoute | Optional Boolean. Specifies if the data should not be subject to routing.
Count | Long. Returns the number of Unicode characters or bytes copied from the Data variable.

Remarks

The Open method must be used to open a socket prior to using this method (the LocalPort property must not be 0).

If RemoteName is in dot notation (for example, nnn.nnn.nnn.nnn), then Data is immediately sent or is cached for sending later if the system buffers are full.

If RemoteName is a host name (for example, eagle3.dart.com), then Data is cached, the host name is asynchronously resolved, and Data is sent when the system buffers can accept it.

If Data is a String, all bytes are converted from 16-bit Unicode characters to multi-byte characters according to the system default ANSI code page. If this is US-ASCII, then each Unicode character converts to a single 8-bit ASCII character. If the code page is not US-ASCII, then each 16-bit Unicode character is translated into a general multi-byte representation.

SendDatagramCount indicates the number of datagrams currently cached.

Error Codes

The Send method may generate the following error codes (refer to the ErrorConstants topic for a complete list of error codes):

  • ptAddressNotAvailable

  • ptMessageSize

  • ptNetworkDown

  • ptNetworkReset

  • ptNoBufferSpace

  • ptNotConnected (Open method was not used first)

  • ptNotInitialized


Receive Event

Fires when a datagram is available for receiving.

Syntax

Private Sub Object_Receive ( [ Index As Integer ] )

Part | Description
Object | Evaluates to a UDP Control.
Index | Integer. Array index if the object is part of an array.

Remarks

WARNING Timeout MUST BE 0 when calling methods from within an event. Failure to observe this rule may cause reentrancy problems and unpredictable results.

The Receive method is used to access data. By using the Receive method from within the body of this event, you can optimize the processing speed of your application without blocking (waiting for data to arrive) or polling (continually checking for available data). The Receive method must be called to enable this event to fire more than once.


DgProtocolConstants

Enumerated values of the Protocol property specifies the type of datagram socket to be created by the Open method:

Value | Constant | Description
1 | ptIcmp | Create a socket that builds IP headers with ICMP specified as the protocol. Received packets are reported with the 20-byte IP header included as data.
2 | ptIgmp | Create a socket that builds IP headers with IGMP specified as the protocol. Received packets are reported with the 20-byte IP header included as data.
3 | ptGgp | Create a socket that builds IP headers with GGP specified as the protocol. Received packets are reported with the 20-byte IP header included as data.
17 | ptUdp | Create a socket that builds IP and UDP headers. A local port and address can be specified for binding purposed. Received packets are reported with data only (IP and UDP headers are removed by the system).
255 | ptRaw | Create a socket that builds IP headers with RAW specified as the protocol. Received packets are reported with the 20-byte IP header included as data.


KB Overview

Knowledge Base Overview

Welcome to the Dart Knowledge Base.

The Knowledge Base is currently divided into these categories:

General Issues- For issues that apply to all tools, development environment issues, distribution issues, licensing issues, and other general problems.

Mail Tool Issues- For issues pertaining to the PowerTCP Mail Tool.

Snmp Tool Issues- For issues pertaining to the PowerTCP SNMP Tool.

Web Tool Issues- For issues pertaining to the PowerTCP Web Tool.


KB General Issues Overview

Knowledge Base - General Issues

General Issues

Control does not work on a web page.

Cannot click a button during some PowerTCP operations.

Visual Basic Issues

VB created ActiveX Control always gives trial message or 429 error.

How do I use your controls in VB without a form?

FoxPro Issues

FoxPro fires Error event with the incorrect number of parameters.

State property does not appear in the FoxPro object browser.

Events do not fire in FoxPro.

PowerBuilder Issues

PowerBuilder app always gives trial message.

ASP Issues

How do I use your controls with ASP?

Trial message when distributing ASP applications.

ASP Error 8002801d "Library not registered"

Eight second delay when creating object on ASP page.

VC Issues

How do I create one of your controls in VC without MFC?

How do I create a licensed control in VC6?


QGEN0001

PRB: Control does not work on web page

ID Number: QGEN0001

Symptoms:

You have a web page that embeds one of our controls. It works fine on your development machine but when you try to use it on another machine there is a red "X" where the control should be and the page does not work.

Cause:

You need to provide a runtime license for the control.

Resolution:

Get LPK_TOOL.EXE from Microsoft. You can find it in their Cabinet Development kit. It is also on one of the CD's that comes with Visual Studio. Use the LPK_TOOL to create a .lpk file for your control. Add the following to your document BEFORE any other objects are declared. Make sure LPKNAME.LPK is the name of YOUR lpk:

<OBJECT CLASSID=clsid:5220cb21-c88d-11cf-b347-00aa00a28331>

<PARAM NAME="LPKPath" VALUE="LPKNAME.LPK">

</OBJECT>

More Info:

None


QGEN0009

Cannot click a button during some PowerTCP operations.

ID Number: QGEN0009

Symptoms:

Buttons do not respond to mouse click during PowerTCP operation.

Cause:

Progress does not contain DoEvents command.

Resolution:

Progress event must contain a DoEvents command (VFP command).

More Info:

Although the DoEvents command will let your program respond to a user's action, it significantly slows the running of the event code, and therefore slows the apparent speed of the file transfer.


QGEN0003

VB created ActiveX Control always gives trial message or a 429 error.

ID Number: QGEN0003

Symptoms:

No matter how many times you recompile a VB6 created ActiveX control that contains one of our controls, you get a trial message when you try to distribute it.

Cause:

When a Licensed control is inserted onto a UserControl, VB6 calls CreateInstance (instead of CreateInstanceLic) to create it.

Resolution:

Instead of inserting the Dart control visually, add it as a reference and Dim it. The following example shows how to do this using the Dart Tcp control:

1) Select Project | References and add the Dart Tcp DLL. DO NOT ADD THE OCA!

2) Add the following code to the top of the module:

Private Withevents Tcp1 as Tcp

3) Add the following when you want to create the control:

Set Tcp1 = New Tcp

More Info:

None


QGEN0004

How do I use your controls in VB without a Form?

ID Number: QGEN0004

Symptoms:

You want to use a Dart control without placing it on a form.

Cause:

N/A

Resolution:

This example shows how to create the Dart TCP control:

1) From the VB menu select Project | References

2) Select the Dart TCP, UDP and Daemon Controls

NOTE: If VB says the location is DartSock.oca, it means that you already have the control added to the toolbox. If you want both, that's OK, but DartTelnet.Dll has to be top priority in order to use it as a reference.

3) Add the following code to the top of your module:

Private Withevents Tcp1 as Tcp

4) When you want to create the control, use the following code:

Set Tcp1 = New Tcp

5) When you want to unload the control use the following code:

Set Tcp1 = Nothing

More Info:

None


QGEN0006

FoxPro fires Error event with the incorrect number of parameters.

ID Number: QGEN0006

Symptoms:

When using Dart Tools in VFP, a Tool error that occurs fires an event but passes parameters based on a VFP error, in which case the parameters do not match the expected parameters.

Cause:

In VFP, you implement an ActiveX control by inserting it into a VFP OLE Container control on a form. An OLE Container control, like all controls in VFP, has an Error event that is passed three parameters: nError, cMethod, and nLine. For example, the FTP Tool also has an Error event, but it is passed two parameters: Number and Description. VFP cannot distinguish or code the two Error events separately. Thus, the VFP Error event is fired by either the FTP Tool (2 parameters) or by VFP (3 parameters).

Resolution:

Use the following technique to code the Error event so that it will handle both Dart FTP errors and VFP errors:

* Dart FTP ActiveX Control Event & VFP OLE Container Control Event

*--------------------------------------------------------------

*

* If fired by a Dart FTP error, the passed parameters are

* Number, Description

*

* If fired by a VFP error, the passed parameters are

* nError, cMethod, nLine

*

parameters ;

Parameter1, ;

Parameter2, ;

Parameter3

if pcount() = 2

*-------- Dart FTP ActiveX Error --------------

local ;

Number, ;

Description

m.Number = m.Parameter1

m.Description = m.Parameter2

<insert code here to handle Dart FTP error>

else

*-------- VFP Error ---------------------------

local ;

nError, ;

cMethod, ;

nLine

m.nError = m.Parameter1

m.cMethod = m.Parameter2

m.nLine = m.Parameter3

<insert code here to handle VFP error>

endif

More Info:

None


QGEN0007

State property does not appear in the FoxPro object browser

ID Number: QGEN0007

Symptoms:

When using Dart Tools in VFP, the Tool’s State property does not appear in the VFP object inspector.

A reference to oleX.State at run-time cause the following VFP error: "Property or method not found."

Cause:

In VFP you cannot have a property named the same as an event or method.

Resolution:

The OLE Container control has an Object property that allows you to directly reference properties/methods of the contained ActiveX control. For example, use the following to reference a Tool’s State property: oleX.Object.State.

More Info:

A VFP OLE Container control has its own properties and methods, but when an ActiveX control is inserted into it (at design time), its object inspector shows both its properties/methods/events and the properties/methods/events of the contained ActiveX control. If you have an OLE Container control, say oleX, on a VFP form, you reference the properties/methods/events of both it and the contained ActiveX control like this:

Search Dart's Support Forum for:
oleX.ContainerProperty1, oleX.ContainerMethod1, oleX.ActiveXProperty1, oleX.ActiveXMethod1.


QGEN0008

Events do not fire in FoxPro.

ID Number: QGEN0008

Symptoms:

You are unable to get a Tool’s event to fire in VFP.

Cause:

_VFP.AutoYield property is not set correctly.

Resolution:

_VFP.AutoYield property must be set to false to allow ActiveX events to fire.

More Info:

None


QGEN0012

PowerBuilder app always gives trial message

ID Number: QGEN0012

Symptoms:

You have followed the directions in the README pertaining to cutting and pasting each control after installing the license, but you still get a Trial message when you deploy your app.

Cause:

Control is probably being created in a way that does not facilitate licensing.

Resolution:

You can't dynamically create our controls and get the licensing into the EXE. You must insert the control onto a window or Userobject.

When you insert a control make sure you use "Insert" and not "Create New"

More Info:

None


QGEN0002

How do I use your controls with ASP?

ID Number: QGEN0002

Symptoms:

You may wish to use a PowerTCP Control in ASP.

Cause:

N/A

Resolution:

The following code shows how to create an HTTP control to fetch our web page using VBScript within an ASP page:

<%

Dim Reply

Dim Http1

Set Http1 = Server.CreateObject("Dart.Http.1")

Http1.Cache = False

Http1.Url = "http://www.dart.com"

Reply = "" ' do this to cast Reply to a string!

Http1.Get Reply

Response.Write Reply

%>

When doing this in trial mode, there will be a 10 second delay before the page loads.

More Info:

See "Distribution under IIS" in the Online Help for information related to licensing and IIS.


QGEN0005

Trial message when distributing ASP applications

ID Number: QGEN0005

Symptoms:

You have an ASP page that you have successfully developed and tested on the machine where you registered PowerTCP. When you attempt to install this page to a machine that does not have a PowerTCP license, you get a delay before the page loads.

Cause:

You need to copy your development license to the other machine.

Resolution:

1) Go to the development machine and run regedit.

2) In the left panel select the following key:

HKEY_LOCAL_MACHINE\SOFTWARE\Dart\PowerTCP\License

3) At this point you can either manually add the licenses

under this key to the other machine, or you can export

them to a file that be imported on the other machine.

(Registry | Export Registry File)

More Info:

None


QGEN0013

ASP Error 8002801d "Library not registered"

ID Number: QGEN0013

Symptoms:

When someone loads an Active Server Pages (ASP) page that has a Dart control it you may receive the following error message:

Server object error 'ASP 0177 : 8002801d'

Server.CreateObject Failed

/vdir/filename.asp, line xx

Library not registered.

Cause:

Usually caused by having a non-Admin install and register the Dart DLL's

Resolution:

Make sure you have Admin rights when you install the DLL's on the server.

More Info:

Search the online support forum for:

Library not registered ASP Error.

http://support.microsoft.com/support/kb/articles/q274/0/38.asp


QGEN0014

Eight second delay when creating object on ASP page

ID Number: QGEN0014

Symptoms:

When a user loads ASP page containing a Dart control, they report that there is a long delay before the page loads.

Cause:

This means that you installed the Dart DLL's on a machine that does not have a registry license entry for the control.

Resolution:

After you have purchased the Dart Tool and installed the development license on your machine. You will need to export this license to the server that is serving the ASP page. This eliminates the trial message that appears in IIS's desktop. Since you can't see the messagebox you can't close it and it goes away on it's own after 8 seconds. See Distribution under Internet Information Server in the Online Help for more information.

More Info:

Search the online support forum for:

ASP asp error delay trial nag splash.


QGEN0010

How do I create one of your controls in VC without MFC?

ID Number: QGEN0010

Symptoms:

You want to create and use one of our controls without inserting as a resource

Cause:

N/A

Resolution:

// Declare the interface

ITcp pTcp;

// The License number can be found in the registry:

// HKEY_LOCAL_MACHINE\SOFTWARE\Dart\PowerTCP\License\<Tool>

BSTR License = SysAllocString(L"");

CreateLicensedControl(OLESTR("Dart.Tcp.1"), License, (void **)&pTcp))

int CreateLicensedControl(LPCOLESTR lpszProgID, BSTR bstrLicense, void ** ppControl)

{

// Get Class ID

CLSID clsID;

HRESULT hr = CLSIDFromProgID(lpszProgID, &clsID);

if(hr!=S_OK)

return 0;

// Get Class Factory Object

IUnknown *ppv;

IClassFactory2 *pClassFactory2;

hr = CoGetClassObject(clsID,

CLSCTX_INPROC_SERVER |

CLSCTX_INPROC_HANDLER,NULL,

IID_IClassFactory2,

(void**)&pClassFactory2);

if (hr==S_OK)

{

hr = pClassFactory2->CreateInstanceLic(NULL,NULL,IID_IOleObject,bstrLicense,(void**)&ppv);

//Don't forget to release

pClassFactory2->Release();

if(hr==S_OK)

{

// Query Interface

hr = ppv->QueryInterface(IID_IDispatch, ppControl);

if(hr!=S_OK)

return 0;

else

{

ppv->Release();

return 1;

}

}

else

return 0;

}

else

return 0;

}

More Info:

None


QGEN0011

How do I create a licensed control in VC6?

ID Number: QGEN0011

Symptoms:

You want to dynamically create one of our controls in Visual C++ and you always get a trial message.

Cause:

Our controls need to be created with the function CreateInstanceLic with a valid serial number.

Resolution:

#include "dartsock.h"

ITcp pTcp;

// The License number can be found in the registry:

// HKEY_LOCAL_MACHINE\SOFTWARE\Dart\PowerTCP\License\<Tool>

BSTR License = SysAllocString(L"");

CreateLicensedControl(OLESTR("Dart.Tcp.1"), License, (void **)&pTcp))

int CreateLicensedControl(LPCOLESTR lpszProgID, BSTR bstrLicense, void ** ppControl)

{

// Get Class ID

CLSID clsID;

HRESULT hr = CLSIDFromProgID(lpszProgID, &clsID);

if(hr!=S_OK)

return 0;

// Get Class Factory Object

IUnknown *ppv;

IClassFactory2 *pClassFactory2;

hr = CoGetClassObject(clsID,

CLSCTX_INPROC_SERVER |

CLSCTX_INPROC_HANDLER,NULL,

IID_IClassFactory2,

(void**)&pClassFactory2);

if (hr==S_OK)

{

hr = pClassFactory2->CreateInstanceLic(NULL,NULL,IID_IOleObject,bstrLicense,(void**)&ppv);

//Don't forget to release

pClassFactory2->Release();

if(hr==S_OK)

{

// Query Interface

hr = ppv->QueryInterface(IID_IDispatch, ppControl);

if(hr!=S_OK)

return 0;

else

{

ppv->Release();

return 1;

}

}

else

return 0;

}

else

return 0;

}

More Info:

None


KB Mail Tool Issues Overview

Knowledge Base- Mail Tool Issues Overview

How do I send an HTML message like Outlook does?


Q1540001

How do I send an HTML message like Outlook does?

ID Number: Q1540001

Symptoms:

Outlook express always sends me messages in HTML. How do I accomplish this using the PowerTCP Mail tool?

Cause:

N/A

Resolution:

While the Mail Tool will not encode HTML, there is a way to send an HTML message, provided that you can supply the HTML. See the following code. To use, create a new VB Project and put an SMTP control and a Command button on the form. Edit the constants that are declared at the top and run the program:

Option Explicit

Const Sender = ""

Const Recipient = ""

Const Server = ""

Private Sub Command1_Click()

On Error GoTo OnError

Command1.Enabled = False

TestStub

GoTo Done

OnError:

Debug.Print "ERROR #" + CStr(Err.Number) + ": " + Err.Description

Done:

Command1.Enabled = True

End Sub

Private Sub TestStub()

Smtp1.Message.Content = ""

Smtp1.To.Add Recipient

Smtp1.From = Sender

Smtp1.Message.To.Add Recipient

Smtp1.Message.From = Sender

Smtp1.Message.Subject = "Test HTML"

' Add the HTML part of the message

Dim p As Part

Set p = New Part

p.Data = HTMLMessage

p.Header.Clear

p.Header.Add msgContentType, "text/html; charset=""iso-8859-1"""

p.Header.Add msgEncoding, "quoted-printable"

Smtp1.Message.Parts.Add p

Set p = New Part

p.Data = TextMessage

p.Header.Clear

p.Header.Add msgContentType, "text/plain"

Smtp1.Message.Parts.Add p

Smtp1.Message.Header.Add msgContentType, "multipart/alternative"

Smtp1.Login Server

Smtp1.Send

Smtp1.Logout

End Sub

Private Function HTMLMessage() As String

Dim s As String

s = "<HTML><CENTER><FONT color=#800000 face=Arial size=7>"

s = s + "Hello World!"

s = s + "</FONT></CENTER></BODY></HTML>"

HTMLMessage = s

End Function

Private Function TextMessage() As String

TextMessage = "Hello World"

End Function

Private Sub Form_Load()

If Recipient = "" Or Sender = "" Then

MsgBox "Constants Not Set in Code!"

Unload Me

End If

End Sub

More Info:

None


KB Snmp Tool Issues Overview

Knowledge Base- Snmp Tool Issues Overview

The module name in the v1.1 traps.mib is incorrect.

Issues involving the installation of SNMP Tool Version 2 over SNMP Tool Version 1.


Q1550001

PRB: The module name in the v1.1 traps.mib is incorrect.

ID Number: Q1550001

Symptoms

N/A

Cause

N/A

Resolution

The module name in the v1.1 traps.mib is incorrect. It should not be RFC1213, which is the same as mib_ii. The automatic duplicate checking will eliminate traps.mib if the old version of this file is used. The new version of the file now uses this declaration at the top of the file:

RFC1157-MIB DEFINITIONS ::= BEGIN

as opposed to:

RFC1213-MIB DEFINITIONS ::= BEGIN

Please make sure any applications dependent on traps.mib use the latest version of this header, or they will not compile these traps.


Q1550002

PRB: Issues involving the installation of SNMP Tool Version 2 over SNMP Tool Version 1.

ID Number: Q1550002

Symptoms

You wish to install SNMP Tool Version 2 on a machine with SNMP Tool Version 1 installed and you want to know of any conflicts.

You have installed SNMP Tool Version 2 on a machine with SNMP Tool Version 1 installed and you wish to revert back.

Cause

N/A

Resolution

If you install SNMP Tool Version 2 on a machine with SNMP Tool Version 1 installed you will no longer be able to use your previous version of the SNMP Tool or the serial number that was assigned to your previous version while Version 2 of the SNMP Tool is installed on your system.

If you wish to revert back to your original version, please make sure that you uninstall SNMP Tool Version 2 so that your license key will be restored. Then re-run the previous version's setup program so that the previous DLL will be registered. Your previous serial number will be saved in the INSTALL.LOG and will be restored upon executing the uninstall for the latest version of the SNMP Tool.

If you wish to get the latest version of SNMP Tool Version 1, go to http://www.dart.com/downloads and click the download link for SNMP Tool Version 1.


KB Web Tool Issues Overview

Knowledge Base- Web Tool Issues Overview

My program does not unload after I do a Secure GET or POST.


Q1570001

My program does not unload after I do a Secure GET or POST

ID Number: Q1570001

Symptoms:

When using the HTTP control to do a secure GET or POST, the program never exits and you have to manually remove the process.

Cause:

This is a known issue with WININET.DLL, which we use internally.

Resolution:

See the following Microsoft KnowledgeBase Article:

http://support.microsoft.com/support/kb/articles/Q238/9/34.ASP.

Also, the PowerTCP WebASP Control is a WININET-independent HTTP control available with the Web Enterprise Tool.

More Info:

None


HttpStatusConstants

Enumerates standard values for Status. These are explained in RFC 2616. If a custom status is desired, Status and StatusText can be set to any desired value.

When Status is set to: StatusText is set to:

Value | Constant | Description
100 | httpContinue | "Continue"
101 | httpSwitchingProtocols | "Switching Protocols"
200 | httpOK | "OK"
201 | httpCreated | "Created"
202 | httpAccepted | "Accepted"
203 | httpNonAuthoritativeInformation | "Non-Authoritative Information"
204 | httpNoContent | "No Content"
205 | httpResetContent | "Reset Content"
206 | httpPartialContent | "Partial Content"
300 | httpMultipleChoices | "Multiple Choices"
301 | httpMovedPermanently | "Moved Permanently"
302 | httpFound | "Found"
303 | httpSeeOther | "See Other"
304 | httpNotModified | "Not Modified"
305 | httpUseProxy | "Use Proxy"
307 | httpTemporaryRedirect | "Temporary Redirect"
400 | httpBadRequest | "Bad Request"
401 | httpUnauthorized | "Unauthorized"
402 | httpPaymentRequired | "Payment Required"
403 | httpForbidden | "Forbidden"
404 | httpNotFound | "Not Found"
405 | httpMethodNotAllowed | "Method Not Allowed"
406 | httpNotAcceptable | "Not Acceptable"
407 | httpProxyAuthenticationRequired | "Proxy Authentication Required"
408 | httpRequestTimeOut | "Request Time-out"
409 | httpConflict | "Conflict"
410 | httpGone | "Gone"
411 | httpLengthRequired | "Length Required"
412 | httpPreconditionFailed | "Precondition Failed"
413 | httpRequestEntityTooLarge | "Request Entity Too Large"
414 | httpRequestURITooLarge | "Request-URI Too Large"
415 | httpUnsupportedMediaType | "Unsupported Media Type"
416 | httpRequestRangeNotSatisfiable | "Request range not satisfiable"
417 | httpExpectationFailed | "Expectation Failed"
500 | httpInternalServerError | "Internal Server Error"
501 | httpNotImplemented | "Not Implemented"
502 | httpBadGateway | "Bad Gateway"
503 | httpServiceUnavailable | "Service Unavailable"
504 | httpGatewayTimeOut | "Gateway Time-out"
505 | httpVersionNotSupported | "HTTP Version not supported"


WebRedirect Constants

Value | Constant | Description
0 | webRedirectNone | Do not allow any redirection at all
1 | webRedirectAll | Allow all redirection
2 | webRedirectSame | Allow redirection from any source to a similar destination
4 | webRedirectToSecure | Allow redirection from a non-secure source to a secure destination
8 | webRedirectToNonSecure | Allow redirection from a secure source to a non-secure destination


IMAP Protocol Overview

This topic covers:

  • Protocol Overview

  • Client Protocol Sender and Server Protocol Receiver

  • Server Protocol Sender and Client Protocol Receiver

Protocol Overview

The Internet Message Access Protocol, Version 4rev1 (IMAP4rev1) allows a client to access and manipulate electronic mail messages on a server. IMAP4rev1 permits manipulation of remote message folders, called "mailboxes", in a way that is functionally equivalent to local mailboxes. IMAP4rev1 also provides the capability for an off-line client to resynchronize with the server (see also [IMAP-DISC]). IMAP4rev1 includes operations for:

  • Creating, deleting, and renaming mailboxes.

  • Checking for new messages.

  • Permanently removing messages.

  • Setting and clearing flags.

  • [RFC822] and [MIME-IMB] parsing.

  • Searching.

  • Selective fetching of message attributes, texts, and portions thereof.

Messages in IMAP4rev1 are accessed by the use of numbers. These numbers are either message sequence numbers or unique identifiers. IMAP4rev1 supports a single server. A mechanism for accessing configuration information to support multiple IMAP4rev1 servers is discussed in [ACAP]. IMAP4rev1 does not specify a means of posting mail; this function is handled by a mail transfer protocol such as [SMTP]. IMAP4rev1 is designed to be upward-compatible from the [IMAP2] and unpublished IMAP2bis protocols. In the course of the evolution of IMAP4rev1, some aspects in the earlier protocol have become obsolete. Obsolete commands, responses, and data formats which an IMAP4rev1 implementation may encounter when used with an earlier implementation are described in [IMAP-OBSOLETE]. Other compatibility issues with IMAP2bis, the most common variant of the earlier protocol, are discussed in [IMAP-COMPAT]. A full discussion of compatibility issues with rare (and presumed extinct) variants of [IMAP2] is in [IMAP-HISTORICAL]; this document is primarily of historical interest.

The IMAP4rev1 protocol assumes a reliable data stream such as provided by TCP. When TCP is used, an IMAP4rev1 server listens on port 143. An IMAP4rev1 connection consists of the establishment of a client/server network connection, an initial greeting from the server, and client/server interactions. These client/server interactions consist of a client command, server data, and a server completion result response. All interactions transmitted by client and server are in the form of lines; that is, strings that end with a CRLF. The protocol receiver of an IMAP4rev1 client or server is either reading a line or reading a sequence of octets with a known count followed by a line.

Back to Top

Client Protocol Sender and Server Protocol Receiver

The client command begins an operation. Each client command is prefixed with an identifier (typically a short alphanumeric string, for example, A0001, A0002, etc.) called a "tag". The client generates a different tag for each command.

A line from the client does not represent a complete command in the following two cases

  • A command argument is quoted with an octet count.

  • The command arguments require server feedback.

In either case, the server sends a command continuation request response if it is ready for the octets (if appropriate) and the remainder of the command. This response is prefixed with the token "+".

Note If, instead, the server detected an error in the command, it sends a BAD completion response with tag matching the command (as described below) to reject the command and prevent the client from sending any more of the command.

It is also possible for the server to send a completion response for some other command (if multiple commands are in progress) or untagged data. In either case, the command continuation request is still pending; the client takes the appropriate action for the response and reads another response from the server. In all cases, the client MUST send a complete command (including receiving all command continuation request responses and command continuations for the command) before initiating a new command. The protocol receiver of an IMAP4rev1 server reads a command line from the client, parses the command and its arguments, and transmits server data and a server command completion result response.

Back to Top

Server Protocol Sender and Client Protocol Receiver

Data transmitted by the server to the client and status responses that do not indicate command completion are prefixed with the token "*", and are called untagged responses. Server data may be sent as a result of a client command, or may be sent unilaterally by the server. There is no syntactic difference between server data that resulted from a specific command and server data that was sent unilaterally. The server completion result response indicates the success or failure of the operation. It is tagged with the same tag as the client command which began the operation. Thus, if more than one command is in progress, the tag in a server completion response identifies the command to which the response applies.

There are three possible server completion responses:

  • OK (indicating success)

  • NO (indicating failure)

  • BAD (indicating protocol error such as unrecognized command or command syntax error)

The protocol receiver of an IMAP4rev1 client reads a response line from the server. It then takes action on the response based upon the first token of the response, which can be a tag, a "*", or a "+". A client must be prepared to accept any server response at all times. This includes server data that was not requested. Server data should be recorded, so that the client can reference its recorded copy rather than sending a command to the server to request the data. In the case of certain server data, the data must be recorded.

Back to Top


Ping Control Example

This VB example shows the use of a Ping Control to test if a server is reachable.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Count As Integer

Dim Delay As Integer

Ping1.Timeout = 10000 'give it 10 seconds to complete

Delay = 0

For Count = 1 To 3

Ping1.Ping "www.dart.com"

Delay = Delay + Ping1.Delay

Next Count

' take the average time

Delay = Delay / Count

MsgBox "Server is reachable, average delay " & Delay & " ms"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "ERROR #" + CStr(Err.Number) + ": " + Err.Description

End Sub


SMTP Protocol Overview

This topic covers:

  • RFCs Supported

  • Transmission Channel Opening and Closing

  • Mail

  • Verifying User Names and Expanding Mailing Lists

  • Service Extensions

RFCs Supported

This product supports the following RFCs:

  • RFC 821 – Simple Mail Transfer Protocol (SMTP)

  • RFC 1123 – Requirements for Internet Hosts

  • RFC 1869 – SMTP Service Extensions

  • RFC 1870 – SMTP Service Extension for Message Size Declaration

  • RFC 1652 – SMTP Service Extension for 8bit-MIME Transport

  • RFC 2197 – SMTP Service Extension for Command Pipelining

  • RFC 2034 – SMTP Service Extension for Returning Enhanced Error Codes

  • RFC 1894 – An Extensible Message Format for Delivery Status Notifications (DSNs)

  • RFC 1893 – Enhanced Mail System Status Codes

  • RFC 1891 – SMTP Service Extension for Delivery Status Notifications

  • RFC 2442 – The Batch SMTP Media Type

The SMTP protocol is initiated when the client establishes a TCP connection with an SMTP server. The server may be the ultimate destination or a relay point for the message.

Once the connection is established, the client sends a greeting to determine the protocol extensions the server supports. This greeting exchange begins with a client sending the EHLO command.

To send mail, the MAIL command is sent from client to server, indicating the sender of the mail. The server responds with an OK reply indicating it is able to accept mail. The client then sends a RCPT command identifying a recipient of the mail. If the server can accept mail for that recipient it responds with an OK reply; if not, it responds with a reply rejecting that recipient (but not the mail transaction). The client can specify several recipients. As long as one recipient is accepted, the client sends the mail data and terminates with a special sequence. If the server successfully processes the mail data it responds with an OK reply. This dialog is initially synchronized in lock step, one command at a time.

The MAIL command's argument is a reverse-path, which specifies who the mail is from. The argument to the RCPT command is a forward-path, which specifies who the mail is to. The forward-path is a source route, while the reverse-path is a return route (which may be used to return a message to the sender if an error occurs with a relayed message).

When the same message is sent to multiple recipients the protocol encourages the transmission of only one copy of the data for all the recipients at the same destination host.

By default, commands and replies are composed of characters from the US-ASCII (7-bit) character set. If the server supports the extended protocol for an 8-bit byte (octet) transmission channel, it responds with this extension at greeting time. PowerTCP supports 8-bit binary transmissions. When the server accepts and forwards a message containing 8-bit data, any 7-bit only intermediate network segments that detect the impending message may refuse to receive the message. This generally results in the message being returned-to-sender.

Back to Top

Transmission Channel Opening and Closing

The following three commands are used in transmission channel opening and closing:

HELO <SP> <domain> <CRLF>
EHLO <SP> <domain> <CRLF>
QUIT <CRLF>

Login uses the HELO and EHLO commands for identification to the server; this command may be interpreted as "Hello, I am <domain>". The normal response to HELO would be a single line response:

250 dbc.mtview.ca.us says hello.

The EHLO command further allows the server to issue a multi-line response identifying any service extensions or optional commands supported, such as:

250- dbc.mtview.ca.us says hello.
250-EXPN
250-HELP
250-8BITMIME
250-SIZE
250-XABC

In this response the server signals its support for two optional commands EXPN and HELP, two service extensions 8BITMIME and SIZE, and one unregistered service extension XABC (identified as experimental by the "X" prefix). These service extension as used to populate the Capabilities property.

Logout sends the QUIT command, causing the server to close the connection.

Back to Top

Mail

There are three steps to send mail, all implemented by the Send method. The transaction is started with a MAIL FROM command, which provides sender identification. A series of one or more RCPT TO commands provides recipient information. Then a DATA command gives the mail data. The end of mail data indicator confirms the transaction.

The first step is the MAIL command. The <reverse-path> contains the source mailbox.

MAIL <SP> FROM: <reverse-path> <CRLF>

This command indicates a new mail transaction is starting (the server should reset all state tables and buffers). It includes the reverse-path, which can be used to report errors. If accepted, the server returns a 250 OK reply.

The second step is the RCPT command.

RCPT <SP> TO: <forward-path> <CRLF>

This command includes a forward-path identifying one recipient. If accepted, the server returns a 250 OK reply and stores the forward-path. If the recipient is unknown the server returns a 550 Failure reply. This second step can be repeated multiple times.

The third step is the DATA command.

DATA <CRLF>

If accepted, the server returns a 354 Intermediate reply and considers all succeeding lines to be the message. When the end of text is received and stored the server sends a 250 OK reply.

The mail message includes header fields with labels such as Date, Subject, To, Cc, and From followed by the message body.

The end of the mail data must be indicated so that the command and reply dialog can be resumed. A line containing a single period indicates the end of the mail. A transparency procedure prevents this from interfering with the message.

The end of mail indicator tells the server to process the stored recipients and mail data. If accepted, the server returns a 250 OK reply. The DATA command should fail only if the mail transaction was incomplete (for example, no recipients), or if resources are not available on the server.

Example

This example shows how Smith at Alpha.ARPA sends mail to Jones, Green, and Brown at Beta.ARPA. Alpha contacts host Beta directly (no intermediate mail servers are involved). This exchange is typical of that resulting from the Send method.

S: MAIL FROM: <Smith@Alpha.ARPA>
R: 250 OK
S: RCPT TO: <Jones@Beta.ARPA>
R: 250 OK
S: RCPT TO: <Green@Beta.ARPA>
R: 550 No such user here
S: RCPT TO: <Brown@Beta.ARPA>
R: 250 OK
S: DATA
R: 354 Start mail input; end with <CRLF> . <CRLF>
S: Blah blah blah...
S: ...etc. etc. etc.
S: <CRLF>.<CRLF>
R: 250 OK

The mail has now been accepted for Jones and Brown. Green did not have a mailbox at host Beta.

Back to Top

Verifying User Names and Expanding Mailing Lists

SMTP also allows verification of a user name and the expansion of a mailing list. This is done with the VRFY and EXPN commands, which have character string arguments. For the VRFY command, the string is a user name, and the response may include the full name of the user and must include the mailbox of the user. For the EXPN command the string identifies a mailing list; the multi-line response may include the full name of the users and must give the mailboxes on the mailing list.

"User name" is a fuzzy term and used purposely. If a host implements the VRFY or EXPN commands then at least local mailboxes must be recognized as "user names". If a host chooses to recognize other strings as "user names" that is allowed.

For some hosts the distinction between a mailing list and an alias for a single mailbox is not clear, since a common data structure may hold both types of entries, and it is possible to have mailing lists of one mailbox. If a request is made to verify a mailing list a positive response can be given if on receipt of a message so addressed it will be delivered to everyone on the list, otherwise an error should be reported (for example., "550 That is a mailing list, not a user"). If a request is made to expand a user name a positive response can be formed by returning a list containing one name, or an error can be reported (for example., "550 That is a user name, not a mailing list").

In the case of a multi-line reply (normal for EXPN) exactly one mailbox is specified on each line of the reply. In the case of an ambiguous request, for example, "VRFY Smith", where there are two Smith's the reply should be "553 User ambiguous".

These commands are not often used, but can be implemented with the Command method.

Back to Top

Service Extensions

SMTP has been extended to support additional features. These enhancements have been carefully designed to not disrupt the original protocol. The notion of a "Service Extension" has been defined as a general-purpose mechanism for allowing enhancements to the basic protocol. Collectively, these extensions are known as Extended-SMTP (ESMTP).

At the heart of the service extensions is a new login command. The original HELO command is replaced by the new EHLO command. The EHLO command differs from HELO by announcing to the mail server the desire to use service extensions. The server reports back to the client a list of supported service extensions with parameters.

The Login method will attempt server authorization using the EHLO command. Upon success, each advertised service extension is added to the Capabilities property. Service extensions are automatically used to maximize performance and accommodate the attributes of messages being sent. Following a successful Login, the using application can examine the Capabilities Property to see what extended features the server supports. You may override the use of a particular extension by removing it from the Capabilities Property.

Since service extensions are automatically used, it is generally not required to consider the server's extension list.

If the EHLO command fails, HELO is used instead.

The following service extensions are supported:

Service Extension

Description

SIZE

Allows a client to declare the size of a particular message to a server as a parameter to the MAIL FROM command, after which the server may indicate to the client that it is or is not willing to accept the message based on the declared message size. Also allows the server to declare the maximum message size it is willing to accept from a client in the SIZE response to the client's EHLO command.

PIPELINING

Allows a server to declare its ability to process multiple SMTP commands that are "pipelined" without synchronization (request / reply pairs are not synchronized in time). This can significantly reduce processing overhead.

8BITMIME

The server will accept messages with 8-bit bytes.

DSN

Allows a client to specify (a) that delivery status notifications (DSNs) should be generated, (b) if such notifications should return the contents of the message, and (c) additional information, to be returned with a DSN, that identifies the recipient(s) for which the DSN was issued and the transaction in which the original message was sent. DSNs are implemented using two optional parameters added to the RCPT command, and two optional parameters added to the MAIL command:

  • An optional parameter for the RCPT command, using the keyword "NOTIFY", specifies the conditions under which a delivery status notification should be generated.

  • An optional parameter for the RCPT command, using the keyword "ORCPT", specifies the "original" (sender-specified) recipient address,

  • An optional parameter for the MAIL command, using the keyword "RET", requests that DSNs containing an indication of delivery failure either return the entire contents of a message or only the message headers,

  • An optional parameter for the MAIL command, using the keyword "ENVID", specifies an identifier for this message transmission envelope, that is returned in any DSNs issued for this transmission.

The DSN method provides control of the DSN service extensions.

ENHANCEDSTATUSCODES

Allows the server to augment its responses with enhanced mail system status codes. These codes can then be used to provide more informative explanations of error conditions, especially in the context of the DSN (delivery status notification) format.

When active, the server prefaces the text part of most replies with status information in the form "class.subject.detail" as illustrated below. The collected status codes are listed in the following section.

C: MAIL FROM: <ned@ymir.claremont.edu>
S: 250 2.1.0 Originator <ned@ymir.claremont.edu> OK
C: RCPT TO: <mrose@dbc.mtview.ca.us>
S: 250 2.1.5 Recipient <mrose@dbc.mtview.ca.us> OK
C: RCPT TO: <nosuchuser@dbc.mtview.ca.us>
S: 550 5.1.1 Mailbox "nosuchuser" does not exist
C: RCPT TO: <remoteuser@isi.edu>
S: 551-5.7.1 Forwarding to remote hosts disabled

Refer to the Enhanced Status Codes topic for a list of codes.

Back to Top


Agent Control Example

This VB example shows how to set values in a Management Information Base (MIB) that will be used to automatically respond to any request received from an SNMP manager.

Private Sub Form_Load()

On Error GoTo OnError

Agent1.Mib.Load "C:\smi.mib" ' MIB file included with Dart's sample MIB Viewer application

Agent1.Mib.Load "C:\mib_ii.mib" ' MIB file included with Dart's sample MIB Viewer application

Agent1.Mib.Variables("sysContact").Value = "DartMan"

Agent1.Mib.Variables("udpInDatagrams").Value = 0

Agent1.Open

Text1.Text = Agent1.Mib.Variables("sysContact").Value

Text2.Text = Agent1.Mib.Variables("udpInDatagrams").Value

Exit Sub

OnError:

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Message Property Example (Agent Control, Manager Control)

Message Property Example (Agent Control/Manager Control)

For the Agent Control, this property is updated each time a message arrives and the Request event fires, as shown in the following VB example.

Private Sub Agent1_Request()

On Error GoTo OnError ' use intrinsic error handling

If Agent1.Message.Community <> "public" Then

'Ignore Message

Else

'Process the message

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

For the Manager Control, this property is updated each time a message arrives and the Response event or Trap event fires:

Private Sub Manager1_Response()

On Error GoTo OnError ' use intrinsic error handling

If Manager1.Message.Community <> "public" Then

'Ignore Message

Else

'Process the message

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

This object is also used for preparing a message prior to encoding and sending it with the Send method. The following Visual Basic code demonstrates how an agent can build a trap message and send it:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Agent1.Message.Reset

Agent1.Message.Type = snmpTrap1

Agent1.Message.Community = "public"

Agent1.Message.GenericTrap = snmpEnterpriseSpecific

Agent1.Message.SpecificTrap = 1

'A message will be sent to each Manager in the TrapManagers property.

Agent1.Send

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

This property can be set to an external SnmpMessage Object. One use for this would be to store messages that have been set and received as this code snippet demonstrates:

Dim NewMessage As New SnmpMessage

Dim OldMessage As SnmpMessage

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

'First store off old message for later.

Set OldMessage = Manager1.Message

Manager1.Message = NewMessage

'Set a 1 second Timeout to wait for the response

Manager1.Timeout = 1000

Manager1.Send

'Set message again and now NewMessage contains the response.

Manager1.Message = OldMessage

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Send Method Example (Agent/Manager Control)

Send Method Example (Agent Control/Manager Control)

This VB example shows how to set values in the Message and related properties and then encode and send the message using an Agent Control.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Agent1.Message.Reset

'Set the Properties of Message here

Agent1.Message.Type = snmpTrap1

'TrapManagers is used for addressing Trap messages

Agent1.TrapManagers.Add "manager.dart.com"

Agent1.Send

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

With a Manager Control, a non-zero Timeout causes this method to block (the Blocked property returns True) until the agent responds or a timeout occurs. Set the contents of the Message, AgentName, and AgentPort properties and send a message, as shown:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Variable As SnmpVariable

Variable.Oid = "1.3.6.1.2.1.1.1.0" 'sysDescr

Manager1.Message.Reset

Manager1.Message.Type = snmpGet1

Manager1.Message.Variables.Add Variable

' AgentPort defaults to 162

Manager1.AgentName = "agent.dart.com"

Manager1.Send

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


ManagerName Property Example (Agent Control)

Private Sub Agent1_Request()

On Error GoTo OnError ' use intrinsic error handling

' add the source address to a list of managers

List1.AddItem Agent1.ManagerName

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


ManagerPort Property Example (Agent Control)

Private Sub Agent1_Request()

On Error GoTo OnError ' use intrinsic error handling

MsgBox "Request received from port " & Agent1.ManagerPort

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Mib Property Example (Agent Control)

This VB example shows how the application can save this information for later use by assigning it to a new object.

Dim OldMib As SnmpMib

Private Sub Command1_Click()

' Increases the usage count of Agent1.Mib

Set OldMib = Agent1.Mib

End Sub

You also can set this property as shown below:

Dim NewMib As New SnmpMib

Private Sub Command1_Click()

' Increases the usage count of NewMib and releases Agent1.Mib

Agent1.Mib = NewMib

End Sub


Request Event Example (Agent Control)

This VB example demonstrates handling a request within this event:

Private Sub Agent1_Request()

On Error GoTo OnError ' use intrinsic error handling

If Agent1.Message.Community = "public" Then

Select Case Agent1.Message.Type

Case snmpGet1, snmpGet2

' Get the appropriate values here.

Case snmpSet1, snmpSet2

' Set the appropriate values here.

Case snmpGetNext1, snmpGetNext2

' Get the appropriate Next value here.

Case snmpGetBulk2

' Get the appropriate Next values here.

End Select

' Bitwise And to mask out version 1 or version 2 packets.

' Set the response version appropriately.

If (Agent1.Message.Type And snmpVersion1) Then

Agent1.Message.Type = snmpResponse1

Else

Agent1.Message.Type = snmpResponse2

End If

Agent1.Send

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


TrapManagers Property Example (Agent Control)

This VB example shows how to add managers to the TrapManagers property.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Add a manager with the default port of 162

Agent1.TrapManagers.Add "manager.dart.com"

' Add a manager with a port of 5000

Agent1.TrapManagers.Add "manager2.dart.com:5000"

Text1.Text = Agent1.TrapManagers.All ' display managers

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Certificate Object Example

This VB example demonstrates checking for a certificate that supports server authentication.

Private Function IsUsedForServerAuth(Certificate As Certificate) As Boolean

On Error GoTo OnError ' use intrinsic error handling

If Certificate.KeyUsage(usageServerAuthentication) Then

IsUsedForServerAuth = True

Else

IsUsedForServerAuth = False

End If

Exit Function

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Function


IssuedBy Property Example (Certificate Object)

Refer to CertificateStore Object Example for an example of how to use the IssuedBy property.


IssuedTo Property Example (Certificate Object)

Refer to CertificateStore Object Example for an example of how to use the IssuedTo property.


KeyName Property Example (Certificate Object)

Refer to CertificateStore Object Example for an example of how to use the KeyName property.


KeySize Property Example (Certificate Object)

Refer to CertificateStore Object Example for an example of how to use the KeySize property.


KeyUsage Property Example (Certificate Object)

Private Function IsUsedForServerAuth(Certificate As Certificate) As Boolean

If Certificate.KeyUsage(usageServerAuthentication) Then

IsUsedForServerAuth = True

Else

IsUsedForServerAuth = False

End If

End Function


SerialNumber Property Example (Certificate Object)

Refer to CertificateStore Object Example for an example of how to use the SerialNumber property.


CertificateList Control Example

This VB example demonstrates setting up the CertificateList Control.

Private Sub Form_Load()

On Error GoTo OnError ' use intrinsic error handling

' Set the certificate store to "MY" store in the LocalMachine.

CertificateList1.StoreName = "MY"

CertificateList1.StoreLocation = locationLocalMachine

' Display the certificates in the listview.

CertificateList1.Refresh

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Count Property Example (Certificates Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Store As New CertificateStore

' Get the certificates in "MY" certificate store located in the

' Local Machine registry key.

Store.Name = "MY"

Store.Location = locationLocalMachine

Store.Refresh

MsgBox "There are " & Store.Certificates.Count & " certificates."

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Item Method Example (Certificates Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Store As New CertificateStore

' Get the certificates in "MY" certificate store located in the

' Local Machine registry key.

Store.Name = "MY"

Store.Location = locationLocalMachine

Store.Refresh

Dim Cert As Certificate

Set Cert = Store.Certificates.Item(1) ' explicit use of Item method

Set Cert = Store.Certificates(1) ' implicit use of Item method

MsgBox "Certificate " & Cert.SerialNumber & " issued by " & Cert.IssuedBy

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


CertificateStore Object Example

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Store As New CertificateStore

Dim Certificate As Certificate

' Get the certificates in "MY" certificate store located in the

' Local Machine registry key.

Store.Name = "MY"

Store.Location = locationLocalMachine

' Must use Refresh to populate Store.Certificates

Store.Refresh

MsgBox "There are " & Store.Certificates.Count & " certificates."

For Each Certificate In Store.Certificates

MsgBox "Owner is " & Certificate.IssuedTo _

& vbCrLf & "Issuer is " & Certificate.IssuedBy _

& vbCrLf & "Certificate version is " & Certificate.Version _

& vbCrLf & "Valid From " & Certificate.ValidFrom & " to " & Certificate.ValidTo _

& vbCrLf & "Serial Number is " & Certificate.SerialNumber _

& vbCrLf & "KeyName is " & Certificate.KeyName _

& vbCrLf & "KeySize is " & Certificate.KeySize

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

The Find method can be used to find a given certificate:

Private Sub Command2_Click()

Dim Store As New CertificateStore

'Get the desired certificate

SecureTcp1.Certificate = Store.Find("ROOT", locationLocalMachine, g_SavedIssuedBy, g_SavedSerialNumber)

End Sub


Find Method Example (CertificateStore Object)

Private Sub Command_Click()

On Error GoTo OnError ' use intrinsic error handling

'Use documents in the C:\WebPub directory

WebServer1.RootDirectory = "C:\WebPub"

'Use CertificateStore to look-up security certificate desired

Dim Store As New CertificateStore

'Get the specified certificate

WebServer1.Certificate = Store.Find("ROOT", locationLocalMachine, g_SavedIssuedBy, g_SavedSerialNumber)

' Listen for secure connections on default port 443

' Listen for non-secure connections on default port 80

' Start processing requests&ldots;

WebServer1.Start

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Children Object Example (Secure Tool)

Children Object Example (SSL Tool)

Dim Child As SecureTcp

For Each Child In SecureServer1.Children

' Send warning to all children and shut down

Child.Send "Dart Server shutting down now"

Child.Close

Next

The number of objects in a collection is returned by:

Count = SecureServer1.Children.Count

Therefore, the above iteration could also be performed as:

Dim I As Integer

For I = 1 To SecureServer1.Children.Count

SecureServer1.Children(I).Send "Dart Server shutting down now"

SecureServer1.Children(I).Close

Next


Children Object Example (SSL Tool)

Children Object Example (Server Tool)

Dim Child As Tcp

For Each Child In Server1.Children

' Send warning to all children and shut down

Child.Send "Dart Server shutting down now"

Child.Close

Next

The number of objects in a collection is returned by:

Count = Server1.Children.Count

Therefore, the above iteration could also be performed as:

Dim I As Integer

For I = 1 To Server1.Children.Count

Server1.Children(I).Send "Dart Server shutting down now"

Server1.Children(I).Close

Next


ColumnCount Property Example (SnmpTable Object)

ColumnCount Property Example

Private Function GetColumnCount(ByVal TableOid As String) As Long

Dim Row As SnmpTableRow

' Get a row from the local MIB

Set Row = Mib.Variables.GetTableRow(TableOid & ".1")

If Not Row Is Nothing Then

GetColumnCount = Row.ColumnCount

Else

GetColumnCount = 0

End If

End Function


All Property Example (Cookie Object)

Dim Cookie As New Cookie

Cookie.All = "Test1=Sub1=""Val1""&Sub2=""Val2"";domain=""www.dart.com"""

' now the cookie has all the value and subvalues from the string


Domain Property Example (Cookie Object)

Public Sub UpdateResponse(Resp As Response)

On Error GoTo OnError ' use intrinsic error handling

Dim Cookie As New Cookie

Cookie.Name = "Cookie1"

Cookie.Value = "Test cookie"

' Send the cookie back with all document requests in

' the domain www.dart.com

Cookie.Domain = "www.dart.com"

Response.Cookies.Add Cookie

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Cookie Object Example

If the cookie has sub-values, there are two ways of accessing the cookie.

Given the following cookie:

Test1 = Sub1 = "Val1" & Sub2 = "Val2"; domain = "www.dart.com"; path = /

To show the sub-values individually:

Dim Var As HttpVariable

For Each Var In Session.Cookies("Test1").SubValues

List1.AddItem Var.Name + " " + Var.Value

Next

The previous code will display:

Sub1 Val1

Sub2 Val2

Optionally you could write the code like this:

List1.AddItem Session.Cookies("Test1").Value

The previous code will display:

Sub1 = "Val1" & Sub2 = "Val2"

The following code demonstrates accessing a specific sub-value:

List1.AddItem Session.Cookies("Test1")("Sub2")

The previous code will display:

Val2


Expires Property Example (Cookie Object)

Private Sub WebServer1_Get(ByVal Session As DartWebServer.ISession, ByVal Request As DartWebServer.IRequest, ByVal Response As DartWebServer.IResponse)

On Error GoTo OnError ' use intrinsic error handling

Dim Cookie As New Cookie

Cookie.Name = "Cookie1"

Cookie.Value = "Test cookie"

'Expire in 7 days.

Cookie.Expires = Now + 7

Response.Cookies.Add Cookie

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Name Property Example (Cookie Object)

Public Sub ListCookies(Request As Request)

On Error GoTo OnError ' use intrinsic error handling

Dim Cookie As Cookie

' put the name of each cookie in the request in a list box

For Each Cookie In Request.Cookies

List1.AddItem "The name of the cookie is " + Cookie.Name

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Path Property Example (Cookie Object)

Given the following cookie:

Cookie1 = "Value"; Path = /testpath

The following document requests would send the cookie along with the request:

/testpath/page.html

/testpath/subdir/page.html

This VB example demonstrates this property.

Private Sub UpdateCookiePath(Response As Response)

On Error GoTo OnError ' use intrinsic error handling

Dim Cookie As New Cookie

Cookie.Name = "Cookie1"

Cookie.Value = "Test cookie"

'Send the cookie back with all document requests that

'begin with /testdir.

Cookie.Path = "/testdir"

Response.Cookies.Add Cookie

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Secure Property Example (Cookie Object)

Private Sub UpdateCookieSecure(Response As Response)

On Error GoTo OnError ' use intrinsic error handling

Dim Cookie As New Cookie

Cookie.Name = "Cookie1"

Cookie.Value = "Test cookie"

'Ensure that when the cookie is sent back to the server

'from the browser it is over a secure connection.

Cookie.Secure = True

Response.Cookies.Add Cookie

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


SubValues Property Example (Cookie Object)

Private Sub ListSubValues(Request As Request)

On Error GoTo OnError ' use intrinsic error handling

Dim Cookie As Cookie

Dim Variable As Cookie

For Each Cookie In Request.Cookies

If Cookie.SubValues.Count > 0 Then

List1.AddItem Cookie.Name + " subvalues:"

For Each Variable In Cookie.SubValues

List1.AddItem Varaible.Name + " = " + Variable.Value

Next

Else

List1.AddItem Cookie.Name + " = " + Cookie.Value

End If

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Value Property Example (Cookie Object)

Private Sub ListCookies(Request As Request)

On Error GoTo OnError ' use intrinsic error handling

Dim Cookie As Cookie

For Each Cookie In Request.Cookies

List1.AddItem Cookie.Name + " = " + Cookie.Value

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Add Method Example (Cookies Object)

Private Sub Add(Response As Response)

On Error GoTo OnError ' use intrinsic error handling

Dim Cookie1 As New Cookie

Cookie1.Name = "Cookie1"

Cookie1.Value = "Value1"

Response.Cookies.Add Cookie1

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Item Method Example (Cookies Object)

Dim Cookie1 As Cookie

' first access cookie by Index as a Long value

Set Cookie1 = Request.Cookies.Item(1) ' explicit use of Item method

Set Cookie1 = Request.Cookies(1) ' implicit use of Item method

' now access cookie by String value

Set Cookie1 = Request.Cookies.Item("Dart") ' explicit use of Item method

Set Cookie1 = Request.Cookies("Dart") ' implicit use of Item method


Remove Method Example (Cookies Object)

Private Sub RemoveCookie(Cookies1 As Cookies, Name As String)

On Error GoTo OnError ' use intrinsic error handling

Dim Cookie1 As Cookie

' remove each cookie in the collection with the passed name

For Each Cookie1 In Cookies1

If Cookie1.Name = Name Then

Cookies1.Remove Name

End If

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Accept Event Example (Daemon Control)

Private Sub Daemon1_Accept()

On Error GoTo OnError ' use intrinsic error handling

' create a new TCP Control and assign the Socket to it

Dim Tcp1 As Tcp

' myclass supports event notification for Tcp operation

Set Tcp1 = New myclass

Tcp1.Socket = Daemon1.Accept

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Accept Method Example (Daemon Control)

When Timeout is 0, and the Accept event fires, the Accept method accesses the new connection for assignment to a TCP Control (-1 is returned if no socket is available to be accepted).

Private Sub Daemon1_Accept()

On Error GoTo OnError ' use intrinsic error handling

' create a new TCP Control and assign the Socket to it

Dim Tcp1 As Tcp

' myclass supports event notification for Tcp operation

Set Tcp1 = New myclass

Tcp1.Socket = Daemon1.Accept

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

When Timeout is greater than 0, the Accept method can also be used:

Private Sub Daemon1_Accept()

On Error GoTo OnError ' use intrinsic error handling

Daemon1.Timeout = 30000 ' block for 30 seconds waiting for the connection

Daemon1.Listen 7 ' listen on port 7

Tcp1.Socket = Daemon1.Accept ' block until a connection can be accepted

Exit Sub

OnError: ' Any error jumps here

' Don't use MsgBox because that interrupts event notification

' Pops out with a ptTimeout error if no connection came in

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Daemon Control Example

' listen on port 7 for connections

Daemon1.Listen 7

' since no Error condition is reported, we know we succeeded

Private Sub Daemon1_Accept()

On Error GoTo OnError ' use intrinsic error handling

' create a new TCP Control and assign the Socket to it

Dim WithEvents Tcp1 As Tcp

' myclass supports event notification for Tcp operation

Set Tcp1 = New myclass

' you'll need to save the Tcp1 reference someplace&ldots;

Tcp1.Socket = Daemon1.Accept

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Listen Method Example (Daemon Control)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' listen on the echo server port

Daemon1.Listen 7

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Clear Method Example (DartStream Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Stream1.Clear

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


DeleteOnDestroy Property Example (DartStream Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

'Destroys the file and DartStream Object.

Stream1.DeleteOnDestroy = True

Set Stream1 = Nothing

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


DartStream Object Example

Dim Stream As DartStream

Private Sub DumpToFile(FileName As String)

On Error GoTo OnError ' use intrinsic error handling

'Create or Replace any file of the same name.

Stream.FileMode = createAlways

'Dump all contents of the Stream object to a file.

Stream.FileName = FileName

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


FileName Property Example (DartStream Objectl)

FileName Property Example (DartStream Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

MsgBox "The specified name was " + Stream1.FileName

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Position Property Example (DartStream Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

MsgBox "Current position is " & Stream1.Position

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Read Method Example (DartStream Object)

Private Sub ReadAll(S As String)

On Error GoTo OnError ' use intrinsic error handling

'Move the position to the beginning

Stream1.Position = 0

Stream1.Read S

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


ReadBytes Method Example (DartStream Object)

Private Function ReadAll(Stream1 As DartStream) As Byte

'Move the position to the beginning

Stream1.Position = 0

ReadAll = Stream1.ReadBytes

End Function


ReadString Method Example (DartStream Object)

Private Function ReadAll(Stream1 As DartStream) As String

'Move the position to the beginning

Stream1.Position = 0

ReadAll = Stream1.ReadString

End Function


Size Property Example (DartStream Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

MsgBox "Current Size of the Stream is " & Stream1.Size

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Write Method Example (DartStream Object)

Private Sub WriteData(S As String)

On Error GoTo OnError ' use intrinsic error handling

Stream1.Write S

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Add Method Example (DartStreams Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Stream As New DartStream

Dim Streams As New DartStreams

Streams.Add Stream

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Item Method Example (DartStreams Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Stream As DartStream

Set Stream = Streams.Index(2) ' explicit use of Item method

'or

Set Stream = Streams(2) ' implicit use of Item method

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Addresses Property Example (DNS Control)

This VB example displays a DNS address in a message box.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dns1.ServerName = "Dns1.nameserver.com"

Dns1.GetAddress "dart.com"

MsgBox "Address for Dns1.servername.com: " & Dns1.Addresses(1)

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


DNS Control Example

This VB example determines the mail server for an email address. This eliminates intermediate message relays and allows the message to be sent directly to the mail server.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' find the mail server for an address

Dns1.ServerName = "Dns1.nameserver.com"

Dns1.GetMailServer "Test@Dart.com"

' use the result of the query as the SMTP Server

Smtp1.QuickSend "Test@Dart.com", "Dave@Test.com", "Testing", _

"More Testing", "", Dns1.Names(1)

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


GetAddress Method Example (DNS Control)

This VB example shows how to display the name for an associated IP address as returned by a DNS server.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dns1.ServerName = "Dns1.nameserver.com"

Dns1.GetAddress "dart.com"

' show the result to the user

MsgBox "Address of ftp.dart.com: " & Dns1.Addresses(1)

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


GetMailServer Method Example (DNS Control)

This VB example shows how to display the mail server name for an email address and a domain address.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim i As Integer

Dns1.ServerName = "Dns1.nameserver.com"

' request for an email address

Dns1.GetMailServer "test@dart.com"

' show the result to the user

For i = 1 To Dns1.Names.Count

MsgBox "Name: " & Dns1.Names(i) & vbCrLf & _

"Address: " & Dns1.Addresses(i)

Next i

' try one by a domain also

Dns1.GetMailServer "dart.com"

' show the result to the user

For i = 1 To Dns1.Names.Count

MsgBox "Name: " & Dns1.Names(i) & vbCrLf & _

"Address: " & Dns1.Addresses(i)

Next i

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


GetName Method Example (DNS Control)

This VB example shows how to resolve a dot address to a host name.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dns1.ServerName = "Dns1.nameserver.com"

Dns1.GetName "xxx.xxx.xxx.xxx"

' show the result to the user

MsgBox "Name 63.66.1.169: " & Dns1.Names(1)

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Id Property Example (DNS Control)

This VB example displays the mail server and request Id when a user clicks a button.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dns1.Timeout = 30000

Dns1.Id = 4567

Dns1.ServerName = "Dns1.nameserver.com"

Dns1.GetMailServer "test@dart.com"

' show the result to the user

MsgBox "Primary Mail Server returned for request id" _

& Dns1.Id & " " & Dns1.Names(1)

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Names Property Example (DNS Control)

This VB example shows how to display the name for an associated IP address as returned by a DNS server.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dns1.ServerName = "Dns1.nameserver.com"

Dns1.GetName "xxx.xxx.xxx.xxx"

MsgBox "Name xxx.xxx.xxx.xxx: " & Dns1.Names(1)

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Response Event Example (DNS Control)

This VB example shows how to verify a response after resolving a dot address to a host name.

Private Sub Dns1_Response()

On Error GoTo OnError ' use intrinsic error handling

' we can now do something with the response

' for this example just report that we got a

' response and the results.

Label1.Caption = Dns1.Id

Label2.Caption = Dns1.Addresses(1)

Label3.Caption = "OK"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


ServerPort Property Example (DNS Control)

This VB example shows shows how you can use the ServerPort property.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dns1.ServerName = "Dns1.nameserver.com"

Dns1.ServerPort = 1052 ' specify a non-standard port

Dns1.GetName "xxx.xxx.xxx.xxx"

MsgBox "Name xxx.xxx.xxx.xxx: " & Dns1.Names(1)

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Help Method Example (FTP Control)

This VB example shows how to login and then display help information for a command.

Private Sub Command1_Click()

On Error GoTo OnError

' Login as anonymous

Ftp1.Login "ftp.dart.com"

If Ftp1.State = tcpConnected Then MsgBox "Connected"

Exit Sub

OnError:

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Private Sub Command2_Click()

Dim HelpResult As String ' local scope allowed because Timeout > 0

Ftp1.Timeout = 1000

' get help on the SITE command

Ftp1.Help HelpResult, "SITE"

Text1.Text = HelpResult ' show to user

End Sub


Listing Property Example (FTP Control)

Contents will be updated each time the List or NameList method is used to request listing information. The user can save this information for later use by assigning it to a new object, as shown in the following VB example.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Ftp1.Timeout = 1000

Ftp1.List "*.txt" ' all text files are requested

Dim TxtListing As ListEntries

Set TxtListing = Ftp1.Listing ' increased usage count keeps object in memory

Ftp1.List "*.exe" ' all executable files are requested

Dim ExeListing As ListEntries

Set ExeListing = Ftp1.Listing ' increased usage count keeps object in memory

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

This property can also be set, as shown in the following VB example.

Dim le1 As New ListEntries

Dim le2 As New ListEntries

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Ftp1.Timeout = 1000

Ftp1.Listing = le1

' get a listing from the current directory

Ftp1.List

Ftp1.Listing = le2

' get a listing from the parent directory

Ftp1.List "../"

' le1 and le2 now contain listings from 2 different directories

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


MGet Method Example (FTP Control)

This VB example demonstrates retrieving all files in the current server directory.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

'Retrieve all files in the current server directory to the

'current local directory.

Ftp1.MGet

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

This VB example demonstrates retrieving all files based on a wildcard.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

'Get all files, from the current server directory,

'that end with .txt and put them in a local directory

'called C:\TextFiles

Ftp1.MGet "*.txt", "C:\TextFiles"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

This VB example demonstrates retrieving an entire directory tree from the server:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Get the entire Test directory, subdirectories included,

' from the server and put it in the C:\NewFolder directory.

Ftp1.MGet "Test/*", "C:\NewFolder"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


MPut Method Example (FTP Control)

This VB example demonstrates storing all files in the current directory.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

'Store all files in the current directory to the current server directory

Ftp1.MPut

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

This VB example demonstrates storing all files based on a wildcard:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

'Store all files from the current directory that end with .txt ' and put them in a server directory called ~/TextFiles

Ftp1.MPut "*.txt", "~/TextFiles"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

This VB example demonstrates storing an entire directory tree on the server.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Store the entire Test directory, subdirectories included,

' on the server and put it in the ~/NewFolder directory

Ftp1.MPut "C:\Test\*", "~/NewFolder"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Put Method Example (Ftp Control)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim FileBuf As String ' local scope allowed because Timeout > 0

' Login to the user account and store File.txt

Ftp1.Put "ftp://user:password@ftp.dart.com/users/user/File.txt"

' Login as anonymous and send the contents of FileBuf to File.txt

Ftp1.Put "ftp.dart.com/users/user/File.txt", FileBuf

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Store Method Example (Ftp Control)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Ftp1.Timeout = 1000

' Store a binary file on the server

Ftp1.Type = ftpImage

Ftp1.Store "TheFile.exe"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Error Event Example (FtpServer Control)

This VB example shows some sample processing.

Private Sub FtpServer1_Error(ByVal Session As DartFtpServerCtl.ISession, ByVal Number As DartFtpServerCtl.ErrorConstants, ByVal Description As String)

On Error GoTo OnError ' use intrinsic error handling

AddLogEntry "ERROR " + CStr(Number) + " " + Description

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


FtpServer Control Example

This VB example demonstrates how to start the server with one line of code.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

'Start Ftp File System at C:\FtpRoot\

'Listen on port 21

FtpServer1.Start "C:\FtpRoot"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

This VB example demonstrates how to do basic authentication.

Private Sub FtpServer1_Login(ByVal Request As DartFtpServerCtl.IRequest, ByVal Response As DartFtpServerCtl.IResponse)

On Error GoTo OnError ' use intrinsic error handling

' Only allow a user to login in if their username is test and their password is secret.

If (Request.Session.User.Name = "test") And (Request.Session.User.Password = "secret") Then

' Its ok we can let it through.

Else

' This user does not have valid rights to login.

Request.Session.User = Nothing

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Setting up a fully functioning stand alone FTP server that accepts any user.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

FtpServer1.Start "C:\FtpRoot\"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

FtpServer1.Stop

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Providing some authentication support to allow only user admin with password secret.

Private Sub FtpServer1_Login(Request As Request, Response As Response)

On Error GoTo OnError ' use intrinsic error handling

If (Request.Session.User.Name = "admin") And _

(Request.Session.User.Password = "secret") Then

' Do initial login stuff here. Example is to

'move them into a home directory.

Request.Session.User.CurrentPath = "\Admin\"

Else

' Not a valid user do not allow them to log in

Set Request.Session.User = Nothing

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Providing a custom authentication routine. User must send the FOO command with a parameter of admin and the BAR command with a parameter of secret.

Private Sub FtpServer1_SessionInit( Session As Session)

On Error GoTo OnError ' use intrinsic error handling

'Client has connected initialize vars

Session.Variables("FOO") = ""

Session.Variables("BAR") = ""

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Private Sub FtpServer1_Command(Command As String, Request As Request, Response As Response)

On Error GoTo OnError ' use intrinsic error handling

If (Command = "FOO") Then

Request.Session.Variables("FOO") = Request.Parameters(1)

Response.Status = 331

Response.StatusText = "BAR required for FOO " + _

Request.Parameters(1)

End If

If (Command = "BAR") Then

Dim Foo, Bar As String

Request.Session.Variables("BAR") = Request.Parameters(1)

Foo = Request.Session.Variables("FOO")

Bar = Request.Session.Variables("BAR")

If (Foo = "admin") And (Bar = "secret) Then

Dim Usr As New User

Usr.Name = Foo

Set Request.Session.User = Usr

Usr.CurrentDirectory = "\admin\"

Response.Status = 230

Response.StatusText = "Yeah your logged in."

Else

Response.Status = 530

Response.StatusText = "Authentication failed."

End If

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

The following protocol examples demonstrate the above code:

C - Client S - Server

C: (Connects)

S: 220

C: FOO admin

S: 331 BAR required for FOO admin

C: BAR secret

S: 230 Yeah your logged in.

another example:

C - Client S - Server

C: (Connects)

S: 220

C: FOO joe

S: 331 BAR required for FOO joe

C: BAR secret

S: 530 Authentication failed.

Rejecting file transfers based on a user. Do not allow user joe to transfer any files.

Private Sub FtpServer1_Retrieve(Request As Request, Response As Response)

On Error GoTo OnError ' use intrinsic error handling

If (Request.Session.User.Name = "joe") Then

Set Response.Data = Nothing

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Private Sub FtpServer1_Store(Request As Request, Response As Response)

On Error GoTo OnError ' use intrinsic error handling

If (Request.Session.User.Name = "joe") Then

Set Response.Data = Nothing

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


MaxIdleTime Property Example (FtpServer Control)

' Set to kill a session after 35 minutes of inactivity

FtpServer1.MaxIdleTime = 35


SessionEnd Event Example (FtpServer Control)

This VB example demonstrates preventing the session object from being deleted:

Private Sub FtpServer1_SessionEnd(ByVal Session As DartFtpServerCtl.ISession)

On Error GoTo OnError ' use intrinsic error handling

' Reset the inactivity time to 0 so the object will not be destroyed by a timeout

Session.IdleTime = 0

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


SessionInit Event Example (FtpServer Control)

This VB example demonstrates the a use of this event to initialize variables for the session.

Private Sub FtpServer1_SessionInit(ByVal Session As DartFtpServerCtl.ISession)

On Error GoTo OnError ' use intrinsic error handling

'Add a variable by the name of Var1 to the sessions Variables

'collection. You may also want to log this even to a file here.

Session.Variables("Var1") = "This a default variable."

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Name Property Example (FtpVariable Object)

Private Sub FtpServer1_Get(ByVal Session As DartFtpServer.ISession, ByVal Request As DartFtpServer.IRequest, ByVal Response As DartFtpServer.IResponse)

On Error GoTo OnError ' use intrinsic error handling

Dim Variable As FtpVariable

List1.AddItem "Variables defined for the session:"

For Each Variable In Session.Variables

' only add variable that don't start with "Temp"

If Variable.Name <> "Temp" Then

List1.AddItem Variable.Name

End If

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Value Property Example (FtpVariable Object)

This VB example demonstrates setting this property to a value.

Dim Variable As New FtpVariable

Variable.Name = "Username"

Variable.Value = "JohnDoe"

This VB example demonstrates setting this property to a Cookie Object:

Dim Cookie As New Cookie

Dim Variable As New FtpVariable

Variable.Name = "Username"

Variable.Value = Cookie


Add Method Example (FtpVariables Object)

Private Sub FtpServer1_SessionInit(ByVal Session As DartFtpServerCtl.ISession)

On Error GoTo OnError ' use intrinsic error handling

Dim Var As New FtpVariable

' Add a default variable to the session.

Var.Name = "DefaultVar"

Var.Value = "DefaultValue"

Session.Variables.Add Var

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Item Property Example (FtpVariables Object)

This VB example demonstrates setting an FtpVariables value.

Dim Variables As New FtpVariables

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Sets the variable named "Var1" to the string value

' of "Test Value 1" or it will create a variable

' name "Var1" and set it string value "Test Value 1" if

' the variable does not exist.

Variables("Var1") = "Test Value 1"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

This VB example demonstrates reading an FtpVariables value.

Dim Variables As New FtpVariables

Private Sub Command1_Click()

On Error GoTo OnError

Dim Value As Variant

' Gets the value of the Variable "Var1"

Value = Variables("Var1")

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Remove Method Example (FtpVariables Object)

Private Sub FtpServer1_Get(ByVal Session As DartFtpServer.ISession, ByVal Request As DartFtpServer.IRequest, ByVal Response As DartFtpServer.IResponse)

On Error GoTo OnError ' use intrinsic error handling

Dim Variable1 As FtpVariable

' removes the first variable

Set Variable1 = Session.Variables.Remove(1)

' remove the variable name "Temp"

Set Variable1 = Session.Variables.Remove("Temp")

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


GetNext Method Example (SnmpVariables Object)

Private Sub Form_Load()

Dim Filenames As New DartStrings

Dim Var As SnmpVariable

Dim Varnext As SnmpVariable

Filenames.Delimiter = Space(1)

Filenames.Add "mib_ii.mib smi.mib"

CompileMib Filenames

Filenames.Clear

RefreshMibs

Var=Mib.Variables.GetNext("1.3.6.1.2.1.1.4")

Varnext=Mib.Variables.GetNext(Var.Name)

End Sub


GetTable Method Example (SnmpVariables Object)

GetTable Method Example

Private Sub Command1_Click()

Dim Mib As New SnmpMib

Dim var As New SnmpVariable

Dim v As SnmpVariable

Dim Table As SnmpTable

Dim strings As New DartStrings

Dim Row As SnmpTableRow

strings.Add (App.Path & "\" & "traps.mib")

strings.Add (App.Path & "\" & "mib_ii.mib")

strings.Add (App.Path & "\" & "smi.mib")

Dim oid As String

Mib.Compile strings

Set Vars = New SnmpVariables

'Getting the ifTable size

oid = Mib.Variables.GetOIDFromName("ifTable")

oid = Mib.Variables.GetNext(oid).oid

Set Table = Mib.Variables.GetTable(oid)

'after ifentry, the row object-type, comes the variables

If Not Table Is Nothing Then

var.oid = oid & ".0"

var.Repeat = True

Manager1.Message.Reset

Manager1.Message.Variables.Add var

Manager1.Message.MaxRepetition = Table.ColumnCount

'Get a row from all agents on the network

Manager1.AgentName = "255.255.255.255"

Manager1.Message.Type = snmpGetBulk2

Manager1.Open

Manager1.Send

Set var = Nothing

'Getting the ifTable

Set Table = Vars.GetTable(oid)

Debug.Print vbCrLf & "count " & Table.RowCount

For Each Row In Table

Debug.Print " row: " & Row.RowIndex & vbCrLf

For Each var In Row

Debug.Print var.Name & " oid: " & var.oid & vbCrLf

Next

Next

Debug.Print "finalrow: " & vbCrLf

Set Row = Vars.GetTableRow("1.3.6.1.2.1.2.2.1.11")

For Each var In Row

Debug.Print var.Name & " oid: " & var.oid & vbCrLf

Next

End If

End Sub


GetTableRow Method Example (SnmpVariables Object)

GetTableRow Method Example

Private Function GetColumnCount(ByVal TableOid As String) As Long

Dim Row As SnmpTableRow

' Get a row from the local MIB

Set Row = Mib.Variables.GetTableRow(TableOid & ".1")

If Not Row Is Nothing Then

GetColumnCount = Row.ColumnCount

Else

GetColumnCount = 0

End If

End Function


HeaderFields Object Example

This VB example displays all the "Received" headers from a message, then the Subject.

Private Sub Command1_Click()

Dim Hdr As New HeaderFields, Begin As Long

Hdr.Add msgFrom, "developer@dart.com"

Hdr.Add msgReceived, "from x@y by a@b with z id abc"

Hdr.Add msgReceived, "from xx@dart.com by a22 with grasp id 33a1"

Hdr.Add msgReceived, "from frd@dart.com by kahuna with z id k32"

Hdr.Add msgFrom, "sales@dart.com"

Hdr.Add msgSubject, "time marches on"

Begin = 0 ' start search at beginning

While Hdr.Find(msgReceived, , Begin) <> "" ' find index of next "Received"

MsgBox "Found: " & Hdr(Begin) ' use positional lookup

Wend

MsgBox (Hdr.Find(msgSubject)) ' show the message Subject line

End Sub


Find Method Example (HeaderFields Object)

Refer to HeaderFields Object Example for an example of how to use the Find method.


Item Method Example (HeaderFields Object)

Private Sub Command1_Click()

Dim Msg As New Message, S As String

Msg.Load "C:\NewTest.msg"

S = Msg.Header.Item(1) ' explicit use of Item method

Text1.Text = S

End Sub

Alternatively, you could use the Item method implicitly:

S = Msg.Header(1) ' implicit use of Item method


Cookies Property Example (Web Control)

This VB example shows how to use the Cookies property to allow user-defined cookies to be sent in a request.

Private Sub Command1_Click()

On Error GoTo OnError

Command1.Enabled = False

Http1.Cookies = False

Dim Header As New DartStrings

Header.Delimiter = vbCrLf

Header.Add "Cookie: This is my Cookie"

Dim Data As String

Http1.Url = "localhost:8080"

Http1.GetEx Header, Data

GoTo Done

OnError:

Debug.Print "ERROR #" + CStr(Err.Number) + ": " + Err.Description

Done:

Command1.Enabled = True

End Sub


HTTP Control Example

Web Control Example

This VB example retrieves a web page from a server and displays the HTML code for that page in a text box.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Get a web page from a web server

Dim Orderform As String

Http1.Timeout = 20000 'give it 20 seconds to complete

Http1.Url = "http://www.dart.com/"

Http1.Get Orderform

Text1.Text = Orderform 'The HTML code for the web site appears in the text box

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Get Method Example (Web Control)

Private Sub Command1_Click()

On Error GoTo OnError

' Get a web page from a secure web server

Dim Orderform As String

' Add DartStrings as a Reference in your VB project using

' Dart Tcp, Daemon, Udp Controls' from the 'Available References' list

Dim Headers As New DartStrings

Http1.Timeout = 60000 'give it up to 60 seconds

Http1.Url = "https://www.amazon.com/order/web1.html"

Http1.Get Orderform, Headers

' making it here with no errors means the page is in Orderform

' with the returned headers in Headers

Exit Sub

OnError:

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


GetEx Method Example (Web Control)

Private Sub Command1_Click()

On Error GoTo OnError

' Get a web page from a secure web server

Dim Orderform As String

Dim RequestHeaders As New DartStrings

Dim ResponseHeaders As New DartStrings

' we want to set a custom header field to go with the request

RequestHeaders.Add "X-MyContent: SessionID=12345"

Http1.Timeout = 60000 'give it up to 60 seconds

Http1.Url = "https://www.amazon.com/order/web1.html"

' get the page into a string

Http1.GetEx RequestHeaders, Orderform, ResponseHeaders

' get the same page and store to a file

Orderform = "c:\temp\OrderForm.html"

Http1.GetEx RequestHeaders, Orderform, ResponseHeaders

Exit Sub

OnError:

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Head Method Example (Web Control)

This VB example retrieves header information from a web page and displays this information in a text box.

Private Sub Command1_Click()

On Error Resume Next

' Get the headers from a web page on a secure web server

' Add DartStrings as a Reference in your VB project

' using Dart Tcp, Daemon, Udp Controls' from the 'Available References' list

Dim Headers As New DartStrings

' Content variable needed if Head method is unsuccessful.

' If the server rejects the Head method, it will return error ' 12152

Http1.Timeout = 60000 'give it up to 60 seconds

' try "https://www.blockbuster.com" for a server that rejects ' Head

Http1.Url = "https://www.us.buy.com/basket/checkout1.asp"

Http1.Head Headers

' Checking to see if the Head method was rejected by server

If err = 12152 Then

' Head was rejected, we can still get the headers using the

' Get method which requires an extra argument for content.

Http1.Get Body, Headers

End If

Text1.Text = Headers.All

End Sub


Post Method Example (Web Control)

Private Sub Post(FormResults As String)

On Error GoTo OnError ' use intrinsic error handling

' Add DartStrings as a Reference in your VB project using

' Dart Tcp, Daemon, Udp Controls' from the 'Available References' list

Dim Headers As New DartStrings

Dim ReqHeaders As New DartStrings

ReqHeaders.Add "X-MyContent: GoodDay"

Http1.Timeout = 60000 'give it up to 60 seconds

Http1.Url = "https://www.amazon.com/order/form.html"

Http1.Post FormResults, , , Headers

' Make it here with no errors post was successful!

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Proxy Property Example (Web Control)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' specify a proxy w/o a port

Http1.Proxy = "proxy.dart.com"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' specify a proxy server and a port

Http1.Proxy = "proxy.dart.com:8080"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Put Method Example (Web Control)

Private Sub Replace(Page As String)

On Error GoTo OnError ' use intrinsic error handling

' Add DartStrings as a Reference in your VB project using

' Dart Tcp, Daemon, Udp Controls' from the 'Available References' list

Dim Headers As New DartStrings

Dim ReturnHdrs As New DartStrings

Dim Result As String

Http1.Timeout = 60000 'give it up to 60 seconds

Http1.Url = "https://www.amazon.com/order/form.html"

Http1.Version = "HTTP/1.1"

Headers.Add "Content-Length: " & Len(Page)

Headers.Add "Content-Type: application/x-www-form-urlencoded"

Http1.Put Page, Headers, Result, ReturnHdrs

' Make it here with no errors - put was successful!

' Put the Resulting data and headers into a text box

Text1.Text = Headers.All & vbCrLf & Result

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Security Property Example (Web Control)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Security As Long

Security = 0

' check to see if redirecting to/from HTTPS OK.

If Label1.Caption = True Then

Security = httpAllowRedirectToHTTP + httpAllowRedirectToHTTPS

End If

' check to see if Certificates are strictly enforced

If Label2.Caption = False Then

Security = Security + httpIgnoreCertNameCheck + _

httpIgnoreCertDateCheck + httpIgnoreUnkCertAuth + _

httpIgnoreCertRevocation

End If

' now set the security level

Http1.Security = Security

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


State Event Example (Web Control)

This VB example shows how to verify the value of the State property.

Private Sub Http1_State()

On Error GoTo OnError ' use intrinsic error handling

' State of the Http1 connection has changed...put up user feedback

Select Case Http1.State

Case httpStartingRequest

Label1.Caption = "Client starting request..."

Case httpConnected

Label2.Caption = "Client Connected to " & Http1.UrlRemoteHost

Case httpClosing

Label3.Caption = "Client Closing..."

Case httpCompleted

Label4.Caption = "Command completed!"

End Select

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Add Method Example (HttpHeaderFields Object)

This VB example illustrates how header fields are added to a HttpHeaderFields Object.

Dim myHeaders As New HttpHeaderFields

' these two lines of code add the same string to the collection

myHeaders.Add httpServer, "My Server/1.0"

myHeaders.Add httpNull, "Server: My Server/1.0", True

' the same line is also added in both of these cases

myHeaders.Add httpContentLength, "4567"

myHeaders.Add httpNull, "Content-Length: 4567", True


All Property Example (HttpHeaderFields Object)

Dim Hdr As New HttpHeaderFields

Dim HeaderString As String

Dim NumAdded As Integer

Hdr.Add httpServer, "Dart Web Server"

Hdr.Add httpContentLength, "90"

Hdr.Add httpLastModified, "Wed, 10 Nov 1999 20:54:01 GMT"

NumAdded = Hdr.Count

' display all the strings

MsgBox "There are " & NumAdded & " header fields:" & vbCrLf & Hdr.All


HttpHeaderFields Object Example

This VB example shows how to add header fields to a Response Object.

Private Sub SetServerName(Response As Response)

On Error GoTo OnError ' use intrinsic error handling

Response.Header.Add(httpServer, "My Company Server/1.0")

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Find Method Example (HttpHeaderFields Object)

Dim Hdr As New HttpHeaderFields

Dim s As Integer

Hdr.Add httpServer, "My Server/1.0"

' A second server header is added for demonstration. This is not the

' normal practice.

Hdr.Add httpServer, "My Server 2/1.0"

Hdr.Add httpHost, "www.dart.com"

s = 0 'start search at beginning

While Hdr.Find(httpServer, , s) <> "" 'find next "Server:" label

MsgBox "Found: " & Hdr(s) 'use positional lookup

Wend


Item Method Example (HttpHeaderFields Object)

Dim Sub As String

Sub = Request.Header.Item(1) ' explicit use of Item method

Sub = Request.Header(1) ' implicit use of Item method

MsgBox "Header Field in Position 1: " & Sub


Remove Method Example (HttpHeaderFields Object)

Dim Sub As String

'remove the Server header

Response.Header.Remove httpServer

' remove the first header field in the collection

Response.Header.Remove httpNull, 1

' remove all the Server header fields

While Response.Header.Remove httpServer <> ""

Wend


Name Property Example (HttpVariable Object)

Private Sub WebServer1_Get(ByVal Session As DartWebServerCtl.ISession, ByVal Request As DartWebServerCtl.IRequest, ByVal Response As DartWebServerCtl.IResponse)

On Error GoTo OnError ' use intrinsic error handling

Dim Variable As HttpVariable

List1.AddItem "Variables defined for the session:"

For Each Variable In Session.Variables

' only add variable that don’t start with "Temp"

If Variable.Name <> "Temp" Then

List1.AddItem Variable.Name

End If

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Value Property Example (HttpVariable Object)

This VB example demonstrates setting this property to a value.

Dim Variable As New HttpVariable

Variable.Name = "Username"

Variable.Value = "JohnDoe"

This VB example demonstrates setting this property to a Cookie Object:

Dim Cookie As New Cookie

Dim Variable As New HttpVariable

Variable.Name = "Username"

Variable.Value = Cookie


Add Method Example (HttpVariables Object)

Private Sub WebServer1_SessionInit(ByVal Session As DartWebServerCtl.ISession)

On Error GoTo OnError ' use intrinsic error handling

Dim Var As New HttpVariable

' Add a default variable to the session.

Var.Name = "DefaultVar"

Var.Value = "DefaultValue"

Session.Variables.Add Var

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Item Method Example (HttpVariables Object)

Private Sub ShowVariables(Variables As HttpVariables)

On Error GoTo OnError ' use intrinsic error handling

Dim s As String

Dim i As Integer

List1.AddItem "Variables defined for the session:"

For i = 1 To Variables.Count

List1.AddItem Variables.Item(i).Name ' explicit use of Item method

Next i

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Item Property Example (HttpVariables Object)

This VB example demonstrates setting an HttpVariables value.

Dim Variables As New HttpVariables

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Sets the variable named "Var1" to the string value

' of "Test Value 1" or it will create a variable

' name "Var1" and set it string value "Test Value 1" if

' the variable does not exist.

Variables("Var1") = "Test Value 1"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

This VB example demonstrates reading an HttpVariable value.

Dim Variables As New HttpVariables

Private Sub Command1_Click()

On Error GoTo OnError

Dim Value As Variant

' Gets the value of the Variable "Var1"

Value = Variables("Var1")

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Remove Method Example (HttpVariables Object)

Private Sub WebServer1_Get(ByVal Session As DartWebServer.ISession, ByVal Request As DartWebServer.IRequest, ByVal Response As DartWebServer.IResponse)

On Error GoTo OnError ' use intrinsic error handling

Dim Variable1 As HttpVariable

' removes the first variable

Session.Variables.Remove(1)

' remove the variable name "Temp"

Session.Variables.Remove("Temp")

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Alert Event Example (IMAP Control)

Private Sub Imap1_Alert(ByVal Message As String)

On Error GoTo OnError ' use intrinsic error handling

' Display the message to the user.

MsgBox Message

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Command Method Example (IMAP Control)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Reply As String

' Timeout 30 seconds

Imap1.Timeout = 30000

' login to the server

Imap1.Login "imap.test.com", "MyUsername", "MyPassword"

' send a standard NOOP command to the server

Imap1.Command "NOOP", Reply

MsgBox "Server Reply: " & Reply

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


IMAP Control Example

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' default timeout implies blocking operation

Imap1.Login "imap.server.com", "user", "pass"

' Get all mailboxes

Imap1.Refresh

' Imap1.Mailboxes("INBOX").Count now contains the number of messages in the INBOX

' Get messages and put them into the map1.Mailboxes("INBOX").Messages

' collection

Imap1.Mailboxes("INBOX").Get

Text1.Text = Imap1.Mailboxes("INBOX").Count

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Login Method Example (IMAP Control)

Most IMAP servers require a Username and Password, as shown in the following VB example.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Imap1.Timeout = 30000

Imap1.Login "imap.test.com", "user", "pass"

If Imap1.State = tcpConnected Then MsgBox "Logged In!"

Imap1.Logout ' end server session

If Imap1.State = tcpClosed Then MsgBox "Session Completed"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Logout Method Example (IMAP Control)

Refer to the IMAP Control Login Method Example topic for an example of how to log out.


Mailboxes Property Example (IMAP Control)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Mailbox As Mailbox

'Set timeout to 30 seconds

Imap1.Timeout = 30000

Imap1.Login "imap.dart.com", "user", "pass"

'Logged in, get mailbox listing

Imap1.Refresh

'Display mailboxes returned in listing

For Each Mailbox In Imap1.Mailboxes

List1.AddItem Mailbox.Name

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Progress Event Example (IMAP Control)

Refer to IMAP Control Usage for an example of how to use the Progress event.


Refresh Method Example (IMAP Control)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Mailbox As Mailbox

Imap1.Login "imap.test.com", "user", "pass"

' Get new listing from the server. The collection will be

' cleared and repopulated.

Imap1.Refresh

' Display all mailboxes returned in the listing

For Each Mailbox In Imap1.Mailboxes

List1.AddItem Mailbox.Name

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Load Method Example (SnmpMib Object)

This sub demonstrates how to load a serialized bin file.

Private Sub LoadSerializedBin()

On Error GoTo OnError

Debug.Print "Loading serialized bin file..."

Mib.Load ("Serialized.bin")

Debug.Print " Total Variables:" + CStr(Mib.Variables.count)

Debug.Print " Total Traps:" + CStr(Mib.Traps.count)

GoTo Done

OnError:

Debug.Print "ERROR #" + CStr(Err.Number) + ": " + Err.Description

Done:

Debug.Print "Destroying MIB object..."

Set Mib = Nothing

End Sub


Add Method Example (Mailbox Object)

Dim Message As Message

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Add a Message to the INBOX.

Imap1.Mailboxes("INBOX").Add Message.Content

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Copy Method Example (Mailbox Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim MsgSet As String

' Copy All Messages from INBOX to the OldMail mailbox

Imap1.Mailboxes("INBOX").Copy "OldMail"

' Copy just the first and last message from INBOX to TestMbx

MsgSet = "1," & Imap1.Mailboxes("INBOX").Count()

Imap1.Mailboxes("INBOX").Copy "TestMbx", MsgSet

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Count Property Example (Mailbox Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Mailbox As Mailbox

Imap1.Refresh

For Each Mailbox In Imap1.Mailboxes

' Display the mailbox name and the number of messages

MsgBox "Mailbox " + Mailbox.Name + " has " & Mailbox.Count & " Msgs"

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Delete Method Example (Mailbox Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim MsgSet As String

'Delete all messages in the INBOX

Imap1.Mailboxes("INBOX").Delete

' Delete the first 3 messages from TestMbx

MsgSet = "1:3"

Imap1.Mailboxes("TestMbx").Delete MsgSet

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Mailbox Object Example

This VB example demonstrates how access a Mailboxes Object to rename a Mailbox Object.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Rename the "Misc" mailbox to "Test"

Imap1.Mailboxes.Item("Misc").Name = "Test"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Flags Property Example (Mailbox Object)

This VB example demonstrates checking for flags.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Mailbox As Mailbox

Imap1.Refresh

For Each Mailbox In Imap1.Mailboxes

List1.AddItem "Flags for " + Mailbox.Name + ":"

' Check for the Marked flag in the collection

If Mailbox.Flags.Find("\Marked") <> "" Then

List1.AddItem "Marked"

End If

' Check for the Unmarked flag in the collection

If Mailbox.Flags.Find("\Unmarked") <> "" Then

List1.AddItem "Unmarked"

End If

' Check for the Noinferiors flag in the collection

If Mailbox.Flags.Find("\Noinferiors") <> "" Then

List1.AddItem "Noinferiors"

End If

' Check for the NoSelect flag in the collection

If Mailbox.Flags.Find("\Noselect") <> "" Then

List1.AddItem "Noselect"

End If

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Get Method Example (Mailbox Object)

Private Sub Command1_Click()

Dim Msg As Message

On Error GoTo OnError ' use intrinsic error handling

Imap1.Timeout = 30000

Imap1.Login "imap.test.com", "MyUsername", "MyPassword"

' Get list of mailboxes

Imap1.Refresh

' Get the size of each Message in the INBOX

Imap1.Mailboxes("INBOX").Get imapGetSize

' Get the content of messages smaller than 10,000 bytes

For Each Msg In Imap1.Mailboxes("INBOX").Messages

If Msg.Size < 10000 Then

' get content for message

Imap1.Mailboxes("INBOX").Get imapGetContent, Msg.Number

Else

' Get the header info instead

Imap1.Mailboxes("INBOX").Get imapGetHeader, Msg.Number

End If

Next

Imap1.Logout ' all done, log out

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Name Property Example (Mailbox Object)

Refer to Mailbox Object Example for an example of how to use the Name property.


Purge Method Example (Mailbox Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Mark all messages in INBOX for deletion

Imap1.Mailboxes("INBOX").Delete

' Permanently delete all the messages

Imap1.Mailboxes("INBOX").Purge

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Put Method Example (Mailbox Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Mark all messages in the INBOX as seen

Imap1.Mailboxes("INBOX").Put "\Seen"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


ReadOnly Property Example (Mailbox Object)

This VB example attempts to reopen a mailbox as read-write.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Set the property to FALSE to attempt a read-write open

Imap1.Mailboxes("TestMailbox1").ReadOnly = False

' Perform an operation and the mailbox will try to open as read-write

Imap1.Mailboxes("TestMailbox1").Get

' Check to see if it is read-write now

If Imap1.Mailboxes("TestMailbox1").ReadOnly = False Then

MsgBox "Mailbox Reopened to Read-Write Successfully!"

Else

MsgBox "Mailbox Reopened to Read-Write Failed!"

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

This VB example attempts to reopen the mailbox as read-only.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Set the property to TRUE to attempt an read-only open

Imap1.Mailboxes("TestMailbox1").ReadOnly = True

' Perform an operation and the mailbox will try to open as read-only

Imap1.Mailboxes("TestMailbox1").Get

' Check to see if it is read-only now

If Imap1.Mailboxes("TestMailbox1").ReadOnly = True Then

MsgBox "Mailbox Reopened to Read-Only Successfully!"

Else

MsgBox "Mailbox Reopened to Read-Only Failed!"

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Recent Property Example (Mailbox Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Mailbox As Mailbox

For Each Mailbox In Imap1.Mailboxes

' Display the mailbox name and the number of messages

' Refresh count & recent property

Mailbox.Refresh

MsgBox Mailbox.Name + " has " & Mailbox.Recent & " Recent Msgs"

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Refresh Method Example (Mailbox Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Mailbox As Mailbox

For Each Mailbox In Imap1.Mailboxes

'Call the refresh method to update the count

Mailbox.Refresh

'List the mailbox name and number of messages it contains.

List1.AddItem Mailbox.Name + "(" & Mailbox.Count & " Messages)"

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Search Method Example (Mailbox Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim MsgSet As String

' Set Timeout to blocking operation so MsgSet remains in scope

Imap1.Timeout = 10000

' Find all messages that have been marked for deletion since Feb 1, 1999

Imap1.Search "DELETED SINCE 1-Feb-1999", MsgSet

' Example MsgSet may be "1 2 4 9"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Uid Property Example (Mailbox Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Mailbox As Mailbox

For Each Mailbox In Imap1.Mailboxes

' Refresh count, uid & recent property

Mailbox.Refresh

' Display the mailbox name, the number of messages, the mailbox Uid

MsgBox "Mailbox " & Mailbox.Name & " Uid " & Mailbox.Uid _

& "has " & Mailbox.Count & " Msgs"

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Undelete Method Example (Mailbox Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim MsgSet As String

Dim Count As Integer

' Set Timeout to blocking operation so MsgSet remains in scope

Imap1.Timeout = 10000

' Unmark all messages in the "DeletedMail" mailbox

Imap1.Mailboxes("DeletedMail").Undelete

' Unmark the last three messages in INBOX

Count = Imap1.Mailboxes("INBOX").Count

MsgSet = Count – 2 & ": " & Count

Imap1.Mailboxes("INBOX").Undelete MsgSet

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Mailboxes Object Example

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Mailbox As Mailbox

Imap1.Refresh

' Display mailboxes returned in listing

For Each Mailbox In Imap1.Mailboxes

List1.AddItem Mailbox.Name

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Item Method Example (Mailboxes Object)

This VB example shows both ways of accessing a mailbox in the collection.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Imap1.Refresh

' Display mailbox name by its index

' explicit use of Item method

MsgBox "Mailbox 2 Name: " & Imap1.Mailboxes.Item(2).Name

' Display number of messages in INBOX

' implicit use of Item method

MsgBox "Number of Messages in INBOX: " & Imap1.Mailboxes("INBOX").Messages.Count

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Remove Method Example (Mailboxes Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Imap1.Refresh

' Remove the mailbox "Misc" from the collection and from the server

Imap1.Mailboxes.Remove ("Misc")

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Subscribe Method Example (Mailboxes Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Subscribe to mailbox called "PublicGroup"

Imap1.Mailboxes.Subscribe "PublicGroup"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Unsubscribe Method Example (Mailboxes Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Unsubscribe to mailbox called "PublicGroup"

Imap1.Mailboxes.Unsubscribe "PublicGroup"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


AgentName Property Example (Manager Control)

Private Sub Manager1_Response()

On Error GoTo OnError ' use intrinsic error handling

' add the source address to a list of agent responses

List1.AddItem Manager1.AgentName

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


AgentPort Property Example (Manager Control)

Private Sub Manager1_Response()

On Error GoTo OnError ' use intrinsic error handling

MsgBox "Response received from port " & Manager1.AgentPort

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


AgentVariable Property Example (Manager Control)

This VB example demonstrates getting a value from an agent.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Variable As SnmpVariable

'Call Reset to assure community is "public"

Manager1.Message.Reset

Manager1.AgentName = "agent.dart.com"

' Get the sysDescr value for the Agent

Set Variable = Manager1.AgentVariable("1.3.6.1.2.1.1.1.0")

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

The following code snippet demonstrates setting a value on an agent:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Variable As New SnmpVariable

'Call Reset to assure community is "public"

Manager1.Message.Reset

Manager1.AgentName = "agent.dart.com"

' Set the sysDescr value for the Agent

Variable.Type = snmpOctetString

Variable.Value = "450mhz w/NT 4.0"

Manager1.AgentVariable("1.3.6.1.2.1.1.1.0") = Variable

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Manager Control Example

This VB example demonstrates requesting a variable, displaying the agent's response, and then setting a variable on the agent.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Value As SnmpVariable

'AgentPort property defaults to 161.

Manager1.Message.Reset

Manager1.AgentName = "agent.dart.com"

Manager1.AgentPort = 161

'Get the sysContact for the agent using the AgentVariable property

Set Value = Manager1.AgentVariable("1.3.6.1.2.1.1.4.0")

List1.AddItem Value.Value

'Set the sysDescr for the agent using the AgentVariable property

Manager1.Message.Reset

Value.Type = snmpOctetString

Value.Value = "450mhz with WinNT 4.0"

Manager1.AgentVariable("1.3.6.1.2.1.1.1.0") = Value

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

This example is a trivial case, but PowerTCP fully supports multi-value packets with a little more coding effort.


Response Event Example (Manager Control)

This VB example demonstrates displaying the values included in the response:

Private Sub Manager1_Response()

On Error GoTo OnError ' use intrinsic error handling

Dim Variable As SnmpVariable

List1.AddItem "Message from " + Manager1.AgentName

If Manager1.Message.Exception = snmpOk Then

For Each Variable In Manager1.Message.Variables

List1.AddItem Variable.Value

Next

Else

MsgBox "Error in variable: " & Manager1.Message.ExceptionIndex

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Trap Event Example (Manager Control)

This VB example demonstrates displaying the variables contained in the trap.

Private Sub Manager1_Trap()

On Error GoTo OnError ' use intrinsic error handling

Dim Variable As SnmpVariable

List1.AddItem "Trap from " + Manager1.AgentName

For Each Variable In Manager1.Message.Variables

List1.AddItem Variable.Value

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


AddAttachment Method Example (Message Object)

Refer to the SMTP Control Send Method Example topic for an example of how to use the AddAttachment method.


AddDigest Method Example (Message Object)

This VB example produces a digest with introductory text and two messages.

Private Sub Command1_Click()

On Error GoTo OnError

Smtp1.Message.To.Add "user@test.com"

Smtp1.Message.AddDigest "C:\Week1.msg", "Company Mailing List Archive for July, 2000"

Smtp1.Message.AddDigest "C:\Week2.msg"

Smtp1.Login "smtp.server.com" ' start the mail session

Smtp1.Send ' send message

Smtp1.Logout ' end session

MsgBox "Message Sent!" ' no errors generated gets us here

Exit Sub

OnError:

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


AddMessage Method Example (Message Object)

This VB example shows the use of the AddMessage and AddText methods to compose a multipart message containing text and two messages.

Private Sub Command1_Click()

On Error GoTo OnError

Dim Msg As New Message, OldMsg As New Message

OldMsg.Load "C:\Test.msg"

Msg.To.Add "user@test.com"

Msg.Header.Add msgSubject, "Merger Information"

Msg.AddText "Including two messages from Bill related to the issue."

Msg.AddMessage "C:\Review.msg"

Msg.AddMessage OldMsg.Content

Smtp1.Login "smtp.server.com" ' start the mail session

Smtp1.Message = Msg ' set message

Smtp1.Send ' send message

Smtp1.Logout ' end session

MsgBox "Message Sent!" ' no errors generated gets us here

Exit Sub

OnError:

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


AddText Method Example (Message Object)

Refer to the Message Object AddMessage Method Example for an example of how to use the AddText method.


Decode Method Example (Message Object)

Dim Msg As New Message

Dim s(2000) As String

While Tcp1.Receive(s) <> 0

Msg.Decode s

Wend

' Object model may now be referenced


DecodeBuf Method Example (Message Object)

Dim Str As String ' sample string to encode

Dim EncodedStr As String ' encoded version of Str

Dim StrOut As String ' decoded version of EncodeStr

Dim Msg As New Message

Str = "Testing of the EncodeBuf method"

Msg.EncodeBuf Str, EncodedStr, msgBase64

' EncodedStr now contains a Base64 encode version of Str

Msg.DecodeBuf EncodedStr, StrOut, msgBase64

' at this point Str and StrOut should be the same

MsgBox StrOut


Encode Method Example (Message Object)

This VB example uses the Encode method to send a Message using the TCP Control.

Dim Msg As New Message

Dim s As String

Msg.Load "C:\Temp\Test.Msg"

' make sure we start with the first buffer

Msg.Encode (0)

While Msg.Encode(s) <> 0

Tcp1.Send s

Wend

' message has been encoded and sent


EncodeBuf Method Example (Message Object)

Dim Str As String ' sample string to encode

Dim EncodedStr As String ' encoded version of Str

Dim StrOut As String ' decoded version of EncodeString

Dim Msg As New Message

Str = "Testing of the EncodeBuf method"

Msg.EncodeBuf Str, EncodedStr, msgBase64

' EncodedStr now contains a Base64 encode version of Str

Msg.DecodeBuf EncodedStr, StrOut, msgBase64

' at this point String and StrOut should be the same

MsgBox StrOut


Message Object Example

Refer to the SMTP Control Send Method Example topic for an example of how to use the Message Object.


Forward Method Example (Message Object)

Private Sub Command1_Click()

On Error GoTo OnError

Dim Msg As New Message

Msg.Load "C:\Test.msg"

'send the message using the SMTP Control

Smtp1.Message = Msg.Forward("user@test.com", "Check this out")

Smtp1.Login "smtp.server.com" ' start the mail session

Smtp1.Send ' send message

Smtp1.Logout ' end session

MsgBox "Message Sent!" ' no errors generated gets us here

Exit Sub

OnError:

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Header Property Example (Message Object, Part Object)

Header Property Example (Message Object/Part Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Msg As New Message

Msg.Load "C:\Test.msg"

Msg.Subject = "This is a test" ' set the subject header field

Msg.Header.Remove msgSender ' remove the sender header field

MsgBox Msg.Header.Find(msgDate) ' display the Date header field

MsgBox "Content Type: " & Msg.Header.Find(msgContentType) ' display Content-Type

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Reply Method Example (Message Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Msg As New Message

Dim MsgReply As Message

Pop1.Login "server", "account", "password"

Pop1.Get msgContent, "1" ' pop the original message

Pop1.Logout

' create the Reply message

Msg = Pop1.Messages(1).Reply "Great Idea!"

' we now have a message ready to send

Smtp1.Login "mail.dart.com"

Smtp1.Send

Smtp1.Logout

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Store Method Example (Message Object)

Private Sub Command1_Click()

On Error GoTo OnError

Dim Msg As New Message

Msg.To.Add "user@test.com"

Msg.Subject = "See Attached Files"

Msg.AddAttachment "C:\Temp\Test.xls"

Msg.AddAttachment "C:\Temp\Test.txt"

' store the message as a single encoded file

Msg.Store "c:\Temp\Encoded\Store.msg"

' store the message as a quick-load object

Msg.Store "c:\Temp\Decoded\Store.msg", msgDecoded

Exit Sub

OnError:

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Add Method Example (Messages Object)

This VB example shows how a message can be initialized and added to a collection.

Private Sub Command1_Click()

On Error GoTo OnError

Dim msg As New Message, msgs As New Messages

' load an existing message from disk

msg.Load "C:\Test.msg"

msgs.Add msg

msg.Load "C:\Info.msg"

msgs.Add msg

Text1.Text = msgs.Count ' display number of messages in collection

Exit Sub

OnError:

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Data Property Example (Part Object)

Private Sub Command1_Click()

' On Error GoTo OnError ' use intrinsic error handling

Dim msg As New Message

msg.AttachmentDirectory = ""

msg.Load "C:\Test.msg"

msg.AddAttachment "C:\Info.msg"

' show the data in the message

If Msg.Parts.Count > 0 Then MsgBox Msg.Parts(1).Data

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Part Object Example

This VB example does not perform any useful application; it simply illustrates the manipulation mechanisms.

Private Sub Command1_Click()

Dim p1 As New Part, p11 As New Part, p12 As New Part

Dim p111 As New Part, p112 As New Part

Dim p2 As New Part, p21 As New Part, p22 As New Part

Dim temp As Part

Dim n As Integer

Dim Msg As New Message

Msg.Content = "" 'clear the object

' Use the Parts collection of the Message Object to add parts

' Create a part structure with 1, 1.1, 1.2, 2, 2.1, 2.2

Msg.Parts.Add p1 ' add 1

Msg.Parts(1).Parts.Add p11 ' add 1.1

Msg.Parts(1).Parts.Add p12 ' add 1.2

Msg.Parts.Add p2 ' add 2

Msg.Parts(2).Parts.Add p21 ' add 2.1

Msg.Parts(2).Parts.Add p22 ' add 2.2

' Save a temporary reference to p11

' Then search the master parts list for the part

Set temp = Msg.Parts(1).Parts(1)

' Create two children under Part 1.1

temp.Parts.Add p111 ' add 1.1.1 using temp

temp.Parts.Add p112 ' add 1.1.2 using temp

' Remove the Part subtree with the parent 1.1

' The remaining parts automatically re-number

Msg.Parts(1).Parts.Remove (1) ' remove 1.1, 1.1.1, 1.1.2 from message

' p12 is now referenced as Msg.Parts(1).Parts(1)

' Iterate through Part objects using automatic iteration

For Each temp In Msg.PartList

MsgBox temp.Index

Next

' Iterate through Part objects using count loop

For n = 1 To Msg.PartList.Count

MsgBox Msg.PartList(n).Index

Next

End Sub


Add Method Example (Parts Object)

Private Sub Command1_Click()

Dim msg As New Message

Dim p1 As New Part, p2 As New Part

' add a new Part to list collection

msg.Parts.Add p2

' create another Part, make it the first in the list

msg.Parts.Add p1, 1

MsgBox "There are " & msg.Parts.Count & " parts"

End Sub


PhoneBookEntries Object Example

This VB example demonstrates automatic iteration.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Fill an external list box with the RAS phonebook entry names

Dim Entry As PhoneBookEntry

For Each Entry In Ras1.PhoneBook

List1.AddItem Entry.Name

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

The above iteration could also be performed as:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Fill an external list box with the RAS phonebook entry names

Dim I As Integer

For I = 1 To Ras1.PhoneBook.Count

List1.AddItem Ras1.PhoneBook(I).Name

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Because the Item index can also be a string, specific entries can also be accessed such as:

List1.AddItem Ras1.PhoneBook("Tokyo Office").Domain

List1.AddItem Ras1.PhoneBook("London Office").Domain


Edit Method Example (PhoneBookEntry Object)

This VB example shows how to invoke system dialog boxes to edit a RAS phonebook entry.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Edit the entry the user has currently selected in the Ras Control list box

Ras1.PhoneBook(Ras1.PhoneBook.Selected).Edit

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Data Property Example (Ping Control)

Private Sub Command1_Click()

On Error GoTo OnError

Dim bOut() As Byte

Dim bIn() As Byte

Dim s As String

Dim n As Integer

bOut = StrConv("Hello World!", vbFromUnicode)

Ping1.Timeout = 3000

' Display Outgoing byte array

For n = 0 To UBound(bOut)

s = s + Chr(bOut(n))

Next

Text1.Text = "Out: " + s

Ping1.Data = bOut

Ping1.Ping "www.dart.com"

bIn = Ping1.Data

' Display Incoming byte array

s = ""

For n = 0 To UBound(bIn)

s = s + Chr(bIn(n))

Next

Text2.Text = "In: " + s

Exit Sub

OnError:

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Delay Property Example (Ping Control)

This VB example shows how to display the time between sending a ping request and receiving a response.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Ping1.Ping "www.dart.com"

MsgBox "Server is alive with a delay of " & Ping1.Delay & " milliseconds"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Id Property Example (Ping Control)

Private Sub Command1_Click()

Dim i As Integer

' go to non-blocking mode

Ping1.Timeout = 0

' send out 3 requests in a row

For i = 1 To 3

Ping1.Id = i

Ping1.Ping "server.test.com"

Next i

' set the first id to look for in the Response Event

NextId = 1

End Sub

Private Sub Ping1_Response()

' make sure we get responses back in order

If Ping1.Id <> NextId Then

MsgBox "Missed Response # " & NextId

End If

' Increment the next incoming response number

NextId = NextId + 1

End Sub


Ping Method Example (Ping Control)

This VB example shows how to determine the average time of multiple ping requests.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim i As Integer

Dim Total As Long

' make sure we are in blocking mode

Ping1.Timeout = 30000

' send out 3 requests in a row

For i = 1 To 3

Ping1.Id = i

Ping1.Ping "www.dart.com"

Total = Total + Ping1.Delay

Next i

MsgBox "Average Delay: " & Int((Total / 3))

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Response Event Example (Ping Control)

This VB example shows how to verify a ping response.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Ping1.Ping "www.dart.com"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Private Sub Ping1_Response()

On Error GoTo OnError ' use intrinsic error handling

' we can now do something with the response

' for this example just report that we got a

' response and how long it took.

Text1.Text = Ping1.Id

Text2.Text = Ping1.Delay

Text3.Text = "OK"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Command Method Example (POP Control)

This VB example shows how to send protocol commands to the POP server.

Private Sub Command1_Click()

Dim Reply As String

On Error GoTo OnError ' use intrinsic error handling

' login to the server

Pop1.Login "pop.server.com", "user", "password"

' send a standard NOOP command to the server

Pop1.Command "NOOP", Reply, False

MsgBox "Server Reply: " & Reply

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Delete Method Example (POP Control)

This VB example shows how to mark one or more messages for removal upon normal completion of the session.

Private Sub Command1_Click()

On Error GoTo OnError

Pop1.Login "pop.server.com", "user", "pass"

Pop1.Delete "2,3" ' Message 2 and 3 marked for deletion

Pop1.Reset ' Delete flags are now cleared

Pop1.Delete "3" ' Message 3 marked for deletion

Pop1.Logout ' Message 3 is actually deleted here

Exit Sub

OnError:

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


POP Control Example

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' create session

Pop1.Login "pop1.server.com", "username", "password"

If Pop1.State = tcpConnected Then MsgBox "Connected!"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Get Method Example (POP Control)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Pop1.TimeOut = 30000

Pop1.Login "pop.server.com", "user", "pass"

' get the size of each Message on the server

Pop1.Get msgSize

' get the content of messages smaller than 10,000 bytes

For Each msg In Pop1.Messages

If msg.Size < 1000 Then ' test size

' get full text of message

Pop1.Get msgText

MsgBox msg.From & vbCrLf & vbCrLf & "Full message text is: " & _

vbCrLf & vbCrLf & msg.Text

Else

' get first ten lines of message

Pop1.Get msgPreview

MsgBox msg.From & vbCrLf & vbCrLf & "Preview message text is: " & _

vbCrLf & vbCrLf & msg.Text

End If

Next

Pop1.Logout ' all done, log out

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Login Method Example (POP Control)

This VB example shows how to log in to a POP server and display the mailbox message count.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Pop1.Login "pop.server.com", "user", "password"

If Pop1.State = tcpConnected Then MsgBox "Connected!"

' display mailbox message count

MsgBox Str(Pop1.Count) & " messages exist."

Pop1.Logout ' end server session

MsgBox "Session Completed" ' no errors generated gets us here

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Logout Method Example (POP Control)

Refer to the POP Control Login Method Example topic for an example of how to log out.


Messages Property Example (POP Control)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Pop1.Timeout = 30000

' create a session

Pop1.Login "pop.test.com", "user", "pass"

' request headers only from the server (no preview lines)

Pop1.Preview = 0

Pop1.Get msgPreview, "1,3,5"

' iterate through messages and inspect

For Each Msg In Pop1.Messages

MsgBox "From: " & Msg.From & " Subject:" & Msg.Subject

Next

' end session

Pop1.Logout

' shows Msg # 5, the 3rd item in the messages collection

MsgBox "Msg # " & Str(Pop1.Messages(3).Attribute(msgNumber))

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Progress Event Example (POP Control)

Refer to the POP Control Usage, Blocking Sample, or Non-Blocking Sample topics for examples of how to use the Progress event.


Reset Method Example (POP Control)

Refer to the POP Control Delete Method Example topic for an example of how to reset the server.


Authenticate Event Example

This VB example demonstrates denying a certificate in this case.

Private Sub SecureTcp1_Authenticate(RemoteCertificate As Certificate, TrustedRoot As Boolean, ValidDate As Boolean, ValidSignature As Boolean, ByRef Valid As Boolean)

On Error GoTo OnError ' use intrinsic error handling

If RemoteCertificate.IssuedTo <> gRemoteHostName Then Valid = False

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Certificate Event Example

Private Sub SecureTcp1_Certificate ( )

Dim Store As New CertificateStore

'Get the desired certificate

SecureTcp1.Certificate = Store.Find("ROOT", locationLocalMachine, g_SavedIssuedBy, g_SavedSerialNumber)

‘ Or you could pop up a list box so the user could select a certificate

End Sub


Certificate Property Example

Dim Store As New CertificateStore

Dim Certificate As Certificate

'Get the certificates in "MY" certificate store located in the

'Local Machine registry key.

Store.Name = "MY"

Store.Location = locationLocalMachine

'Must use Refresh to populate Store.Certificates

Store.Refresh

MsgBox "There are " & Store.Certificates.Count & " certificates."

'Set the certificate to the one for "DartServer"

For Each Certificate In Store.Certificates

If Certificate.IssuedTo = "DartServer" Then

SecureTcp1.Certificate = Certificate

Exit For

End If

Next

Alternatively, you can use the Find method to set the certificate:

Dim Store As New CertificateStore

'Get the desired certificate

SecureTcp1.Certificate = Store.Find("ROOT", locationLocalMachine, g_SavedIssuedBy, g_SavedSerialNumber)


ClientAuthentication Property Example

Private Sub Daemon1_Accept()

On Error GoTo OnError ' use intrinsic error handling

' The server will ask the client to authenticate itself.

SecureTcp1.ClientAuthentication = True

' Specify the digital certificate the server will use.

Dim Store As New CertificateStore

Dim Certificate As Certificate

'Get the certificate in "ROOT" certificate store located in the

'Local Machine registry key, and identified by Issuer and SN.

SecureTcp1.Certificate = Store.Find("ROOT", locationLocalMachine, g_SavedIssuedBy, g_SavedSerialNumber)

' Accept the socket...the Timeout Property is automatically set to 0

SecureTcp1.Socket = Daemon1.Accept

' SecureTcp1 will negotiate a secure connection with the client...

' State Event will fire when authentication completes

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Fill Method Example

Private Sub Tcp1_Receive()

Dim ReceiveBuffer(4) As Byte

Dim Count As Long

Tcp1.Timeout = 0

Count = Tcp1.Fill(ReceiveBuffer)

' if Count is equal to 0, then 5 Bytes were not available.

End Sub

Private Sub Tcp1_Receive()

Dim Count As Long

Dim ReceiveBuffer(99) As Byte

' want all 100 Bytes or none at all!

Tcp1.Timeout = 1000 ' wait for at least one second

Count = Tcp1.Fill(ReceiveBuffer)

' Count is guaranteed to be 100 if we don't time out!

End Sub

In addition, you can use this method to receive binary data and structures. The following VB code snippet shows how user-defined types and the Lset command can be used to receive and process data that is sent in binary format. In C++, a union would be used to accomplish the same thing without a memory copy.

Private Type MyStruct

i As Integer

l As Long

End Type

Private Type ByteStruct

b(6) As Byte ' b MUST be the same size As i and l from MyStruct

End Type

Private Sub Tcp1_Receive()

Dim Count As Long

Dim x As MyStruct, y As ByteStruct

' want all 6 Bytes or none at all!

Tcp1.Timeout = 0 ' check and immediately return

Count = Tcp1.Fill(y.b) ' fill Byte array in ByteStruct user-defined type

LSet x = y ' user-defined types can do this!

' If Count > 0, then reference x.i and x.l for the binary numbers that were sent

End Sub


Protocol Property Example

This VB example demonstrates the use of this property.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Detect and use any supported protocol to establish

' a secure connection.

SecureTcp1.Protocol = secureAuto

SecureTcp1.Connect "secure.dart.com"

MsgBox "Connected!"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

This VB example demonstrates the use of this property when using a specified protocol.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Use only the PCT protocol to establish a secure connection.

' If not available/supported connection will not be established

SecureTcp1.Protocol = securePCT

SecureTcp1.Connect "secure.dart.com"

MsgBox "Connected!"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Receive Event Example (TCP Control)

Private Sub Tcp1_Receive()

On Error GoTo OnError ' use intrinsic error handling

Dim s As String

Tcp1.Receive s ' receive as much data as is available into a String

Text1.SelText = s ' append received data to text in the text box

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Receive Method Example (TCP Control)

' pre-initialize byte array to size 8k at module level

Dim ReceiveBuffer(8192) As Byte

Private Sub Tcp1_Receive()

On Error GoTo OnError ' use intrinsic error handling

Dim Count As Long

' perform non-blocking receive, since Receive event fired

Count = Tcp1.Receive (ReceiveBuffer)

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Function GetData() As String

' use un-initialized variable length String

Dim Data As String

Dim Count As Long

' fetch what's found, wait up to 10 seconds to find at least one byte

Tcp1.Timeout = 10000

Count = Tcp1.Receive (Data)

GetData = Data

End Function

Function GetAllData1() As String

' fetch all the data until the remote host closes the connection

While Tcp1.State <> tcpClosed

' un-initialize Data so it is resized each time

Data = ""

Dim Count As Long

Count = Tcp1.Receive(Data)

' append received string to return value

GetAllData1 = GetAllData1 & Data

Wend

End Function

Function GetAllData2() As String

' fetch all the data until the remote host closes the connection

Dim Data As String

While Tcp1.Receive(Data)

' append received string to return value

GetAllData2 = GetAllData2 & Data

' un-initialize Data so it is resized each time

Data = ""

Wend

End Function


Send Event Example

Private Sub Tcp1_Send()

On Error GoTo OnError ' use intrinsic error handling

' read from file that is open and send that string

' this event will fire again later when we can send more

Dim Count As Long

' compute the number of bytes left in the file

gSendTransfer = LOF(2) - Loc(2)

' limit the number of bytes to the specified buffers size

If gSendTransfer > CLng(Text1.Text) Then gSendTransfer = Text1.Text

If gSendTransfer > 0 Then

' save the number of bytes sent and send the data

Count = Tcp1.Send(Input$(gFile, #2))

' put up the total count read so far

Label1.Caption = Str(Val(Label2.Caption) + Count)

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Close Method Example (RAS Control)

Blocking Example:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Ras1.Timeout = 15000

Ras1.Close

' didn’t go to OnError, so we closed before 15 seconds elapsed!

MsgBox "Graceful Closed!"

Exit Sub

Exit Sub

OnError: ' Any error jumps here

MsgBox "Aborted!"

End Sub

Non-Blocking Example:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' intrinsic error handling is of limited value for asynchronous connection&ldots;

Ras1.Close

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Private Sub Ras1_State()

On Error GoTo OnError ' use intrinsic error handling

If Ras1.State = rasClosed Then MsgBox "Closed!"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Connect Method Example (RAS Control)

Blocking Example:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' give RAS up to 60 secs to dial out and make connection

Ras1.Timeout = 60000

' connect without using a phonebook entry

Ras1.Connect "555-9595", "johndoe", "pleaseconnect"

' didn’t go to OnError, so we connected successfully!

' can now connect via a TCP connection

Exit Sub

OnError: ' Any error jumps here

' no connection within 30 seconds, or other error (Ras1.State is rasClosed)

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Non-Blocking Example:

Private Sub Command1_Click()

Ras1.Timeout = 0

' connect without the use of a phonebook entry

Ras1.Connect "555-9595", "johndoe", "pleaseconnect"

End Sub

Private Sub Ras1_State()

If Ras1.State = rasConnected Then MsgBox "Connected!"

End Sub


ConnectEntry Method Example (RAS Control)

Blocking Example:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' give RAS up to 60 secs to dial out and make connection

Ras1.Timeout = 60000

' connect to a RAS entry previously chosen

Ras1.ConnectEntry sRasEntry

' Interactive example: Ras1.ConnectEntry Ras1.PhoneBook.Selected

' didn’t go to OnError, so we connected successfully!

' Can now connect with a TCP connection.

Exit Sub

OnError: ' Any error jumps here

' no connection within 30 seconds, or other error (Ras1.State is rasClosed)

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Non-Blocking Example:

Private Sub Command1_Click()

' intrinsic error handling is of limited value for asynchronous connection

Ras1.Timeout = 0

' connect to the RAS entry

Ras1.ConnectEntry sRasEntry

End Sub

Private Sub Ras1_State()

If Ras1.State = rasConnected Then MsgBox "Connected!"

End Sub


Request Object Example (WebServer Tool)

Private Sub WebServer1_Get(ByVal Session As DartWebServerCtl.ISession, ByVal Request As DartWebServerCtl.IRequest, ByVal Response As DartWebServerCtl.IResponse)

On Error GoTo OnError ' use intrinsic error handling

' The Request parameter holds the current request

List1.AddItem "Request from " + Request.RemoteAddress

List1.AddItem "Request Doc " + Request.FileName

' Do other processing here

' . . .

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


FileName Property Example (Request Object - WebServer Tool)

FileName Property Example (Request Object)

Private Sub WebServer1_Get(ByVal Session As DartWebServer.ISession, ByVal Request As DartWebServer.IRequest, ByVal Response As DartWebServer.IResponse)

On Error GoTo OnError ' use intrinsic error handling

List1.AddItem "The absolute path of the requested object is:"

List1.AddItem WebServer1.RootDirectory + Request.FileName

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Files Property Example (Request Object - WebServer Tool)

Files Property Example (Request Object)

This VB example shows how to set the files to persist after the event completes.

Dim File As DartStream

' Set DeleteOnDestroy to False to keep files

For Each File In Request.Files

File.DeleteOnDestroy = False

Next


Cookies Property Example (Request Object/Response Object - WebServer Tool)

Cookies Property Example (Request Object/Response Object)

This VB example demonstrates this property when part of a Request Object.

Private Sub WebServer1_Get(ByVal Session As DartWebServer.ISession, ByVal Request As DartWebServer.IRequest, Response As DartWebServer.IResponse)

On Error GoTo OnError ' use intrinsic error handling

Dim Cookie As Cookie

List1.AddItem "Cookies sent by the client:"

For Each Cookie In Request.Cookies

List1.AddItem Cookie.Name + " = " + Cookie.Value

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

This VB example demonstrates this property when part of a Response Object.

Private Sub WebServer1_Get(ByVal Session As DartWebServer.ISession, ByVal Request As DartWebServer.IRequest, Response As DartWebServer.IResponse)

On Error GoTo OnError ' use intrinsic error handling

Dim Cookie As Cookie

'Add a new cookie with only one value. Username = loginname

Set Cookie = New Cookie

Cookie.Name = "Username"

Cookie.Value = "loginname"

Response.Cookies.Add Cookie

'Add a new cookie with 2 sub values.

' Passwords = Pass1 = "secret" & Pass2 = "othersecret"

Set Cookie = New Cookie

Cookie.Name = "Passwords"

Cookie.SubValues("Pass1") = "secret"

Cookie.SubValues("Pass2") = "othersecret"

Response.Cookies.Add Cookie

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Header Property Example (Request Object/Response Object - WebServer Tool)

Header Property Example (Request Object/Response Object)

This VB example demonstrates this property when part of a Request Object.

Private Sub WebServer1_Get(ByVal Session As DartWebServer.ISession, ByVal Request As DartWebServer.IRequest, Response As DartWebServer.IResponse)

On Error GoTo OnError ' use intrinsic error handling

Dim HeaderLine As String

List1.AddItem "Headers sent by the client:"

For Each HeaderLine In Request.Header

List1.AddItem HeaderLine

Next

End Sub

This VB example demonstrates this property when part of a Response Object.

Private Sub WebServer1_Get(ByVal Session As DartWebServer.ISession, ByVal Request As DartWebServer.IRequest, Response As DartWebServer.IResponse)

' The response object will automatically contain the requested page

' or an error page, but we can alter it here.

' Add Headers for the response.

Dim Page As New DartStream

Response.Header.Clear

Response.Header(httpNull) = "Server: My Server/1.0"

' Now set the body

Page.Write "<HTML><BODY>Hello World!</BODY></HTML>"

Response.Body = Page

Response.Status = httpOK

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Secure Property Example (Request Object - WebServer Tool)

Secure Property Example (Request Object)

Private Sub WebServer1_Get(ByVal Session As DartWebServer.ISession, ByVal Request As DartWebServer.IRequest, Response As DartWebServer.IResponse)

On Error GoTo OnError ' use intrinsic error handling

If Not Response.Secure Then

' ensure all requests are secure

' return response telling user Only Secure connections

' are allowed

Dim Page As New DartStream

Page.FileName = "SecureOnly.htm"

Page.FileMode = createExisting

Response.Body = Page

Response.Status = httpOK

Else

' we have a secure connection, process normally

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Variables Property Example (Request Object/Session Object - WebServer Tool)

Variables Property Example (Request Object/Session Object)

This VB example demonstrates this property when part of a Request Object.

Private Sub WebServer1_Get(ByVal Session As DartWebServer.ISession, ByVal Request As DartWebServer.IRequest, ByVal Response As DartWebServer.IResponse)

On Error GoTo OnError ' use intrinsic error handling

Dim Variable As HttpVariable

List1.AddItem "Variables sent by the client:"

For Each Variable In Request.Variables

List1.AddItem Variable.Name & " = " & Variable.Value

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

This VB example demonstrates this property when part of a Session Object:

Private Sub WebServer1_SessionInit(ByVal Session As DartWebServer.ISession)

On Error GoTo OnError ' use intrinsic error handling

' Initialize the session variables to their starting values

' Note we are saving Variants

Session.Variables("StartTime") = Now

Session.Variables("ProcessStep") = 1

Session.Variables("Phrase") = "Big Red Dog"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Body Property Example (Response Object - WebServer Tool)

Body Property Example (Response Object)

This VB example demonstrates this property when part of a Response Object.

Private Sub WebServer1_Get(ByVal Session As DartWebServerCtl.ISession, ByVal Request As DartWebServerCtl.IRequest, ByVal Response As DartWebServerCtl.IResponse)

On Error GoTo OnError ' use intrinsic error handling

' If the request is for a certain file, change the default response

' property to our new file

If Request.FileName = "HelpMe.html" Then

Dim Page As New DartStream

Page.FileName = "NewHelpMe.html"

Page.FileMode = createExisting

Response.Body = Page

' response will now include NewHelpMe.html

Else

' do normal GET Request processing here

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Response Object Example (WebServer Tool)

Response Object Example

This VB example demonstrates changing the response to a custom value:

Private Sub WebServer1_Get(ByVal Session As DartWebServer.ISession, ByVal Request As DartWebServer.IRequest, ByVal Response As DartWebServer.IResponse)

On Error GoTo OnError ' use intrinsic error handling

' Clear the Body and construct a custom one

Dim Page As New DartStream

Page.Write "<HTML><BODY>Hello World!</BODY></HTML>"

Response.Status = httpOK

' Demonstrating sending a made up page to the client.

Response.Body = Page

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Expires Property Example (Response Object - WebServer Tool)

Expires Property Example (Response Object)

Private Sub WebServer1_Get(ByVal Session As Session, ByVal Request As Request, ByVal Response As Response)

On Error GoTo OnError ' use intrinsic error handling

'The response is valid for 2 days.

Response.Expires = Now + 2

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Send Method Example (Response Object - WebServer Tool)

Send Method Example (Response Object)

Private Sub WebServer1_Get(ByVal Session As DartWebServerCtl.ISession, ByVal Request As DartWebServerCtl.IRequest, ByVal Response As DartWebServerCtl.IResponse)

On Error GoTo OnError ' use intrinsic error handling

'Set Response.Delay to defeat default processing

Response.Delay = True

'Create an instance of a class that is multi-threaded

Dim Client As MultiThreadedClient

'Create him on his own thread

Set Client = CreateObject("MyApp.MultiThreadedClient")

'Make cross-thread call to initialize Client

Client.Initialize Session, Request, Response

'Return to WebServer Control, but Response won't be sent...

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Over in your class definition of MultiThreadedClient, you have the following code:

Public Sub Initialize(ByVal Session As DartWebServerCtl.ISession, ByVal Request As DartWebServerCtl.IRequest, ByVal Response As DartWebServerCtl.IResponse)

On Error GoTo OnError ' use intrinsic error handling

'first, initialize local class members

Set mSession = Session

Set mRequest = Request

Set mResponse = Response

'now, use a timer or some other mechanism to trigger processing...

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Public Sub TriggerProcessing()

On Error GoTo OnError ' use intrinsic error handling

'this is called on Client's thread

'start lengthy database operation or calculations...

'finally, when done, call Send method to release resources

mResponse.Send

'now, just delete self...

'...

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Status Property Example (Response Object - WebServer Tool)

Status Property Example (Response Object)

Private Sub WebServer1_Get(ByVal Session As DartWebServerCtl.ISession, ByVal Request As DartWebServerCtl.IRequest, ByVal Response As DartWebServerCtl.IResponse)

On Error GoTo OnError ' use intrinsic error handling

' check the request for a Username and Password

If Request.UserName = "" Or Request.Password = "" Then

Response.Status = httpUnauthorized

' Response.StatusText is now set to "Unauthorized"

Response.Headers.Add httpWWWAuthenticate, "Basic realm=""Login"""

Else

' do password checking, etc. here

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


StatusText Property Example (Response Object - WebServer Tool)

StatusText Property Example (Response Object)

Private Sub WebServer1_Get(ByVal Session As DartWebServerCtl.ISession, ByVal Request As DartWebServerCtl.IRequest, ByVal Response As DartWebServerCtl.IResponse)

On Error GoTo OnError ' use intrinsic error handling

' check the request for a Username and Password

If Request.UserName = "" Or Request.Password = "" Then

Response.Status = httpNoContent

Response.StatusText = "No Content is Available on Mondays"

Else

' do password checking, etc. here

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Version Property Example (Response Object - WebServer Tool)

Version Property Example (Response Object)

Private Sub WebServer1_Get(ByVal Session As DartWebServerCtl.ISession, ByVal Request As DartWebServerCtl.IRequest, ByVal Response As DartWebServerCtl.IResponse)

On Error GoTo OnError ' use intrinsic error handling

' return error for all request not using version 1.1

If Request.Version <> "1.1" Then

' send back a response telling user of wrong version

Response.Body.FileMode = createExisting

Response.Body.FileName = "WrongVersion.html"

Response.Status = httpVersionNotSupported

Else

' we have a valid version, process the request as usual

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


RowCount Property Example (SnmpTable Object)

RowCount Property Example

' Use this function to determine how many rows

' are in a table on a remote agent.

Private Function GetRowCount(ByVal TableOid As String, ByVal ColCount As Long) As Long

On Error GoTo OnError

' Get all of the first column

Dim Vars As SnmpVariables

Set Vars = GetFirstColumn(TableOid, ColCount)

If Vars Is Nothing Then Exit Function

Dim Table As SnmpTable

Set Table = Vars.GetTable(TableOid & ".1")

If Not Table Is Nothing Then

GetRowCount = Table.RowCount

Else

GetRowCount = 0

End If

Exit Function

OnError:

AddLog "COULD NOT GET ROW COUNT - ERROR #" + CStr(Err.Number) + ": " + Err.Description

End Function


RowIndex Property Example (SnmpTableRow Object)

RowIndex Property Example

Private Sub PrintDebug()

For Each Row In Table

Debug.Print " row: " & Row.RowIndex & vbCrLf

For Each var In Row

Debug.Print var.Name & " oid: " & var.oid & vbCrLf

Next

Next

End Sub


SecurePop Control Example

' create session

SecurePop1.Login "serv.dart.com", "MyUsername", "MyPassword"

' Pop1.Count now contains the number of messages on the server

' Get all messages and put them into the Pop1.Messages collection

SecurePop1.Get


SecureServer Control Example

' listen on default port 443 for connections

SecureServer1.Listen

' since no Error condition is reported, we know we succeeded

Private Sub SecureServer1_Receive(Child As DartSecureCtl.ISecureTcp)

On Error GoTo OnError ' use intrinsic error handling

Dim data As String

Child.Receive data

If Left(data, 18) = "GET / HTTP/1.0" + vbCrLf + vbCrLf Then

' process HTTP Get request...

' Response may be an HTML page, for example

Child.Send Response

' Server closes the connection after sending response

Child.Close

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Listen Method Example (SecureServer Control)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' listen on the default SSL server port

Daemon1.Listen

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Connect Method Example (SecureTcp Control)

This VB example demonstrates the use of this method:

Public Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

'Connects to port 443

SecureTcp1.Connect "secure.dart.com"

MsgBox "Connected to server!"

Exit Sub

OnError: ' Any error jumps here

' no connection within 30 seconds, or other error (Ras1.State is rasClosed)

MsgBox "Error connecting to the server."

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


SecureTcp Control Example

This VB example illustrates a typical use. It creates a simple application that connects to a secure HTTP server, sends a request, receives the reply, and waits for the server to close the connection.

Dim Reply As String

Dim Data As String

' Timeout Property defaults to 30 seconds

' Establish a secure connection with the server.

' Defaults to Port 443 (Secure)

SecureTcp1.Connect "www.dart.com"

SecureTcp1.Send "GET / HTTP/1.0" + vbCrLf + vbCrLf

While SecureTcp1.State <> tcpClosed

SecureTcp1.Receive Data

Reply = Reply + Data

Wend


Socket Property Example (SecureTcp Control)

Private Sub Daemon1_Accept()

On Error GoTo OnError ' use intrinsic error handling

'Specify the digital certificate the server will use.

Dim Store As New CertificateStore

'Get the desired certificate

SecureTcp1.Certificate = Store.Find("ROOT", locationLocalMachine, g_SavedIssuedBy, g_SavedSerialNumber)

'Accept the socket...the Timeout Property is automatically set to 0

SecureTcp1.Socket = Daemon1.Accept

'SecureTcp1 will negotiate a secure connection with the client...

'State Event will fire when authentication completes

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Server Control Example

' listen on port 7 for connections

Server1.Listen 7

' since no Error condition is reported, we know we succeeded

Private Sub Server1_State(ByVal Child As DartServerCtl.ITcp)

On Error GoTo OnError ' use intrinsic error handling

If Child.State = tcpConnected Then

' send client a welcome message

Child.Send "Welcome to the Dart Server!" & vbCrLf

ElseIf Child.State = tcpClosed Then

' perform any cleanup of local data structures, because object is gone

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Private Sub Server1_Receive(ByVal Child As DartServerCtl.ITcp)

On Error GoTo OnError ' use intrinsic error handling

Dim data As String

Child.Receive data

If data = "Quit" Then

' we close the connection when the user sends a QUIT

Child.Send "Goodbye"

Child.Close

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Service Control Example

This VB example demonstrates how easily a simple echo server service can be built with the Service Control and the Server Control.

Private Sub Form_Load()

On Error GoTo OnError ' use intrinsic error handling

'Connect to the Service Control Manager

Service1.Connect

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Private Sub Service1_State()

On Error GoTo OnError ' use intrinsic error handling

Dim I As Integer

Select Case Service1.State

Case serviceRunning

' service is now running, beep to the world!

Beep

' Start the Echo Server

Server1.Listen 7

Case servicePaused

' service is now going to sleep, stop listening for new connections

Server1.Close

Case serviceResumed

' service is now waking up from sleep, resume listening!

Server1.Listen 7

Case serviceStopped

' service is now stopping, log a message to Windows event log

Service1.Log serviceInformation, serviceInfoEvent, “Stopping”

' stop listening for new connections

Server1.Close

' shut down all active connections

For I = 1 To Server1.Children.Count

Server1.Children(I).Close

Next

End Select

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Abort Method Example (Service Control)

Private Sub Stop_Myself()

On Error GoTo OnError ' use intrinsic error handling

'abort and stop my service

Service1.Abort

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Connect Method Example (Service Control)

Private Sub Form_Load()

On Error GoTo OnError ' use intrinsic error handling

'let Windows know we’re a service

Service1.Connect

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Install Method Example (Service Control)

One way to self-install a service is via a command line switch, as shown in the following VB example.

Private Sub Form_Load()

On Error GoTo OnError ' use intrinsic error handling

'if the /install command line switch is set, self-install ourselves as a service!

If LCase(Trim(Command)) = "/install" Then

'install as service "MyService"

Service1.Install "MyService"

Else

'We are running as a service! Make the Connect call to connect to the SCM

Service1.Connect

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Log Method Example (Service Control)

Private Sub Service1_State()

On Error GoTo OnError ' use intrinsic error handling

Dim I As Integer

Select Case Service1.State

Case serviceRunning

' service is now running

Service1.Log serviceInformation, serviceStarted

Case servicePaused

' service is now going to sleep

Service1.Log serviceInformation, servicePaused

Case serviceResumed

' service is now waking up from sleep, resume

Service1.Log serviceInformation, serviceResume

Case serviceStop

' service is now stopping, log a final message to Windows event log

Service1.Log serviceInformation, serviceStopped

End Select

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


State Event Example (Service Control)

Private Sub Service1_State()

On Error GoTo OnError ' use intrinsic error handling

Dim I As Integer

Select Case Service1.State

Case serviceRunning

' service is now running, beep to the world!

Beep

' Start the Echo Server

Server1.Listen 7

Case servicePaused

' service is now going to sleep, stop listening for new connections

Server1.Close

Case serviceResumed

' service is now waking up from sleep, resume listening!

Server1.Listen 7

Case serviceStopped

' service is now stopping, log a message to Windows event log

Service1.Log serviceInformation, serviceInfoEvent, "Stopping"

' stop listening for new connections

Server1.Close

' shut down all active connections

For I = 1 To Server1.Children.Count

Server1.Children(I).Close

Next

End Select

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Uninstall Method Example (Service Control)

Private Sub Form_Load()

On Error GoTo OnError ' use intrinsic error handling

'if the /uninstall command line switch is set, uninstall ourselves as a service!

If LCase(Trim(Command)) = "/uninstall" Then

'uninstall our service "MyService"

Service1.Uninstall "MyService"

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Session Object Example (WebServer Tool)

Session Object Example

Private Sub WebServer1_Get(ByVal Session As DartWebServer.ISession, ByVal Request As DartWebServer.IRequest, ByVal Response As DartWebServer.IResponse)

On Error GoTo OnError ' use intrinsic error handling

Dim Variable As HttpVariable

For Each Variable In Session.Variables

List1.AddItem Variable.Name + " " + Variable.Value

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Id Property Example (Session Object - Server Tool)

Id Property Example (Session Object)

Private Sub FtpServer1_SessionInit(ByVal Session As DartFtpServer.ISession)

On Error GoTo OnError ' use intrinsic error handling

List1.AddItem "Session " + Session.Id + " has been started."

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Id Property Example (Session Object - WebServer Tool)

Id Property Example (Session Object)

Private Sub WebServer1_SessionInit(ByVal Session As DartWebServer.ISession)

On Error GoTo OnError ' use intrinsic error handling

List1.AddItem "Session " + Session.Id + " has been started."

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


IdleTime Property Example (Session Object - Server Tool)

IdleTime Property Example (Session Object)

This VB example demonstrates resetting this property to 0 so that the session is not eliminated.

Private Sub FtpServer1_SessionEnd(Session As Session)

On Error GoTo OnError ' use intrinsic error handling

'Reset sessions IdleTime to 0 to prevent it from being killed.

Session.IdleTime = 0

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


IdleTime Property Example (Session Object - WebServer Tool)

IdleTime Property Example (Session Object)

Private Sub CheckIdleTimes(colSession As Sessions)

On Error GoTo OnError ' use intrinsic error handling

Dim Index As Long

For Index = 1 To colSessions.Count

If colSessions(Index).Variables("Delay") = True Then

' allow this session to remain idle longer than normal

colSessions(Index).IdleTime = 0

ElseIf colSessions(Index).Variables("Remove") = True Then

' allow this timeout right now

colSessions(Index).IdleTime = 20

End If

Next Index

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


User Property Example (Session Object - Server Tool)

User Property Example (Session Object)

Private Sub FtpServer1_Login (ByVal Request As DartFtpServerCtl.IRequest, ByVal Response As DartFtpServerCtl.IResponse)

On Error GoTo OnError ' use intrinsic error handling

If (Request.Session.User.Name <> "username") Or _

(Request.Session.User.Password <> "password") Then

' Do not allow login.

Set Request.Session.User = Nothing

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

This VB example demonstrates the use of this property for custom authentication.

Private Sub FtpServer1_Command (ByVal Cmd As String, ByVal Request As DartFtpServerCtl.IRequest, ByVal Response As DartFtpServerCtl.IResponse)

On Error GoTo OnError ' use intrinsic error handling

If Cmd = "FOO" Then

Dim Usr As New User

' Set the User property to indicate this session is an

' authenticated session.

Set Request.Session.User = Usr

Response.Status = 230

Response.StatusText = "User is authenticated."

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

The following protocol example demonstrates the above example:

C - Client S - Server

C: (Connects to server)

S: 220 Welcome to my server.

C: FOO

S: 230 User is authenticated.


Variables Property Example (Session Object - Server Tool)

Variables Property Example (Session Object)

Private Sub FtpServer1_SessionInit(ByVal Session As DartFtpServer.ISession)

On Error GoTo OnError ' use intrinsic error handling

' Initialize the session variables to their starting values

' Note we are saving Variants

Session.Variables("StartTime") = Now

Session.Variables("ProcessStep") = 1

Session.Variables("Phrase") = "Big Red Dog"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Item Method Example (Sessions Object - WebServer Tool)

Item Method Example (Sessions Object)

Private Sub cmdRemoveSession(colSessions As Sessions, User As String)

On Error GoTo OnError ' use intrinsic error handling

Dim s As Session

Dim Pos As Long

For Pos = 1 To colSessions.Count

' look for a session variable of "Username" with the passed name

If colSessions(Pos).Variables("Username") = User Then

colSessions.Remove (Pos)

End If

Next Pos

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Remove Method Example (Sessions Object - Server Tool)

Remove Method Example (Sessions Object)

This VB example illustrates how to remove a session from the collection.

Private Sub cmdRemoveSession(colSessions As Sessions, User As String)

On Error GoTo OnError ' use intrinsic error handling

Dim s As Session

Dim Pos As Long

Pos = 1

For Each s In colSessions

' look for a session variable of "Username" with the passed name

If s.Variables("Username") = User Then

colSessions.Remove (Pos)

End If

Pos = Pos + 1

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Remove Method Example (Sessions Object - WebServer Tool)

Remove Method Example (Sessions Object)

This VB example illustrates how to remove a session from the collection.

Private Sub cmdRemoveSession(colSessions As Sessions, User As String)

On Error GoTo OnError ' use intrinsic error handling

Dim s As Session

Dim Pos As Long

Pos = 1

For Each s In colSessions

' look for a session variable of "Username" with the passed name

If s.Variables("Username") = User Then

colSessions.Remove (Pos)

End If

Pos = Pos + 1

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Command Method Example (SMTP Control)

This VB example shows how to send protocol commands to the server.

Private Sub Command1_Click()

Dim Reply As String

On Error GoTo OnError ' use intrinsic error handling

' login to the server

Smtp1.Login "smtp.test.com"

' send an SMTP Verify command

Smtp1.Command "VRFY user@test.com", Reply

MsgBox "Verify Result: " & Reply

' send an SMTP Expand command

Smtp1.Command "EXPN SomeList", Reply

MsgBox "Expand Result: " & Reply

' send a NOOP Command

Smtp1.Command "NOOP", Reply

MsgBox "Noop Response: " & Reply

' send a SMTP Help Command

Smtp1.Command "HELP", Reply

MsgBox "Help Response: " & Reply

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


SMTP Control Example

This VB example builds and sends a test message using a dynamically created component.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' build and send a message

Dim Mail As New Smtp

Mail.QuickSend "Tom@Test.com", "Dave@Test.com", _

"Requested files", "I have attached your requested files.", _

"Budget.xls; Budget.doc", "smtp.test.com"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


From Property Example (SMTP Control)

This VB example demonstrates this property, overriding the determination of the sender from the message.

Smtp1.Login "smtp.test.com"

Smtp1.From = "test@test.com"

Smtp1.Message.To.Add = "Tom@test.com"

Smtp1.Message.Subject = "Big Adventure!"

Smtp1.Message.From = "Dave@test.com"

Smtp1.Message.Text = "This award winning show is on Sunday night at 8"

' The message return path information will be set to test@test.com

Smtp1.Send

Smtp1.Logout


Login Method Example (SMTP Control)

This VB example illustrates logging into an SMTP server using blocking operation.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Smtp1.Login "smtp.test.com" ' allow other parameters to default

MsgBox "The following capabilities are supported by the server: " & vbCrLf & _

Smtp1.Capabilities.All ' capabilities are now valid

Smtp1.Logout ' end session

MsgBox "Session Completed" ' no errors generated gets us here

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Logout Method Example (SMTP Control)

Refer to the SMTP Control Login Method Example topic for an example of how to log out.


Message Property Example (SMTP Control)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim msg As New Message

Dim msg2 As New Message

' load two messages

msg.Load "C:\Test1.msg"

msg2.Load "C:\Test2.msg"

Smtp1.Login "smtp.test.com"

Smtp1.Message = msg ' set the first message

Smtp1.Send ' send the first message

Smtp1.Message = msg2 ' set the second message

Smtp1.Send ' send the second message

Smtp1.Logout

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Progress Event Example (SMTP Control)

This VB example shows how to use the Progress event to send mail, log out, and display progress to the user.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Smtp1.Login "smtp.test.com" ' start the mail session

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Private Sub Smtp1_Progress(ByVal Method As DartMailCtl.SmtpMethodConstants, ByVal Status As DartMailCtl.SmtpStatusConstants, ByVal Reply As String, ByVal Count As Long, ByVal Size As Long)

On Error GoTo OnError ' use intrinsic error handling

If Status = smtpOk Then

Select Case Method

Case smtpLogin

' logged in, mail a message from disk

Smtp1.Send "C:\Test.msg"

Case smtpSend

' mail send is complete, log out

Smtp1.Logout

Case smtpLogout

' operation complete

End Select

ElseIf Status = smtpSending Then

' udpate the progress for the user

Label1.Caption = CDbl(Count) / CDbl(Size) * 100

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


QuickSend Method Example (SMTP Control)

This VB example shows how to build and send a message in one step.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' build message, login, send message, and logout

Smtp1.QuickSend "mary@test.com, john@othercompany.com", "steve@test.com", _

"Requested Files", "Here are the files you requested.", _

"C:\Test.gif; C:\Sample.txt", "smtp1.test.com"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Reset Method Example (SMTP Control)

This VB example shows how to reset the session under blocking operation.

Private Sub Command1_Click()

On Error GoTo OnError

Smtp1.Login "smtp.test.com" ' create a session

'do SMTP processing

Smtp1.Send "c:\temp\test.msg"

Smtp1.Logout ' end session

' no errors generated gets us here

Exit Sub

OnError: ' Any error jumps here

Smtp1.Reset

MsgBox "Reset Complete."

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Send Method Example (SMTP Control)

This VB example shows how to send a mail message using blocking operation.

Private Sub Command1_Click()

On Error GoTo OnError

Smtp1.Message.To.Add "user@test.com"

Smtp1.Message.Subject = "Test Message"

Smtp1.Message.Text = "This is a test." ' add message body

Smtp1.Message.AddAttachment "C:\company.gif" ' add attachment

Smtp1.Login "smtp.server.com" ' start the mail session

Smtp1.Send ' send message

Smtp1.Logout ' end session

MsgBox "Message Sent!" ' no errors generated gets us here

Exit Sub

OnError:

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


To Property Example (SMTP Control)

This VB example demonstrates this property, overriding the mail recipients found in the message header.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Smtp1.Login "smtp.test.com"

' add two recipients to envelope

Smtp1.To.Add = "bill@dart.com; ted@dart.com"

Smtp1.Message.To.Add = "programmers@dart.com"

Smtp1.Message.Subject = "Big Adventure!"

Smtp1.Message.Text = "This award winning show is on Sunday night at 8"

' send the message to bill & ted

Smtp1.Send

Smtp1.Logout

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Community Property Example (SnmpMessage Object)

For requests, this property must match the community name on the agent. For responses, it must match the community name on the manager. The default value is "public". The VB example shows matching community values for the Agent Control and the Manager Control.

Manager Example:

Dim Message As New SnmpMessage

Message.Community = "MyPassword"

.

.

Agent Example:

Message.Decode Packet

If Message.Community = "MyPassword" Then

'The message is ok. Process it.

Else

'Authorization failed. May want to send a trap now.

End If


Decode Method Example (SnmpMessage Object)

This VB example illustrates how the response from a "GetRequest" is processed.

Dim Message As New SnmpMessage

Dim Packet() As Byte

Dim Variable As SnmpVariable

' Udp1 accepts the reply from the SNMP agent

Udp1.Receive Packet

' Decode the packet

Message.Decode Packet

For Each Variable In Message.Variables

List1.AddItem Variable.Oid + " : " + Variable.Value

Next


Encode Method Example (SnmpMessage Object)

This VB example illustrates a simple SNMP manager application that sends a version 1 GetRequest message to an agent and captures the response.

Dim Message As New SnmpMessage

Dim Variable As New SnmpVariable

Dim Udp As New Udp

Dim Packet() As Byte

Message.Type = snmpGet1

' add the OID(s) we wish to get

Variable.Oid = "1.3.6.1.2.1.1.1.0"

Message.Variables.Add Variable

' Open a port...any will do for an SNMP manager

Udp.Open

' Encode the packet into a Byte array

Message.Encode Packet

' Send the message to port 161, the default port for SNMP agents

Udp.Send Packet, "my.snmp.agent", 161

' Block for up to a second and get the reply

Udp.Timeout = 1000

Udp.Receive Packet

' Decode the packet

Message.Decode Packet

' Put the variable value into a text box for viewing

Text1.Text = Message.Variables(1).Oid + " : " + Message.Variables(1).Value


Enterprise Property Example (SnmpMessage Object)

Manager VB Example:

Message.Decode Packet

If Message.Enterprise = "1.3.6.1.2.1.1" Then

'The trap was generated by the system branch of the MIB tree.

Else

'Check for other branches here.

End If

Agent VB Example:

Dim Message As New SnmpMessage

'Indicate that the system branch of the MIB tree generated this trap.

Message.Enterprise = "1.3.6.1.2.1.1"

.

.


SnmpMessage Object Example

This VB example illustrates a simple application that receives a message from an agent and puts the values of the variables into a list box.

Dim Message As New SnmpMessage

Dim Variable As New SnmpVariable

Dim Packet() As Byte

' Udp1 accepts a reply from an SNMP agent

Udp1.Receive Packet

' Use the Decode method to decode the message

Message.Decode Packet

For Each Variable In Message.Variables

List1.AddItem Variable.Oid & ": " & Variable.Value

Next


Exception Property Example (SnmpMessage Object)

Manager VB Example:

Dim Message As New SnmpMessage

Message.Decode Packet

If Message.Exception = snmpOk Then

' No Error occurred, go on

Else

List1.AddItem "Error in Variable #" & Message.ExceptionIndex

End If

.

.

.

Agent VB Example:

' Variable 1 does not exist.

Message.Exception = snmpNoSuchName

Message.ExceptionIndex = 1


ExceptionIndex Property Example (SnmpMessage Object)

Manager VB Example:

Dim Message As New SnmpMessage

Message.Decode Packet

If Message.Exception = snmpOk Then

' No Error occurred, go on

Else

List1.AddItem "Error in Variable #" & Message.ExceptionIndex

End If

.

.

.

Agent VB Example:

' Variable 1 does not exist.

Message.Exception = snmpNoSuchName

Message.ExceptionIndex = 1


SnmpMib Object Compile Example

Compile Example

Private Sub CompileMibs()

Dim Mib As New SnmpMib

Dim MibList As New DartStrings

' Add Mibs to Dartstrings Collection (Order does not matter)

MibList.Add "smi.mib"

MibList.Add "mib_ii.mib"

MibList.Add "traps.mib"

' Compile all Mibs in Collection

Mib.Compile MibList

'Add Variable Names to a Listbox

Dim v

For Each v In Mib.Variables

lstVariables.AddItem v.Name

Next

End Sub


SnmpMib Object Example

This VB example demonstrates cross-referencing a MIB object when receiving a trap to display a description of the trap.

Dim Message As SnmpMessage

Dim Trap As SnmpTrap

Dim Mib As SnmpMib

Dim Packet() As Byte

Mib.Load "c:\MIBs\Dart.mib"

Udp1.Receive Packet

Message.Decode Packet

For Each Trap In Mib.Traps

If Trap.Enterprise = Message.Enterprise Then

If Trap.SpecificTrap = Message.SpecificTrap Then

List1.AddItem Trap.Description

End If

End If

Next


SnmpTable Object Example

Private Sub Command1_Click()

Dim Mib As New SnmpMib

Dim var As New SnmpVariable

Dim v As SnmpVariable

Dim Table As SnmpTable

Dim strings As New DartStrings

Dim Row As SnmpTableRow

strings.Add (App.Path & "\" & "traps.mib")

strings.Add (App.Path & "\" & "mib_ii.mib")

strings.Add (App.Path & "\" & "smi.mib")

Dim oid As String

Mib.Compile strings

Set Vars = New SnmpVariables

'Getting the ifTable size

oid = Mib.Variables.GetOIDFromName("ifTable")

oid = Mib.Variables.GetNext(oid).oid

Set Table = Mib.Variables.GetTable(oid)

'after ifentry, the row object-type, comes the variables

If Not Table Is Nothing Then

var.oid = oid & ".0"

var.Repeat = True

Manager1.Message.Reset

Manager1.Message.Variables.Add var

Manager1.Message.MaxRepetition = Table.ColumnCount

'Get a row from all agents on the network

Manager1.AgentName = "255.255.255.255"

Manager1.Message.Type = snmpGetBulk2

Manager1.Open

Manager1.Send

Set var = Nothing

'Getting the ifTable

Set Table = Vars.GetTable(oid)

Debug.Print vbCrLf & "count " & Table.RowCount

For Each Row In Table

Debug.Print " row: " & Row.RowIndex & vbCrLf

For Each var In Row

Debug.Print var.Name & " oid: " & var.oid & vbCrLf

Next

Next

Debug.Print "finalrow: " & vbCrLf

Set Row = Vars.GetTableRow("1.3.6.1.2.1.2.2.1.11")

For Each var In Row

Debug.Print var.Name & " oid: " & var.oid & vbCrLf

Next

End If

End Sub


SnmpTableRow Object Example

Private Function GetColumnCount(ByVal TableOid As String) As Long

Dim Row As SnmpTableRow

' Get a row from the local MIB

Set Row = Mib.Variables.GetTableRow(TableOid & ".1")

If Not Row Is Nothing Then

GetColumnCount = Row.ColumnCount

Else

GetColumnCount = 0

End If

End Function


SnmpTraps Object Example

Dim Trap As SnmpTrap

For Each Trap In Mib.Traps

List1.AddItem Trap.Description

Next

The count of SnmpTrap objects in a collection is returned by:

TrapCount = Mib.Traps.Count

Therefore, the above iteration could also be performed as:

Dim I As Long

For I = 1 To Mib.Traps.Count

List1.AddItem Mib.Traps(I).Description

Next

Because the Item index can be passed a Trap name, specific entries can also be accessed:

List1.AddItem Mib.Traps("colStart").Description

The Add method can be used to add an object to the collection, as the following VB example demonstrates:

Dim Trap As New SnmpTrap

Mib.Traps.Add Trap


SnmpVariables Object Example

Dim Variable As SnmpVariable

Dim Message As SnmpMessage

For Each Variable In Message.Variables

List1.AddItem Variable.Value

Next

The number of objects in the collection is returned by:

VariableCount = Message.Variables.Count

The above iteration could also be performed by:

Dim I As Integer

For I = 1 To Message.Variables.Count

List1.AddItem Message.Variables(I).Value

Next

Because the Item index can also be an OID or Name, entries can be accessed as follows:

List1.AddItem Message.Variables("1.3.6.1.2.1.1.1.0").Value

The Add method can be used to add an object to the collection, as the following VB example demonstrates:

Dim Variable As New SnmpVariable

Message.Variables.Add Variable

The Remove method can be used to remove an object from the collection, as the following VB example demonstrates:

'Removes the object at index 1

Message.Variables.Remove 1

Because the Remove index can be passed an OID or Name, specific entries can be accessed such as:

'Removes the reference OID

Message.Variables.Remove "1.3.6.1.2.1.1.1.0"

The Clear method can be used to remove all objects from the collection, as the following VB example demonstrates:

'Removes all objects.

Message.Variables.Clear


System Object Example

This VB example illustrates a simple application that lists the Winsock system information in a list box.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim System As New System

List1.AddItem System.Description

List1.AddItem System.Status

List1.AddItem Str$(System.MajorVersion) + "." + Str$(System.MinorVersion)

List1.AddItem "Local name: " & System.Name

Dim Address As Variant

For Each Address In System.Addresses

List1.AddItem "Address: " & Address

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


TableOID Property Example (SnmpTable Object)

TableOID Property Example

Private Sub SetHeadings(ByVal Table as SnmpTable)

Dim r As Long

Dim c As Long

Dim Row As SnmpTableRow

For c = 1 To Table.ColumnCount

SetColumnHeader c, Table.TableOid

For r = 1 To Table.RowCount

Set Row = Table(r)

Set Var = Row(c)

SetItem r, c, Var

Next r

Next c

End Sub


TCP Control Example

This VB example shows a simple application that connects to an echo server, sends a character, receives the echoed reply, and then closes the connection.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Reply As String

' Set Timeout to 1000 milliseconds to wait on communications for program execution

Tcp1.Timeout = 1000

' Establish a connection to an echo server that repeats back what it receives

' "myhostname" is the host address, and 7 indicates the echo port

Tcp1.Connect "myhostname", 7

' Since no Error condition is reported, we know we succeeded: send a string

Tcp1.Send "!"

Tcp1.Receive Reply

If Reply = "!" Then MsgBox "Success!"

' Close the connection

Tcp1.Close

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Search Method Example (TCP Control)

Function FetchNextLine() As String

On Error GoTo OnError ' use intrinsic error handling

Dim Line As String

Dim LineLength As Long

' Get the next line from server, which ends with a carriage-return, line-feed

Tcp1.Timeout = 1000

LineLength = Tcp1.Search(Line, vbCrLf)

FetchNextLine = Line

' if no error generated, Line is guaranteed to have the next line

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Receive Method Example (Telnet Control)

This VB example shows how to establish a Telnet connection and view the details in a VT Control.

Private Sub Telnet1_Receive()

On Error GoTo OnError ' use intrinsic error handling

Dim s() As Byte

Dim r As Long

' when data arrives, receive it and put it into the VT Control

r = Telnet1.Receive(s)

If r > 0 Then

Vt1.Display s

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Rexec Method Example (Telnet Control)

Blocking Example:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Telnet1.Timeout = 30000

Telnet1.Rexec "myhost", "myUsername", "myPassword", "reboot" 'reboot UNIX host

' didn't go to OnError, so we connected and executed command before 30 seconds elapsed!

Dim Output As String

' Telnet1.State should be tcpClosing at this point

Telnet1.Receive Output

' Telnet1.State should be tcpClosed at this point

' First character is completion code, so strip it off and display rest

Text1.Text = Right(Output, Len(Output)-1)

Exit Sub

OnError: ' Any error jumps here

' no connection within 30 seconds, or other error (Telnet1.State is tcpClosed)

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Non-Blocking Example:

Private Sub Command1_Click()

' intrinsic error handling is of limited value for asynchronous connection&ldots;

Telnet1.Timeout = 0

'connect and start executing listing followed by the date command

'this demonstrates executing multiple commands

Telnet1.Rexec "myhost", "myUsername", "myPassword", "ls –la; date"

End Sub

Private Sub Telnet1_State()

If Telnet1.State = tcpConnected Then MsgBox "Connected!"

End Sub

Private Sub Telnet1_Receive()

Dim Output As String

Telnet1.Receive Output

' First character is completion code, so strip it off and display rest

Text1.Text = Right(Output, Len(Output)-1)

End Sub


Rlogin Method Example (Telnet Control)

Blocking Example:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Telnet1.Timeout = 1000

Telnet1.Rlogin "myhost", "myUsername"

' didn't go to OnError, so we connected before 30 seconds elapsed!

MsgBox "Connected!"

Dim Output As String

Telnet1.Receive Output

Text1.Text = Output

Exit Sub

OnError: ' Any error jumps here

' no connection within 1 second, or other error (Tcp1.State is tcpClosed)

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Non-Blocking Example:

Private Sub Command1_Click()

' intrinsic error handling is of limited value for asynchronous connection&ldots;

Telnet1.Timeout = 0

Telnet1.Rlogin "myhost", "myUsername"

End Sub

Private Sub Telnet1_State()

If Telnet1.State = tcpConnected Then MsgBox "Connected!"

End Sub

Private Sub Telnet1_Receive()

Dim Output As String

Telnet1.Receive Output

Text1.Text = Output

End Sub


Rsh Method Example (Telnet Control)

Blocking Example:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Telnet1.Timeout = 1000

Telnet1.Rsh "myhost", "myUsername", "reboot" 'reboot remote UNIX host

' didn't go to OnError, so we connected and execute listing before 30 seconds elapsed!

Exit Sub

OnError: ' Any error jumps here

' no connection within 30 seconds, or other error (Tcp1.State is tcpClosed)

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Non-Blocking Example:

Private Sub Command1_Click()

Telnet1.Timeout = 0

'connect and start executing listing followed by the date command

'this demonstrates executing multiple commands

Telnet1.Rsh "myhost", "myUsername", "ls –la; date"

End Sub

Private Sub Telnet1_State()

If Telnet1.State = tcpConnected Then MsgBox "Connected!"

End Sub

Private Sub Telnet1_Receive()

Dim Output As String

Telnet1.Receive Output

Text1.Text = Output

End Sub


UDP Control Example

This VB example illustrates a simple application that sends a datagram to a UDP echo server and displays the response.

Private Sub Command1_Click()

Dim uResponse As String

Dim uAddress As String

Dim uPort As String

Udp1.Timeout = 0

'LocalPort defaults to 0... system will assign an unused (ephemeral) port

Udp1.Open

' Send a datagram to www.dart.com, echo port 7

Udp1.Send "Send me an echo", "www.dart.com", 7

' uResponse will by dynamically expanded and filled with the echo response

Udp1.Receive uResponse

uAddress = Udp1.LocalAddress

uPort = Udp1.LocalPort

'display address and port information in message box

dMsg = d & vbCrLf

dMsg = dMsg & "LocalAddress is " & uAddress & vbCrLf

dMsg = dMsg & "LocalPort is " & uPort

MsgBox dMsg

End Sub


Join Method Example (UDP Control)

This VB example shows how to join a multicast group.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' specify we want port 4567

Udp1.Open 4567

' join the group at 239.255.255.254

Udp1.Join "239.255.255.254"

List1.AddItem "Joined: 239.255.255.254"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Receive Event Example (UDP Control)

Private Sub Udp1_Receive()

On Error GoTo OnError ' use intrinsic error handling

Dim s As String

Tcp1.Receive s ' receive a datagram into a String

Text1.SelText = s ' append received data into the text box

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


CurrentPath Property Example (User Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim S As Session

For Each Session In FtpServer1.Sessions

List1.AddItem S.User.CurrentPath

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Name Property Example (User Object)

Private Sub FtpServer1_Login(Session As Session, Request As Request, Response As Response)

On Error GoTo OnError ' use intrinsic error handling

If (Session.User.Name <> "username") Or _

(Session.User.Password <> "password") Then

' Do not allow login

Set Session.User = Nothing

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Password Property Example (User Object)

Private Sub FtpServer1_Login(Session As Session, Request As Request, Response As Response)

On Error GoTo OnError ' use intrinsic error handling

If (Session.User.Name <> "username") Or _

(Session.User.Password <> "password") Then

' Do not allow login

Set Session.User = Nothing

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


hWnd Property Example (VT Control)

This VB example shows how to get the process ID from the window handle.

Function ProcIDFromWnd(ByVal hWnd As Long) As Long

Dim idProc As Long

Call GetWindowThreadProcessId(hWnd, idProc)

ProcIDFromWnd = idProc

End Function

ProcessID = ProcIDFromWnd(Vt1.hWnd)


Authenticate Event Example

This VB example demonstrates allowing a user to override default security options.

Private Sub WebASP1_Authenticate(ByVal RemoteCertificate As DartWebASPCtl.ICertificate, ByVal TrustedRoot As Boolean, ByVal ValidDate As Boolean, ByVal ValidSignature As Boolean, ByVal ValidName As Boolean, Valid As Boolean)
Dim Msg As String

' Check various parts of the certificate to give the user a chance

' cancel if desired.

If Not Valid Then

If Not ValidDate Then Msg = Msg + "- Certificate date is invalid" + vbCrLf

If Not TrustedRoot Then Msg = Msg + "- Certificate Authority is not trusted" + vbCrLf

If Not ValidSignature Then Msg = Msg + "- Certificate does not contain a valid signature" + vbCrLf

If Not ValidName Then Msg = Msg + "- The name on the security certificate does not match the name of the site" + vbCrLf

End If

If Msg <> "" Then

Msg = "The following conditions are true:" + vbCrLf + vbCrLf + Msg + vbCrLf + vbCrLf

Msg = Msg + "Do you still wish to authenticate?"

If MsgBox(Msg, vbYesNo + vbExclamation, "Security Alert") = vbYes Then

Valid = True

End If

End If
End Sub


WebASP Control Example

Visual Basic Example

Private Sub GetTest_Clicked()

WebASP1.Timeout = 30000

'Reset the Request Message

WebASP1.Request.Content = ""

' fill in the request body

WebASP1.Request.Url = "www.test.com/testweb.html"

WebASP1.Get

'check the result

If WebASP1.Response.Status = 200 Then

' good response from server

' save it to a file

WebASP1.Response.Body.Filename = "C:\temp\TestWeb.txt"

End If

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

Dim s

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebASP1.Timeout = 30000

'Reset the Request Message

WebASP1.Request.Content = ""

' fill in the request body

WebASP1.Request.Url = "www.dart.com"

WebASP1.Get

'check the result

If WebASP1.Response.Status = 200 Then

' good response from server

' write result to web page

s = WebASP1.Response.Body.ReadString

Response.Write s

End If

End Sub

%


Protocol Property Example (WebASP Control)

Visual Basic Example

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Detect and use any supported protocol to establish

' a secure connection.

WebASP1.Protocol = securePCT

WebASP1.Request.Url = "secure.dart.com"

WebASP1.Get

' Display headers in message box to see if successful

MsgBox WebASP1.Response.Header.All

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub ProtocolTest()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

' Detect and use any supported protocol to establish

' a secure connection.

WebASP1.Timeout = 30000

WebASP1.Protocol = securePCT

WebASP1.Request.Url = "www.test.com/testweb"

WebASP1.Get

' Display status to see if successful

Response.Write "Response: " & WebASP1.Response.Status & "-" & WebASP1.Response.StatusText

End Sub

%>


ProxyHost Property Example (WebASP Control)

ProxyHost Property Example

Visual Basic Example

Sub ProxyTest_Click()

' specify the proxy server to be used

WebASP1.ProxyHost = "proxy.test.com"

' add in the Username/Password sent to the proxy on requests

WebASP1.ProxyUsername = "ProxyUser1"

WebASP1.ProxyPassword = "ProxyPass1"

' get a page

WebASP1.Request.Url = "www.test.com\testweb.html"

WebASP1.Get

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebAsp.1")

' Detect and use any supported protocol to establish

' a secure connection.

WebASP1.Timeout = 30000

WebASP1.ProxyHost = "www.proxy.test.com"

WebASP1.ProxyPort = "8080"

WebASP1.ProxyUsername = "user"

WebASP1.ProxyPassword = "pass"

WebASP1.ProxyType = ptProxySocks5

WebASP1.Get

' Display headers to see if successful

Response.Write WebASP1.Response.Header.All & "<br>"

Response.Write WebASP1.Response.Status

end sub

%>


ProxyPassword Property Example (WebASP Control)

ProxyPassword Property Example

Visual Basic Example

Sub ProxyTest_Click()

' specify the proxy server to be used

WebASP1.ProxyHost = "proxy.test.com"

' add in the Username/Password sent to the proxy on requests

WebASP1.ProxyUsername = "ProxyUser1"

WebASP1.ProxyPassword = "ProxyPass1"

' get a page

WebASP1.Request.Url = "www.test.com\testweb.html"

WebASP1.Get

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebAsp.1")

' Detect and use any supported protocol to establish

' a secure connection.

WebASP1.Timeout = 30000

WebASP1.ProxyHost = "www.proxy.test.com"

WebASP1.ProxyPort = "8080"

WebASP1.ProxyUsername = "user"

WebASP1.ProxyPassword = "pass"

WebASP1.ProxyType = ptProxySocks5

WebASP1.Get

' Display headers to see if successful

Response.Write WebASP1.Response.Header.All & "<br>"

Response.Write WebASP1.Response.Status

end sub

%>


ProxyPort Property Example (WebASP Control)

ProxyPort Property Example

Visual Basic Example

Private Sub ProxyTest_Click()

' specify a proxy

WebASP1.ProxyHost = "proxy.test.com"

' specify a port

WebASP1.ProxyPort = "8080"

WebASP1.Request.Url = "www.test.com/testweb"

WebASP1.Get

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebAsp.1")

' Detect and use any supported protocol to establish

' a secure connection.

WebASP1.Timeout = 30000

WebASP1.ProxyHost = "www.proxy.test.com"

WebASP1.ProxyPort = "8080"

WebASP1.ProxyUsername = "user"

WebASP1.ProxyPassword = "pass"

WebASP1.ProxyType = ptProxySocks5

WebASP1.Get

' Display headers to see if successful

Response.Write WebASP1.Response.Header.All & "<br>"

Response.Write WebASP1.Response.Status

end sub

%>


ProxyType Property Example (WebASP Control)

ProxyType Property Example

Visual Basic Example

Private Sub ProxyTest_Click()

' specify the proxy server to be used

WebASP1.ProxyHost = "proxy.test.com"

WebASP1.ProxyType = ptSocks4

' add in the Username/Password sent to the proxy on requests

WebASP1.ProxyUsername = "ProxyUser1"

WebASP1.ProxyPassword = "ProxyPass1"

' get a page

WebASP1.Request.Url = "www.test.com\testweb.html"

WebASP1.Get

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebAsp.1")

' Detect and use any supported protocol to establish

' a secure connection.

WebASP1.Timeout = 30000

WebASP1.ProxyHost = "www.proxy.test.com"

WebASP1.ProxyPort = "8080"

WebASP1.ProxyUsername = "user"

WebASP1.ProxyPassword = "pass"

WebASP1.ProxyType = ptProxySocks5

WebASP1.Get

' Display headers to see if successful

Response.Write WebASP1.Response.Header.All & "<br>"

Response.Write WebASP1.Response.Status

end sub

%>


ProxyUsername Property Example (WebASP Control)

ProxyUsername Property Example

Visual Basic Example

Sub ProxyTest_Click()

' specify the proxy server to be used

WebASP1.ProxyHost = "proxy.test.com"

' add in the Username/Password sent to the proxy on requests

WebASP1.ProxyUsername = "ProxyUser1"

WebASP1.ProxyPassword = "ProxyPass1"

' get a page

WebASP1.Request.Url = "www.test.com\testweb.html"

WebASP1.Get

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebAsp.1")

' Detect and use any supported protocol to establish

' a secure connection.

WebASP1.Timeout = 30000

WebASP1.ProxyHost = "www.proxy.test.com"

WebASP1.ProxyPort = "8080"

WebASP1.ProxyUsername = "user"

WebASP1.ProxyPassword = "pass"

WebASP1.ProxyType = ptProxySocks5

WebASP1.Get

' Display headers to see if successful

Response.Write WebASP1.Response.Header.All & "<br>"

Response.Write WebASP1.Response.Status

end sub

%>


Security Property Example (WebASP Control)

Private Sub Command1_Click()

WebASP1.Redirect = True

' set to accept all certificates passed from the server

WebASP1.Security = webSecureDisable

' set request url

WebASP1.Request.Url = "http://www.test.com/secureweb"

WebASP1.Get

' check server response

MsgBox WebASP1.Response.Status

WebASP1.Redirect = True

' set to check certificates

WebASP1.Security = webSecureNormal

WebASP1.Request.Url = "http://www.test.com/secureweb"

WebASP1.Get

'check server response

MsgBox WebASP1.Response.Status

End Sub


State Event Example (WebASP Control)

Private Sub WebASP1_State()

On Error GoTo OnError ' use intrinsic error handling

' State of the WebAsp1 connection has changed...put up user feedback

Select Case WebASP1.State

Case 1 'tcpConnecting

Label1.Caption = "Client Connecting..."

Case 2 'tcpConnected

Label1.Caption = "Client Connected"

Case 3 'tcpClosing

Label1.Caption = "Client Closing..."

Case 0 'tcpClosed

Label1.Caption = "Client Closed"

End Select

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Redirect Event Example

This VB example demonstrates allowing a user to decide whether to redirect.

Private Sub WebASP1_Redirect(ByVal SecureSource As Boolean, ByVal SecureDestination As Boolean, Allow As Boolean)

Dim Msg As String

' Check various parts of the certificate to give the user a chance

' cancel if desired.

If Not Allow Then

If Not SecureSource And SecureDestination Then Msg = "Allow redirection to secure page?" + vbCrLf

If SecureSource And Not SecureDestination Then Msg = "Allow redirection to non-secure page?" + vbCrLf

End If

If Msg <> "" Then

If MsgBox(Msg, vbYesNo + vbExclamation, "Security Alert") = vbYes Then

Allow = True

End If

End If
End Sub


Web Enterprise Tool SOAP Sample

Private Sub Execute(ByVal Method As String)

Dim sSOAPAction As String 'The SOAP Action - usually implies the method to execute

Dim Serializer As SoapSerializer 'The MS SOAP Serializer - creates the SOAP message

Dim Reader As SoapReader 'The MS SOAP Reader - reads the returned response from the server

On Error GoTo ErrorHandler

'Build the SOAP Action description

sSOAPAction = "SOAPAction: " & """" & BASE_SOAP_ACTION_URI & Method & """"

'Make sure you are using HTTP 1.1

WebASP1.Request.Version = webHTTP11

'Set the URL of the WSDL file

WebASP1.Request.Url = txtEndPoint.Text

'Add a unique header for the SOAP Action

WebASP1.Request.Header.Add httpNull, sSOAPAction, True

'Set the Content-Type header to read text/xml

WebASP1.Request.Header.Add httpContentType, "text/xml", True

'Pass the request that is going to be created to the Serializer

Set Serializer = New SoapSerializer

Serializer.Init WebASP1.Request

'Create the SOAP body using the Serializer

Serializer.startEnvelope

Serializer.startBody

Serializer.startElement Method, WRAPPER_ELEMENT_NAMESPACE, , "m"

Serializer.startElement "A"

Serializer.writeString txtA.Text

Serializer.endElement

Serializer.startElement "B"

Serializer.writeString txtB.Text

Serializer.endElement

Serializer.endElement

Serializer.endBody

Serializer.endEnvelope

'The Serializer has now written the appropriate data into the Request

'so the SOAP message can now be posted to the server

WebASP1.Post

'Load the Response from the server into the Reader. Remember that since this

'is a SOAP message the body is all XML

Set Reader = New SoapReader

Reader.loadXML WebASP1.Response.Body.ReadString

WebASP1.Request.Body.Clear

If Not Reader.Fault Is Nothing Then

MsgBox Reader.faultstring.Text, vbExclamation

Else

txtEquals.Text = Reader.RPCResult.Text

End If

Exit Sub

ErrorHandler:

MsgBox "ERROR: " & Err.Description, vbExclamation

End Sub


KeepAlive Property Example (WebMessage Object - WebASP Tool)

KeepAlive Property Example (WebMessage Object)

Visual Basic Example

Sub CheckImages(Image As DartStrings)

Dim i As Integer

WebASP1.Request.Version = webHTTP11

WebASP1.Request.KeepAlive = True

WebASP1.Timeout = 30000

' this first request establishes a connection to the server

' and leaves it open after the response is received

WebASP1.Request.Url = Image(1)

WebASP1.Head

List1.AddItem WebASP1.Response.Header.All

' these next connections will use the established connection

For i = 2 To Image.Count

WebASP1.Request.Url = Image(i)

WebASP1.Head

List1.AddItem WebASP1.Response.Header.All

Next i

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub CloseTest()

on error resume next

Set WebASP1 = Server.CreateObject("Dart.Web.1")

WebASP1.Timeout = 10000

WebASP1.Request.KeepAlive = True

WebASP1.Request.Url = "www.test.com"

' connection will stay open for all 3 GETs

WebASP1.Get

If err = 0 then

Response.Write ("Successful GET 1 <br>")

else

Response.Write ("error GET 1 <br> ")

End if

WebASP1.Request.Url = "www.test.com/page1.asp"

WebASP1.Get

If err = 0 then

Response.Write ("Successful GET 2<br>")

else

Response.Write ("error GET 2<br>")

End if

WebASP1.Request.Url = "www.test.com/dir/page2.asp"

WebASP1.Get

If err = 0 then

Response.Write ("Successful GET 3<br>")

else

Response.Write ("error GET 3<br>")

End if

End Sub

%>


Body Property Example (WebMessage Object - WebASP Tool)

Body Property Example (WebMessage Object)

Visual Basic Example

Sub UpdateImage(Image As String)

Dim stream As New DartStream

WebASP.Request.Version = webHTTP11

WebASP.KeepConnection = TRUE

WebASP.Timeout = 30000

' get a copy of the requested image

WebASP.Request.UrlHost = "www.stagingserver.com"

WebASP.Request.UrlPath = Image

WebASP.Get

' save the Image to a temporary file

WebASP.Response.Body.Filename = "C:\Temp\" & Image

' set the location of the new server

WebASP.Request.UrlHost = "www.hostingserver.com"

WebASP.Request.UrlPath = Image

' add the file to the request

stream.Filename = Image

WebASP.Request.Body.Add (stream)

' try to put the file on a server

WebASP.Put

' finally, check the response for any errors

If WebASP.Response.Status < 200 Or WebASP.Response.Status >299 Then

MsgBox "Put Error: " & WebASP.Response.StatusText

End If

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

Dim s

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebASP1.Timeout = 30000

'Reset the Request Message

WebASP1.Request.Content = ""

' fill in the request body

WebASP1.Request.Url = "www.dart.com"

WebASP1.Get

'check the result

If WebASP1.Response.Status = 200 Then

' good response from server

' write result to web page

s = WebASP1.Response.Body.ReadString

Response.Write s

End If

End Sub

%>


Cookies Property Example (WebMessage Object - WebASP Tool)

Cookies Property Example (WebASP Tool)

Visual Basic Example

Sub GetFile(FileName As String)

Dim c1 as New Cookie

Dim c2 as New Cookie

WebASP1.Request.Version = webHTTP11

WebASP1.Request.KeepAlive = True

WebASP1.Timeout = 30000

' get a copy of the requested image

WebASP1.Request.UrlHost = "www.test.com/testweb"

WebASP1.Request.UrlPath = FileName

' add the previously returned UserId and Process cookies

c1.Name = "UserID"

c1.Value = g_sUserId

WebASP1.Request.Cookies.Add c1

c2.Name = "Process"

c2.Value = g_nProcess

WebASP1.Request.Cookies.Add c2

WebASP1.Get

' finally, check the response for any errors

If WebASP1.Response.Status < 200 Or WebASP1.Response.Status >299 Then

MsgBox "Get Error: " & WebASP1.Response.StatusText

Else

' save the resulting image to a temporary file

WebASP1.Response.Body.Filename = "C:\Temp\" & Filename

End If

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

Dim c1

Dim c2

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebASP1.Timeout = 30000

WebASP1.Redirect = False

WebASP1.Request.Url = "www.dart.com"

c1.name = "cookie1"

c1.value = "value1"

c2.name = "cookie2"

c2.value = "value2"

WebASP1.Request.Cookies.Add c1

WebASP1.Request.Cookies.Add c2

WebASP1.Get

' check the result

If WebASP1.Response.Status = 200 Then

' good response from server

Response.Write WebASP1.Response.Header.All

End If

End Sub

%>


WebMessage Object Example

Visual Basic Example

Private Sub GetTest_Clicked()

WebASP1.Timeout = 30000

'Reset the Request Message

WebASP1.Request.Content = ""

' fill in the request body

WebASP1.Request.Url = "www.test.com/testweb.html"

WebASP1.Get

'check the result

If WebASP1.Response.Status = 200 Then

' good response from server

' save it to a file

WebASP1.Response.Body.Filename = "C:\temp\TestWeb.txt"

End If

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

Dim s

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebASP1.Timeout = 30000

'Reset the Request Message

WebASP1.Request.Content = ""

' fill in the request body

WebASP1.Request.Url = "www.dart.com"

WebASP1.Get

'check the result

If WebASP1.Response.Status = 200 Then

' good response from server

' write result to web page

s = WebASP1.Response.Body.ReadString

Response.Write s

End If

End Sub

%


FilesToPost Property Example (WebMessage Object)

Private Sub Command1_Click()

WebASP1.Timeout = 30000

WebASP1.Request.Url = "www.test.com/postpage.asp"

Dim files As New DartStreams

Dim f1 As New DartStream

Dim f2 As New DartStream

' Files to Post

f1.FileName = "c:\temp\file1.txt"

f1.Ref = "file1"

f2.FileName = "c:\temp\file2.txt"

f2.Ref = "file2"

' Add Files to Collection

files.Add f1

files.Add f2

WebASP1.Request.FilesToPost = files

WebASP1.Post

' check the result

If WebASP1.Response.Status = 200 Then

' good response from the server

' output response

Text1.Text = WebASP1.Response.Header.All

Text2.Text = WebASP1.Response.Body.ReadString

End If

End Sub


Header Property Example (WebMessage Object - WebASP Tool)

Header Property Example (WebMessage Object)

Visual Basic Example

Sub GetFile(MyUrl As String)

WebASP1.Request.Version = webHTTP11

WebASP1.Timeout = 30000

' this first request establishes a connection to the server

' and leaves it open after the response is received

WebASP1.Request.Url = MyUrl

' add a custom label

WebASP1.Request.Header.Add httpNull, "X-DartServer: 5rtfg65444fdf655"

' add a cache control label

WebASP1.Request.Header.Add httpIfModifiedSince, "Mon, 22 May 2000 12:00:00 GMT"

WebASP1.Get

' Header property can also be used to retrieve header fields from a response

MsgBox WebASP1.Response.Header.Find(httpContentLength)

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebASP1.Timeout = 30000

WebASP1.Request.Url = "www.dart.com"

' add a custom header

WebASP1.Request.Header.Add httpNull, "X-DartServer: 5rtfg65444fdf655"

' add a cache control label

WebASP1.Request.Header.Add httpIfModifiedSince, "Tue, 17 Apr 2001 12:00:00 GMT"

WebASP1.Get

' write response headers to web page

for i = 1 to WebAsp1.Response.Header.Count

Response.Write(WebAsp1.Response.Header(i) & "<br>")

next

End Sub

%>


Password Property Example (WebMessage Object - WebASP Tool)

Password Property Example (WebMessage Object)

Visual Basic Example

Sub GetFile (Filename As String, User as String, Pass as String)

WebASP1.Request.Url = Filename

WebASP1.Request.Version = webHTTP11

WebASP1.Request.KeepAlive = False

WebASP1.Timeout = 30000

WebASP1.Get

' check to see if authentication is required, if so add the

' username and password to the request and resend

If WebASP1.Response.Status = 401 Then

WebASP1.Request.Username = User

WebASP1.Request.Password = Pass

' resend

WebASP1.Get

End If

' the caller will handle any errors and/or response processing

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub Authenticate()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebASP1.Timeout = 30000

WebASP1.Request.Url = "www.dart.com"

WebASP1.Request.Version = webHTTP11

WebASP1.Request.KeepAlive = False

WebASP1.Timeout = 30000

WebASP1.Get

' write status to web page for user

Response.Write WebASP1.Response.Status & "<br>"

' check to see if authentication is required, if so add the

' username and password to the request and resend

If WebASP1.Response.Status = 401 Then

WebASP1.Request.Username = "User"

WebASP1.Request.Password = "Pass"

' resend

WebASP1.Get

End If

' the caller will handle any errors and/or response processing

End Sub

%>


Status Property Example (WebMessage Object - WebASP Tool)

Status Property Example (WebMessage Object)

Visual Basic Example

Sub GetFile (Filename As String)

WebASP1.Request.Version = webHTTP11

WebASP1.Request.KeepAlive = False

WebASP1.Timeout = 30000

WebASP1.Request.Url = "www.test.com/" & Filename

WebASP1.Get

' report status to user

MsgBox "Response: " & WebASP1.Response.Status & "-" & WebASP1.Response.StatusText

' the caller will handle any errors or response processing

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebASP1.Timeout = 30000

WebASP1.Request.Url = "www.dart.com"

WebASP1.Request.Version = webHTTP11

WebASP1.Request.KeepAlive = False

WebASP1.Timeout = 30000

WebASP1.Get

' report to user

Response.Write "Response: " & WebASP1.Response.Status & "-" & WebASP1.Response.StatusText

End Sub

%>


StatusText Example (WebMessage Object - WebASP Tool)

StatusText Property Example (WebMessage Object)

Visual Basic Example

Sub GetFile (Filename As String)

WebASP1.Request.Version = webHTTP11

WebASP1.Request.KeepAlive = False

WebASP1.Timeout = 30000

WebASP1.Request.Url = "www.test.com/" & Filename

WebASP1.Get

' report status to user

MsgBox "Response: " & WebASP1.Response.Status & "-" & WebASP1.Response.StatusText

' the caller will handle any errors or response processing

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebASP1.Timeout = 30000

WebASP1.Request.Url = "www.dart.com"

WebASP1.Request.Version = webHTTP11

WebASP1.Request.KeepAlive = False

WebASP1.Timeout = 30000

WebASP1.Get

' report to user

Response.Write "Response: " & WebASP1.Response.Status & "-" & WebASP1.Response.StatusText

End Sub

%>


Url Property Example (WebMessage Object - WebASP Tool)

Url Property Example (WebMessage Object)

Visual Basic Example

Sub GetData()

WebASP1.Request.Version = webHTTP11

WebASP1.Request.KeepAlive = False

WebASP1.Timeout = 30000

' fill in the Url, this updates UrlSecure, UrlPort, UrlPath,

' UrlHost, and UrlQueryString

WebASP1.Request.Url = "www.test.com/index.html"

' since the Url did not contain a port, defaults to 80

' modify it to something else

WebASP1.Request.UrlPort = 8080

' Url property now http:8080//www.test.com/index.html

WebASP1.Request.UrlSecure = True

' Url property now https:8080//www.test.com/index.html

WebASP1.Get

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebASP1.Timeout = 30000

' fill in the Url, this updates UrlSecure, UrlPort, UrlPath,

' UrlHost, and UrlQueryString

WebASP1.Request.Url = "www.test.com"

' since the Url did not contain a port, defaults to 80

' modify it to something else

WebASP1.Request.UrlPort = 8080

' Url property now http:8080//www.test.com/index.html

WebASP1.Request.UrlSecure = True

' Url property now https:8080//www.test.com/index.html

WebASP1.Get

'write response

Response.Write "Response: " & WebASP1.Response.Status & "-" & WebASP1.Response.StatusText

End Sub

%>


UrlHost Property Example (WebMessage Object)

Visual Basic Example

Sub GetData()

WebASP1.Request.Version = webHTTP11

WebASP1.Request.KeepAlive = False

WebASP1.Timeout = 30000

' Fill in the Url. This updates UrlHost, UrlPort, UrlPath,

' UrlHost, and UrlQueryString

WebASP1.Request.UrlHost = "www.test.com/testweb.html"

' Url now http://www.test.com/testweb/

WebASP1.Request.UrlPath = "Content.html"

' Url now http://www.test.com/testweb/Content.html?aaa=111;bbb=222

WebASP1.Request.UrlQueryString = "aaa=111;bbb=222"

' Url now http://www.test.com/testweb/Content.html?aaa=111;bbb=222

WebASP1.Get

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebASP1.Timeout = 30000

' Fill in the Url. This updates UrlHost, UrlPort, UrlPath,

' UrlHost, and UrlQueryString

WebASP1.Request.UrlHost = "www.test.com"

' Url now http://www.test.com

WebASP1.Request.UrlQueryString = "aaa=111;bbb=222"

' Url now http://www.test.com?aaa=111;bbb=222

WebASP1.Request.UrlPath = "Content.html"

' Url now http://www.test.com/Content.html?aaa=111;bbb=222

WebASP1.Get

'write response

Response.Write "Response: " & WebASP1.Response.Status & "-" & WebASP1.Response.StatusText

End Sub

%>


UrlPath Property Example (WebMessage Object - WebASP Tool)

UrlPath Property Example (WebMessage Object)

Visual Basic Example

Sub GetData()

WebASP1.Request.Version = webHTTP11

WebASP1.Request.KeepAlive = False

WebASP1.Timeout = 30000

' Fill in the Url. This updates UrlHost, UrlPort, UrlPath,

' UrlHost, and UrlQueryString

WebASP1.Request.UrlHost = "www.test.com/testweb.html"

' Url now http://www.test.com/testweb/

WebASP1.Request.UrlPath = "Content.html"

' Url now http://www.test.com/testweb/Content.html?aaa=111;bbb=222

WebASP1.Request.UrlQueryString = "aaa=111;bbb=222"

' Url now http://www.test.com/testweb/Content.html?aaa=111;bbb=222

WebASP1.Get

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebASP1.Timeout = 30000

' Fill in the Url. This updates UrlHost, UrlPort, UrlPath,

' UrlHost, and UrlQueryString

WebASP1.Request.UrlHost = "www.test.com"

' Url now http://www.test.com

WebASP1.Request.UrlQueryString = "aaa=111;bbb=222"

' Url now http://www.test.com?aaa=111;bbb=222

WebASP1.Request.UrlPath = "Content.html"

' Url now http://www.test.com/Content.html?aaa=111;bbb=222

WebASP1.Get

'write response

Response.Write "Response: " & WebASP1.Response.Status & "-" & WebASP1.Response.StatusText

End Sub

%>


UrlPort Property Example (WebMessage Object - WebASP Tool)

UrlPort Property Example (WebMessage Object)

Visual Basic Example

Sub GetData()

WebASP1.Request.Version = webHTTP11

WebASP1.Request.KeepAlive = False

WebASP1.Timeout = 30000

' fill in the Url, this updates UrlSecure, UrlPort, UrlPath,

' UrlHost, and UrlQueryString

WebASP1.Request.Url = "www.test.com/index.html"

' since the Url did not contain a port, defaults to 80

' modify it to something else

WebASP1.Request.UrlPort = 8080

' Url property now http:8080//www.test.com/index.html

WebASP1.Request.UrlSecure = True

' Url property now https:8080//www.test.com/index.html

WebASP1.Get

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebASP1.Timeout = 30000

' fill in the Url, this updates UrlSecure, UrlPort, UrlPath,

' UrlHost, and UrlQueryString

WebASP1.Request.Url = "www.test.com"

' since the Url did not contain a port, defaults to 80

' modify it to something else

WebASP1.Request.UrlPort = 8080

' Url property now http:8080//www.test.com/index.html

WebASP1.Request.UrlSecure = True

' Url property now https:8080//www.test.com/index.html

WebASP1.Get

'write response

Response.Write "Response: " & WebASP1.Response.Status & "-" & WebASP1.Response.StatusText

End Sub

%>


UrlQueryString Property Example (WebMessage Object - WebASP Tool)

UrlQueryString Property Example

Example 1: Using the UrlQueryString Property of the WebMessage Object.

Sub GetData()

WebASP1.Request.Version = webHTTP11

WebASP1.Request.KeepAlive = False

WebASP1.Timeout = 30000

' Fill in the Url. This updates UrlHost, UrlPort, UrlPath,

' UrlHost, and UrlQueryString

WebASP1.Request.UrlHost = "www.test.com/testweb.html"

' Url now http://www.test.com/testweb/

WebASP1.Request.UrlPath = "Content.html"

' Url now http://www.test.com/testweb/Content.html?aaa=111;bbb=222

WebASP1.Request.UrlQueryString = "aaa=111;bbb=222"

' Url now http://www.test.com/testweb/Content.html?aaa=111;bbb=222

WebASP1.Get

End Sub

Example 2: Using the UrlQueryString Property of the WebResource Object.

Private Sub Command1_Click()

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

' set request url

WebASP1.Request.Url = "http://www.test.com/testweb"

' get page

WebASP1.Get

' set source to content returned from Get

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through WebResources and add to list box to see all

' WebResources associated with this url

For i = 1 To WebPage1.Resources.Count

List1.AddItem "WebResources " & i

List1.AddItem "Url: " & WebPage1.Resources.Item(i).Url

List1.AddItem "UrlAltText: " & WebPage1.Resources.Item(i).UrlAltText

List1.AddItem "UrlName: " & WebPage1.Resources.Item(i).UrlName

List1.AddItem "UrlPath: " & WebPage1.Resources.Item(i).UrlPath

List1.AddItem "UrlQueryString: " & WebPage1.Resources.Item(i).UrlQueryString

List1.AddItem "UrlType: " & WebPage1.Resources.Item(i).UrlType

List1.AddItem ""

Next

End Sub


UrlSecure Property Example (WebMessage Object - WebASP Tool)

UrlSecure Property Example (WebMessage Object)

Visual Basic Example

Sub GetData()

WebASP1.Request.Version = webHTTP11

WebASP1.Request.KeepAlive = False

WebASP1.Timeout = 30000

' fill in the Url, this updates UrlSecure, UrlPort, UrlPath,

' UrlHost, and UrlQueryString

WebASP1.Request.Url = "www.test.com/index.html"

' since the Url did not contain a port, defaults to 80

' modify it to something else

WebASP1.Request.UrlPort = 8080

' Url property now http:8080//www.test.com/index.html

WebASP1.Request.UrlSecure = True

' Url property now https:8080//www.test.com/index.html

WebASP1.Get

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebASP1.Timeout = 30000

' fill in the Url, this updates UrlSecure, UrlPort, UrlPath,

' UrlHost, and UrlQueryString

WebASP1.Request.Url = "www.test.com"

' since the Url did not contain a port, defaults to 80

' modify it to something else

WebASP1.Request.UrlPort = 8080

' Url property now http:8080//www.test.com/index.html

WebASP1.Request.UrlSecure = True

' Url property now https:8080//www.test.com/index.html

WebASP1.Get

'write response

Response.Write "Response: " & WebASP1.Response.Status & "-" & WebASP1.Response.StatusText

End Sub

%>


Username Property Example (WebMessage Object - WebASP Tool)

Username Property Example (WebMessage Object)

Visual Basic Example

Sub GetFile (Filename As String, User as String, Pass as String)

WebASP1.Request.Url = Filename

WebASP1.Request.Version = webHTTP11

WebASP1.Request.KeepAlive = False

WebASP1.Timeout = 30000

WebASP1.Get

' check to see if authentication is required, if so add the

' username and password to the request and resend

If WebASP1.Response.Status = 401 Then

WebASP1.Request.Username = User

WebASP1.Request.Password = Pass

' resend

WebASP1.Get

End If

' the caller will handle any errors and/or response processing

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub Authenticate()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebASP1.Timeout = 30000

WebASP1.Request.Url = "www.dart.com"

WebASP1.Request.Version = webHTTP11

WebASP1.Request.KeepAlive = False

WebASP1.Timeout = 30000

WebASP1.Get

' write status to web page for user

Response.Write WebASP1.Response.Status & "<br>"

' check to see if authentication is required, if so add the

' username and password to the request and resend

If WebASP1.Response.Status = 401 Then

WebASP1.Request.Username = "User"

WebASP1.Request.Password = "Pass"

' resend

WebASP1.Get

End If

' the caller will handle any errors and/or response processing

End Sub

%>


Variables Property Example (WebMessage Object - WebASP Tool)

Variables Property Example

Visual Basic Example

Sub GetFile(Filename As String)

WebASP1.Request.Version = webHTTP11

WebASP1.Request.KeepAlive = False

WebASP1.Timeout = 30000

WebASP1.Request.Url = "www.test.com/testweb/" & Filename

' put in the variables

WebASP1.Request.Variables("Name") = "John Doe"

WebASP1.Request.Variables("Company") = "Dart"

WebASP1.Request.Variables("State") = "NY"

WebASP1.Request.Variables("WebSite") = "www.dart.com"

' send the data back to the server for processing

WebASP1.Post

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebASP1.Timeout = 30000

WebASP1.Request.Url = "www.test.com/testweb"

' put in the variables

WebASP1.Request.Variables("Name") = "John Doe"

WebASP1.Request.Variables("Company") = "Dart"

WebASP1.Request.Variables("State") = "NY"

WebASP1.Request.Variables("WebSite") = "www.dart.com"

' send the data back to the server for processing

WebASP1.Post

'write response

Response.Write "Response: " & WebASP1.Response.Status & "-" & WebASP1.Response.StatusText

End Sub

%>


WebPage Object Example

Visual Basic Example

The Source property of the WebPage object must be set before the WebPage object can be used. The first example demonstrates setting the source with a local file.

Private Sub Command1_Click()

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

Dim stream1 As New DartStream

stream1.FileMode = createExisting

' set path for local HTML file

stream1.FileName = "C:\temp\default.asp"

' read data into the Source property

WebPage1.Source = stream1.ReadString

' display results

Text1.Text = WebPage1.Source

End Sub

The second example demonstrates setting the source with an online webpage using the WebASP Control.

Private Sub Command1_Click()

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

' set request url

WebASP1.Request.Url = "www.test.com/testweb"

' get page

WebASP1.Get

' set source to body returned from GET

WebPage1.Source = WebASP1.Response.Body.ReadString

' display results

Text2.Text = WebPage1.Source

End Sub

ASP Example


Find Method Example (WebPage Object)

Visual Basic Example

Private Sub FindString(strUrl As String, strToken1 As String, strToken2 As String)

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

' DartStrings to hold results of Find method

Dim results As DartStrings

' set request url with value passed in

WebASP1.Request.Url = strUrl

' get page

WebASP1.Get

' set source of WebPage object with html source returned

WebPage1.Source = WebASP1.Response.Body.ReadString

' find text between the two tokens passed in

Set results = WebPage1.Find(strToken1, strToken2)

' iterate through DartStrings method displaying results

For i = 1 To results.Count

Text1.Text = Text1.Text & "Result " & i & vbCrLf

Text1.Text = Text1.Text & results.Item(i) & vbCrLf & vbCrLf

Next

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub FindString(strUrl, strToken1, strToken2)

on error resume next

Dim WebPage1

Dim WebASP1

Dim results

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

set results = Server.CreateObject("Dart.DartStrings.1")

WebAsp1.Timeout = 30000

WebASP1.Request.Url = strUrl

WebASP1.Get

If WebASP1.Response.Status = 200 then

' set source with html source from response

WebPage1.Source = WebASP1.Response.Body.ReadString

set results = WebPage1.Find(strToken1, strToken2)

Response.Write results.Count & " Results Found<br>"

For i = 1 to results.Count

Response.Write "Result " & i & ": " & results.Item(i) & "<br>"

Next

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


MetaContent Method Example (WebPage Object)

Visual Basic Example

' global declaration of WebPage Object

Dim WebPage1 As New WebPage

Private Sub Command1_Click()

On Error GoTo OnError

'set the request url

WebASP1.Request.Url = "www.test.com/testweb"

' get the page

WebASP1.Get

' set the source of the WebPage Object. this fills the WebTables and

' WebResources collection

WebPage1.Source = WebASP1.Response.Body.ReadString

' put all metanames found into a listbox

For i = 1 To WebPage1.MetaNames.Count

List1.AddItem WebPage1.MetaNames(i)

Next

Exit Sub

OnError:

Debug.Print Err & " " & Err.Description

End Sub

Private Sub List1_Click()

' when metaname is clicked in listbox, display associated meta-content in

' textbox

Text2.Text = WebPage1.MetaContent(List1)

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetMetaTags(strUrl)

on error resume next

' WebPage object to use for parsing

Dim WebPage1

Dim WebASP1

Dim s

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

' set request url

WebASP1.Request.Url = strUrl

WebASP1.Get

If WebASP1.Response.Status = 200 then

WebPage1.Source = WebASP1.Response.Body.ReadString

For i = 1 to WebPage1.MetaNames.Count

Response.Write WebPage1.MetaContent(WebPage1.MetaNames(i))

Next

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


MetaNames Property Example (WebPage Object)

Visual Basic Example

' global declaration of WebPage Object

Dim WebPage1 As New WebPage

Private Sub Command1_Click()

On Error GoTo OnError

'set the request url

WebASP1.Request.Url = "www.test.com/testweb"

' get the page

WebASP1.Get

' set the source of the WebPage Object. this fills the WebTables and

' WebResources collection

WebPage1.Source = WebASP1.Response.Body.ReadString

' put all metanames found into a listbox

For i = 1 To WebPage1.MetaNames.Count

List1.AddItem WebPage1.MetaNames(i)

Next

Exit Sub

OnError:

Debug.Print Err & " " & Err.Description

End Sub

Private Sub List1_Click()

' when metaname is clicked in listbox, display associated meta-content in

' textbox

Text2.Text = WebPage1.MetaContent(List1)

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetMetaTags(strUrl)

on error resume next

' WebPage object to use for parsing

Dim WebPage1

Dim WebASP1

Dim s

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

' set request url

WebASP1.Request.Url = strUrl

WebASP1.Get

If WebASP1.Response.Status = 200 then

WebPage1.Source = WebASP1.Response.Body.ReadString

For i = 1 to WebPage1.MetaNames.Count

Response.Write WebPage1.MetaContent(WebPage1.MetaNames(i))

Next

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


Paragraphs Method Example (WebPage Object)

Visual Basic Example

Private Sub WriteParagraphData(strUrl As String)

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

Dim s As String

Dim Stream1 As New DartStream

Stream1.FileMode = createAlways

' output path

Stream1.FileName = "C:\temp\paragraph.txt"

' set request url with string passed in

WebASP1.Request.Url = strUrl

' get page

WebASP1.Get

' check for good server response

If WebASP1.Response.Status = 200 Then

' set source with html source from response

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through Paragraphs collection, adding values to string s

For i = 1 To WebPage1.Paragraphs.Count

s = s & "Paragraph: " & i & vbCrLf

s = s & "Source: " & WebPage1.Paragraphs.Item(i) & vbCrLr & vbCrLf & vbCrLf

Next

' write s to file

Stream1.Write s

End If

MsgBox "Done"

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub ShowParagraphs(strUrl)

on error resume next

Dim WebPage1

Dim WebASP1

Dim s

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

WebASP1.Request.Url = strUrl

WebASP1.Get

If WebASP1.Response.Status = 200 then

' set source with html source from response

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through Paragraphs collection, adding values to string s

For i = 1 To WebPage1.Paragraphs.Count

s = s & "Paragraph: " & i & vbCrLf

s = s & "Source: " & WebPage1.Paragraphs.Item(i) & vbCrLr & vbCrLf & vbCrLf

Next

' write s to screen

Response.Write s

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


PrimaryFrame Property Example (WebPage Object)

Visual Basic Example

Private Sub Frame_Test()

On Error GoTo OnError

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

' set request url

WebASP1.Request.Url = "www.frametestpage.com"

WebASP1.Get

' set the source of the WebPage Object

WebPage1.Source = WebASP1.Response.Body.ReadString

If WebPage1.PrimaryFrame = "" Then

Text1.Text = "This page either does not contain frames or contains nested frames"

Else

Text1.Text = WebPage1.PrimaryFrame

End If

Exit Sub

OnError:

Debug.Print Err & " " & Err.Description

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub Frames(strUrl)

on error resume next

' WebPage object to use for parsing

Dim WebPage1

Dim WebASP1

Dim s

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

' set request url

WebASP1.Request.Url = strUrl

WebASP1.Get

If WebASP1.Response.Status = 200 then

' good server response, set source of WebPage Object

WebPage1.Source = WebASP1.Response.Body.ReadString

If WebPage1.PrimaryFrame = "" then

Response.Write "This page either does not contain frames or contains nested frames."

Else

Response.Write "The primary frame of this page is located at " & WebPage1.PrimaryFrame

End if

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


Resources Property Example (WebPage Object)

Visual Basic Example

Private Sub GetImages(strUrl As String)

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

Dim blnResult As Boolean

' set request url

WebASP1.Request.Url = strUrl

WebASP1.Get

' set webpage source to html source from response

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through WebResources, be sure to set WebPage.UrlHost first

WebPage1.UrlHost = WebASP1.Request.Url

For i = 1 To WebPage1.Resources.Count

If WebPage1.Resources.Item(i).UrlType = resImg Then

' this WebResource is an image, so write to file

blnResult = WebPage1.Resources(i).Get("C:\temp\img", True, 30000)

If blnResult = True Then

List1.AddItem WebPage1.Resources(i).UrlName & " successfully written to file"

End If

End If

Next

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub DisplayImages(strUrl)

on error resume next

Dim WebPage1

Dim WebASP1

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

WebASP1.Request.Url = strUrl

WebASP1.Get

If WebASP1.Response.Status = 200 then

' Set WebPage Object source

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through Resources Collection, displaying all images

For i = 1 to WebPage1.Resources.Count

If WebPage1.Resources.Item(i).UrlType = 2 then

' this WebResource is an image, so display on screen

' first check for bad path

If WebPage1.Resources.Item(i).UrlPath <> "" then

Response.Write "Graphic: " & i & " Name: " & WebPage1.Resources.Item(i).UrlName & "<br>"

Response.Write "<img src = '" & strUrl & WebPage1.Resources.Item(i).Url & "'><br>"

End if

End if

Next

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


Source Property Example (WebPage Object)

Visual Basic Example

The first example demonstrates setting the source by reading a local file.

Private Sub Command1_Click()

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

Dim stream1 As New DartStream

stream1.FileMode = createExisting

' set path for local HTML file

stream1.FileName = "C:\temp\default.asp"

' read data into the Source property

WebPage1.Source = stream1.ReadString

' display results

Text1.Text = WebPage1.Source

End Sub

The second example demonstrates setting the source with an online webpage using the WebASP Control.

Private Sub Command1_Click()

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

' set request url

WebASP1.Request.Url = "www.test.com/testweb"

' get page

WebASP1.Get

' set source to body returned from GET

WebPage1.Source = WebASP1.Response.Body.ReadString

' display results

Text2.Text = WebPage1.Source

End Sub

ASP Example

ASP Example

<%@ Language=VBScript %>

<%

Sub DisplayTitle(strUrl)

on error resume next

Dim WebPage1

Dim WebASP1

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

WebASP1.Request.Url = strUrl

WebASP1.Get

If WebASP1.Response.Status = 200 then

' Set WebPage Object source

WebPage1.Source = WebASP1.Response.Body.ReadString

Response.Write "Title: " & WebPage1.Title

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


Text Method Example (WebPage Object)

Visual Basic Example

Private Sub Command1_Click()

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

' set request url

WebASP1.Request.Url = "www.dart.com"

' get page

WebASP1.Get

' set source to body returned from GET

WebPage1.Source = WebASP1.Response.Body.ReadString

' display all text results

Text2.Text = WebPage1.Text

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub ExtractText(strUrl)

on error resume next

Dim WebPage1

Dim WebASP1

Dim s

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

WebASP1.Request.Url = strUrl

WebASP1.Get

If WebASP1.Response.Status = 200 then

' Set WebPage Object source

WebPage1.Source = WebASP1.Response.Body.ReadString

' use text method to get page with comments extracted by specifying

' them as tokens

s = WebPage1.Text(False, "<!--", "-->")

Response.Write s

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


Title Property Example (WebPage Object)

Visual Basic Example

Private Sub Command1_Click()

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

' set request url

WebASP1.Request.Url = "www.dart.com"

' get page

WebASP1.Get

' check for good response fom server

If WebASP1.Response.Status = 200 Then

' set source of WebPage object

WebPage1.Source = WebASP1.Response.Body.ReadString

' display results

Text1.Text = "Page Title: " & WebPage1.Title

End If

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub DisplayTitle(strUrl)

on error resume next

Dim WebPage1

Dim WebASP1

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

WebASP1.Request.Url = strUrl

WebASP1.Get

If WebASP1.Response.Status = 200 then

' Set WebPage Object source

WebPage1.Source = WebASP1.Response.Body.ReadString

Response.Write "Title: " & WebPage1.Title

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


UrlHost Property Example (WebPage Object)

Visual Basic Example

Private Sub GetImages(strUrl As String)

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

Dim blnResult As Boolean

' set request url

WebASP1.Request.Url = strUrl

WebASP1.Get

' set webpage source to html source from response

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through WebResources, be sure to set WebPage.UrlHost first

WebPage1.UrlHost = WebASP1.Request.Url

For i = 1 To WebPage1.Resources.Count

If WebPage1.Resources.Item(i).UrlType = resImg Then

' this WebResource is an image, so write to file

blnResult = WebPage1.Resources(i).Get("C:\temp\img", True, 30000)

If blnResult = True Then

List1.AddItem WebPage1.Resources(i).UrlName & " successfully written to file"

End If

End If

Next

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage(strUrl)

on error resume next

Dim WebPage1

Dim WebASP1

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

WebASP1.Request.Url = strUrl

WebASP1.Get

If WebASP1.Response.Status = 200 then

WebPage1.Source = WebASP1.Response.Body.ReadString

WebPage1.UrlHost = strUrl

For i = 1 to WebPage1.Resources.Count

If WebPage1.Resources.Item(i).UrlType = 2 then

' this is an image, check to see if it is in proper format

If Left(WebPage1.Resources.Item(i).Url, 4) <> "http" then

' display in browser

Response.Write "<img src = '" & "http://" & WebPage1.Resources.Item(i).Url & "'><br>"

else

Response.Write "<img src = '" & WebPage1.Resources.Item(i).Url & "'><br>"

end if

End if

Next

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

GetPage("www.dart.com")

%>


WebTables Property Example (WebPage Object)

Visual Basic Example

Private Sub PrintTableReport(strUrl As String)

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

' datastream for file writing

Dim stream As New DartStream

Dim s

stream.FileName = "C:\temp\tempfile.txt"

' set request url

WebASP1.Request.Url = strUrl

WebASP1.Get

' check for good response from server

If WebASP1.Response.Status = 200 Then

' set WebPage source with html content from the response

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through WebTables collection, adding each to s

For i = 1 To WebPage1.WebTables.Count

s = s & "Table " & i & vbCrLf

s = s & "Dimensions: " & WebPage1.WebTables.Item(i).ColumnCount & "X" & WebPage1.WebTables.Item(i).RowCount & vbCrLf

s = s & "Source: " & WebPage1.WebTables.Item(i).Source & vbCrLf & vbCrLf

Next

stream.Write s

End If

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage(strUrl)

on error resume next

' WebPage object to use for parsing

Dim WebPage1

Dim WebASP1

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

WebASP1.Request.Url = strUrl

WebASP1.Get

If WebASP1.Response.Status = 200 then

' set source of WebPage object

WebPage1.Source = WebASP1.Response.Body.ReadString

Response.Write "<h3>Table Report for " & strUrl & "</h3>"

' iterate through WebTables collection and display results

For i = 1 to WebPage1.WebTables.Count

Response.Write "Table " & i & "<br>"

Response.Write "Dimensions: " & WebPage1.WebTables.Item(i).ColumnCount & "X" & WebPage1.WebTables.Item(i).RowCount & "<br>"

Response.Write "Source: " & WebPage1.WebTables.item(i).Source & "<br><br>"

Next

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


Get Method Example (WebResource Object)

Private Sub GetImages(strUrl As String)

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

Dim blnResult As Boolean

' set request url

WebASP1.Request.Url = strUrl

WebASP1.Get

' set webpage source to html source from response

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through WebResources

WebPage1.UrlHost = WebASP1.Request.Url

For i = 1 To WebPage1.Resources.Count

If WebPage1.Resources.Item(i).UrlType = resImg Then

' this WebResource is an image, so write to file

blnResult = WebPage1.Resources(i).Get("C:\temp\img", True, 30000)

If blnResult = True Then

List1.AddItem WebPage1.Resources(i).UrlName & " successfully written to file"

End If

End If

Next

End Sub


Url Property Example (WebResource Object)

Visual Basic Example

Private Sub Command1_Click()

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

' set request url

WebASP1.Request.Url = "http://www.test.com/testweb"

' get page

WebASP1.Get

' set source to content returned from Get

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through WebResources and add to list box to see all

' WebResources associated with this url

For i = 1 To WebPage1.Resources.Count

List1.AddItem "WebResources " & i

List1.AddItem "Url: " & WebPage1.Resources.Item(i).Url

List1.AddItem "UrlAltText: " & WebPage1.Resources.Item(i).UrlAltText

List1.AddItem "UrlName: " & WebPage1.Resources.Item(i).UrlName

List1.AddItem "UrlPath: " & WebPage1.Resources.Item(i).UrlPath

List1.AddItem "UrlQueryString: " & WebPage1.Resources.Item(i).UrlQueryString

List1.AddItem "UrlType: " & WebPage1.Resources.Item(i).UrlType

List1.AddItem ""

Next

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub DisplayImages(strUrl)

on error resume next

Dim WebPage1

Dim WebASP1

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

WebASP1.Request.Url = strUrl

WebASP1.Get

If WebASP1.Response.Status = 200 then

' Set WebPage Object source

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through Resources Collection, displaying all images

For i = 1 to WebPage1.Resources.Count

If WebPage1.Resources.Item(i).UrlType = 2 then

' this WebResource is an image, so display on screen

' first check for bad path

If WebPage1.Resources.Item(i).UrlPath <> "" then

Response.Write "Graphic: " & i & " Name: " & WebPage1.Resources.Item(i).UrlName & "<br>"

Response.Write "<img src = '" & strUrl & WebPage1.Resources.Item(i).Url & "'><br>"

End if

End if

Next

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


UrlAltText Property Example (WebResource Object)

UrlAltText Property (WebResource Object)

Visual Basic Example

Private Sub Command1_Click()

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

' set request url

WebASP1.Request.Url = "http://www.test.com/testweb"

' get page

WebASP1.Get

' set source to content returned from Get

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through WebResources and add to list box to see all

' WebResources associated with this url

For i = 1 To WebPage1.Resources.Count

List1.AddItem "WebResources " & i

List1.AddItem "Url: " & WebPage1.Resources.Item(i).Url

List1.AddItem "UrlAltText: " & WebPage1.Resources.Item(i).UrlAltText

List1.AddItem "UrlName: " & WebPage1.Resources.Item(i).UrlName

List1.AddItem "UrlPath: " & WebPage1.Resources.Item(i).UrlPath

List1.AddItem "UrlQueryString: " & WebPage1.Resources.Item(i).UrlQueryString

List1.AddItem "UrlType: " & WebPage1.Resources.Item(i).UrlType

List1.AddItem ""

Next

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub DisplayResourceInfo(strUrl)

on error resume next

Dim WebPage1

Dim WebASP1

Dim s

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

WebASP1.Request.Url = strUrl

WebASP1.Get

If WebASP1.Response.Status = 200 then

' Set WebPage Object source

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through Resources Collection, displaying all data

For i = 1 to WebPage1.Resources.Count

Response.Write "Url: " & WebPage1.Resources.Item(i).Url & "<br>"

Response.Write "UrlAltText: " & WebPage1.Resources.Item(i).UrlAltText & "<br>"

Response.Write "UrlName: " & WebPage1.Resources.Item(i).UrlName & "<br>"

Response.Write "UrlPath: " & WebPage1.Resources.Item(i).UrlPath & "<br>"

Response.Write "UrlQueryString: " & WebPage1.Resources.Item(i).UrlQueryString & "<br>"

Response.Write "UrlType: " & WebPage1.Resources.Item(i).UrlType & "<br><br>"

Next

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


UrlName Property Example (WebResource Object)

Visual Basic Example

Private Sub GetImages(strUrl As String)

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

Dim blnResult As Boolean

' set request url

WebASP1.Request.Url = strUrl

WebASP1.Get

' set webpage source to html source from response

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through WebResources, be sure to set WebPage.UrlHost first

WebPage1.UrlHost = WebASP1.Request.Url

For i = 1 To WebPage1.Resources.Count

If WebPage1.Resources.Item(i).UrlType = resImg Then

' this WebResource is an image, so write to file

blnResult = WebPage1.Resources(i).Get("C:\temp\img", True, 30000)

If blnResult = True Then

List1.AddItem WebPage1.Resources(i).UrlName & " successfully written to file"

End If

End If

Next

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub DisplayImages(strUrl)

on error resume next

Dim WebPage1

Dim WebASP1

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

WebASP1.Request.Url = strUrl

WebASP1.Get

If WebASP1.Response.Status = 200 then

' Set WebPage Object source

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through Resources Collection, displaying all images

For i = 1 to WebPage1.Resources.Count

If WebPage1.Resources.Item(i).UrlType = 2 then

' this WebResource is an image, so display on screen

' first check for bad path

If WebPage1.Resources.Item(i).UrlPath <> "" then

Response.Write "Graphic: " & i & " Name: " & WebPage1.Resources.Item(i).UrlName & "<br>"

Response.Write "<img src = '" & strUrl & WebPage1.Resources.Item(i).Url & "'><br>"

End if

End if

Next

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


UrlPath Property Example (WebResource Object)

Visual Basic Example

This example shows how to parse a WebResources collection and get each file manually. To see how the WebPage Object can do this automatically using the Get method, refer to the Get Method Example.

Private Sub GetImages(strUrl As String)

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

' set request url

WebASP1.Request.Url = strUrl

WebASP1.Get

' set webpage source to html source from response

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through WebResources

For i = 1 To WebPage1.Resources.Count

If WebPage1.Resources.Item(i).UrlType = resImg Then

' this WebResource is an image

If WebPage1.Resources.Item(i).UrlPath <> "" Then

' if UrlPath is not null, set new url to get image

WebASP1.Request.Url = strUrl & "/" & WebPage1.Resources(i).UrlPath

WebASP1.Get

' write image to file

WebASP1.Response.Body.FileName = "C:\temp\img\" & WebPage1.Resources.Item(i).UrlName

If Err = 0 Then

List1.AddItem WebPage1.Resources.Item(i).UrlName & " written to file"

Else

Debug.Print err & " " & err.Description

End If

End If

End If

Next

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub DisplayImages(strUrl)

on error resume next

Dim WebPage1

Dim WebASP1

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

WebASP1.Request.Url = strUrl

WebASP1.Get

If WebASP1.Response.Status = 200 then

' Set WebPage Object source

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through Resources Collection, displaying all images

For i = 1 to WebPage1.Resources.Count

If WebPage1.Resources.Item(i).UrlType = 2 then

' this WebResource is an image, so display on screen

' first check for bad path

If WebPage1.Resources.Item(i).UrlPath <> "" then

Response.Write "Graphic: " & i & " Name: " & WebPage1.Resources.Item(i).UrlName & "<br>"

Response.Write "<img src = '" & strUrl & WebPage1.Resources.Item(i).Url & "'><br>"

End if

End if

Next

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


UrlType Property Example (WebResource Object)

Visual Basic Example

Private Sub GetImages(strUrl As String)

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

Dim blnResult As Boolean

' set request url

WebASP1.Request.Url = strUrl

WebASP1.Get

' set webpage source to html source from response

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through WebResources, be sure to set WebPage.UrlHost first

WebPage1.UrlHost = WebASP1.Request.Url

For i = 1 To WebPage1.Resources.Count

If WebPage1.Resources.Item(i).UrlType = resImg Then

' this WebResource is an image, so write to file

blnResult = WebPage1.Resources(i).Get("C:\temp\img", True, 30000)

If blnResult = True Then

List1.AddItem WebPage1.Resources(i).UrlName & " successfully written to file"

End If

End If

Next

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub DisplayImages(strUrl)

on error resume next

Dim WebPage1

Dim WebASP1

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

WebASP1.Request.Url = strUrl

WebASP1.Get

If WebASP1.Response.Status = 200 then

' Set WebPage Object source

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through Resources Collection, displaying all images

For i = 1 to WebPage1.Resources.Count

If WebPage1.Resources.Item(i).UrlType = 2 then

' this WebResource is an image, so display on screen

' first check for bad path

If WebPage1.Resources.Item(i).UrlPath <> "" then

Response.Write "Graphic: " & i & " Name: " & WebPage1.Resources.Item(i).UrlName & "<br>"

Response.Write "<img src = '" & strUrl & WebPage1.Resources.Item(i).Url & "'><br>"

End if

End if

Next

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


WebResources Object Example

Visual Basic Example

Private Sub GetImages(strUrl As String)

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

Dim blnResult As Boolean

' set request url

WebASP1.Request.Url = strUrl

WebASP1.Get

' set webpage source to html source from response

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through WebResources, be sure to set WebPage.UrlHost first

WebPage1.UrlHost = WebASP1.Request.Url

For i = 1 To WebPage1.Resources.Count

If WebPage1.Resources.Item(i).UrlType = resImg Then

' this WebResource is an image, so write to file

blnResult = WebPage1.Resources(i).Get("C:\temp\img", True, 30000)

If blnResult = True Then

List1.AddItem WebPage1.Resources(i).UrlName & " successfully written to file"

End If

End If

Next

End Sub

ASP Example


Error Event Example (WebServer Control)

This VB example shows some sample processing.

Private Sub WebServer1_Error(ByVal Session As DartWebServerCtl.ISession, ByVal Number As DartWebServerCtl.ErrorConstants, ByVal Description As String)

On Error GoTo OnError ' use intrinsic error handling

If Number <> ptConnectionAborted _

And Number <> ptConnectionReset Then

If m_nAppType = AT_SERVICE Then

Service1.Log serviceError, serviceErrorEvent, Description

Else

AddLogEntry "ERROR " + CStr(Number) + " " + Description

End If

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Get Event Example (WebServer Control)

Private Sub WebServer1_Get(ByVal Session As DartWebServerCtl.ISession, ByVal Request As DartWebServerCtl.IRequest, ByVal Response As DartWebServerCtl.IResponse)

On Error GoTo OnError ' use intrinsic error handling

Response.Header(httpServer) = "My Web Server/1.0"

' Add other headers here.

If Response.Status = httpOK Then

' found template page...

Else

' page not found: return default error page

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Head Event Example (WebServer Control)

Private Sub WebServer1_Head(ByVal Session As DartWebServerCtl.ISession, ByVal Request As DartWebServerCtl.IRequest, ByVal Response As DartWebServerCtl.IResponse)

On Error GoTo OnError ' use intrinsic error handling

Response.Header(httpServer) = "My Web Server/1.0"

' Add other headers here.

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


MaxIdleTime Property Example (WebServer Control)

Private Sub WebServer1_SetIdleClick()

On Error GoTo OnError ' use intrinsic error handling

' Allow the session to be idle for 30 minutes before expiring.

WebServer1.MaxIdleTime = 30

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Post Event Example (WebServer Control)

Private Sub WebServer1_Post(ByVal Session As DartWebServerCtl.ISession, ByVal Request As DartWebServerCtl.IRequest, ByVal Response As DartWebServerCtl.IResponse)

On Error GoTo OnError ' use intrinsic error handling

' prepare the response...go to OnError if file does not exist

Response.Body.FileMode = createOpen

Response.Body.FileName = Request.FileName ' throws error if not present

' process Request.Variables

Dim Var As HttpVariable

For Each Var In Request.Variables

MsgBox Var.Name & " = " & Var.Value

Next

Response.Status = httpOK

' Response.StatusText defaults to "200 OK"

' Response.Body will be returned to client

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

' return error because Request.FileName was not found

Response.Status = httpNotFound

' Response.StatusText defaults to "403 Not Found"

End Sub


Put Event Example (WebServer Control)

Private Sub WebServer1_Put(ByVal Session As DartWebServerCtl.ISession, ByVal Request As DartWebServerCtl.IRequest, ByVal Response As DartWebServerCtl.IResponse)

On Error GoTo OnError

Request.Body.FileName = WebServer1.RootDirectory + Request.Filename

Response.Status = httpCreated

Exit Sub

OnError:

Response.Status = httpForbidden

End Sub


RootDirectory Property Example (WebServer Control)

' establish the root directory for all web documents

' subsequent file operations use this as the default directory

WebServer1.RootDirectory = "C:\WebPub"


SessionEnd Event Example (WebServer Control)

This VB example demonstrates preventing the session object from being deleted:

Private Sub WebServer1_SessionEnd(ByVal Session As DartWebServerCtl.ISession)

On Error GoTo OnError ' use intrinsic error handling

' Reset the inactivity time to 0 so the object will not be destroyed.

Session.IdleTime = 0

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


SessionInit Event Example (WebServer Control)

This VB example demonstrates the a use of this event to initialize variables for the session.

Private Sub WebServer1_SessionInit(ByVal Session As DartWebServerCtl.ISession)

On Error GoTo OnError ' use intrinsic error handling

'Add a variable by the name of Var1 to the sessions Variables

'collection. You may also want to log this even to a file here.

Session.Variables("Var1") = "This a default variable."

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Sessions Property Example (WebServer Control)

This VB example shows the Sessions property being used to look for a session with a particular session id and update one of the session variables.

Private Sub UpdateName(Id As String, Name As String)

On Error GoTo OnError ' use intrinsic error handling

WebServer1.Sessions(Id).Variables("FirstName") = Name

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Start Method Example (WebServer Control)

This VB example demonstrates starting a non-secure server (no HTTPS).

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Start a non-secure server on port 8080

WebServer1.Start 8080, -1

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

This VB example demonstrates starting a non-secure using the default port and a secure server using an assigned port.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

'Use documents in the C:\WebPub directory

WebServer1.RootDirectory = "C:\WebPub"

'Use CertificateStore to look-up security certificate desired

Dim Store As New CertificateStore

'Get the specified certificate

WebServer1.Certificate = Store.Find("ROOT", locationLocalMachine, g_SavedIssuedBy, g_SavedSerialNumber)

' Listen for secure connections on default port 443

' Listen for non-secure connections on default port 80

WebServer1.Start

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Stop Method Example (WebServer Control)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Stop listening and accepting connections

WebServer1.Stop

' We also want to clear all our sessions

WebServer1.Sessions.Clear

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


WebServer Tool SOAP Sample

'SOAP uses the POST command to send messages to the server.

'Using Microsoft's or Dart's SOAP client, an initial GET is

'performed is performed to extract the WSDL file so that the

'available functions are known. After that, the remaining

'commands are POST.

Private Sub WebServer1_Post(ByVal Session As DartWebServerCtl.ISession, ByVal Request As DartWebServerCtl.IRequest, ByVal Response As DartWebServerCtl.IResponse)

Dim SS As SoapServer 'The MS SoapServer object

Dim SHeader As String 'The header containing the SOAP action

'Extract the SOAP Action (the function to be called) from the header of the

'HTTP request

SHeader = Request.Header.Find(httpNull, "SOAPAction:")

Set SS = New SoapServer

'If there is no SOAPAction header, we consider this to be a non-SOAP

'POST and all SOAP related functionality is ignored

If SHeader <> "" Then

'Initialize the SoapServer with the WSDL and WSML file locations

SS.Init txtWSDLPath & "\" & txtWSDL, txtWSMLPath & "\" & txtWSML

'Initialize a new stream for the response so that the WSDL file

'is not over-written because this is a POST

Dim stream As New DartStream

Response.Body = stream

'Extract the SOAPAction from the header

SHeader = Left(SHeader, Len(SHeader) - 1)

SHeader = Right(SHeader, Len(SHeader) - 2)

'Invoke the SoapPServer by passing it the Request body, the Response object, and the SOAPAction

SS.SoapInvoke Request.Body.ReadBytes, Response, SHeader

'Line below not required by Microsoft example, but necessary for SOAP compliance:

Response.Header.Add httpContentType, "text/xml", True

End If

End Sub


Caption Property Example (WebTable Object)

Visual Basic Example

Private Sub GetTableInfo(strUrl As String, lngTable As Long)

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

' set request

WebASP1.Request.Url = strUrl

WebASP1.Get

' check for good server response

If WebASP1.Response.Status = 200 Then

' set WebPage object source

WebPage1.Source = WebASP1.Response.Body.ReadString

Text1.Text = "Table Caption: " & WebPage1.WebTables(lngTable).Caption & vbCrLf

Text1.Text = Text1.Text & "Table Summary: " & WebPage1.WebTables(lngTable).Summary

End If

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage(strUrl)

on error resume next

' WebPage object to use for parsing

Dim WebPage1

Dim WebASP1

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

' set request url

WebASP1.Request.Url = strUrl

WebASP1.Get

' check for good server response

If WebASP1.Response.Status = 200 then

WebPage1.Source = WebASP1.Response.Body.ReadString

Response.Write "Table Caption: " & WebPage1.WebTables(1).Caption & "<BR>"

Response.Write "Table Summary: " & WebPage1.WebTables(1).Summary

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


Cell Method Example (WebTable Object)

Visual Basic Example

Private Sub GetCellSource(strUrl As String, lngTable As Long, lngColumn As Long, lngRow As Long)

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

Dim s As String

' set Request url

WebASP1.Request.Url = strUrl

WebASP1.Get

' check for good server response

If WebASP1.Response.Status = 200 Then

' set WebPage object source with html page returned in response

WebPage1.Source = WebASP1.Response.Body.ReadString

' get cell source using row and column values passed into the function

s = WebPage1.WebTables(lngTable).Cell(lngRow, lngColumn)

' dump result into text box

Text1.Text = s

End If

MsgBox "OK"

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetCellSource (strUrl, lngTable, lngCol, lngRow)

on error resume next

' WebPage Object to use for parsing

Dim WebPage1

Dim WebASP1

Dim s

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

WebASP1.Request.Url = strUrl

WebASP1.Get

' check for good server response

If WebASP1.Response.Status = 200 then

WebPage1.Source = WebASP1.Response.Body.ReadString

' output cell source

Response.Write "Cell Source for row " & lngRow & ", column " & lngCol & " of table " & lngTable

s = WebPage1.WebTables(lngTable).Cell(lngRow, lngCol)

Response.Write "<br>" & s

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


ColumnCount Property Example (WebTable Object)

Visual Basic Example

Private Sub PrintTableReport(strUrl As String)

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

' datastream for file writing

Dim stream As New DartStream

Dim s

stream.FileName = "C:\temp\tempfile.txt"

' set request url

WebASP1.Request.Url = strUrl

WebASP1.Get

' check for good response from server

If WebASP1.Response.Status = 200 Then

' set WebPage source with html content from the response

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through WebTables collection, adding each to s

For i = 1 To WebPage1.WebTables.Count

s = s & "Table " & i & vbCrLf

s = s & "Dimensions: " & WebPage1.WebTables.Item(i).ColumnCount & "X" & WebPage1.WebTables.Item(i).RowCount & vbCrLf

s = s & "Source: " & WebPage1.WebTables.Item(i).Source & vbCrLf & vbCrLf

Next

stream.Write s

End If

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage(strUrl)

on error resume next

' WebPage object to use for parsing

Dim WebPage1

Dim WebASP1

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

WebASP1.Request.Url = strUrl

WebASP1.Get

If WebASP1.Response.Status = 200 then

' set source of WebPage object

WebPage1.Source = WebASP1.Response.Body.ReadString

Response.Write "<h3>Table Report for " & strUrl & "</h3>"

' iterate through WebTables collection and display results

For i = 1 to WebPage1.WebTables.Count

Response.Write "Table " & i & "<br>"

Response.Write "Dimensions: " & WebPage1.WebTables.Item(i).ColumnCount & "X" & WebPage1.WebTables.Item(i).RowCount & "<br>"

Response.Write "Source: " & WebPage1.WebTables.item(i).Source & "<br><br>"

Next

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


RowCount Property Example (WebTable Object)

Visual Basic Example

Private Sub PrintTableReport(strUrl As String)

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

' datastream for file writing

Dim stream As New DartStream

Dim s

stream.FileName = "C:\temp\tempfile.txt"

' set request url

WebASP1.Request.Url = strUrl

WebASP1.Get

' check for good response from server

If WebASP1.Response.Status = 200 Then

' set WebPage source with html content from the response

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through WebTables collection, adding each to s

For i = 1 To WebPage1.WebTables.Count

s = s & "Table " & i & vbCrLf

s = s & "Dimensions: " & WebPage1.WebTables.Item(i).ColumnCount & "X" & WebPage1.WebTables.Item(i).RowCount & vbCrLf

s = s & "Source: " & WebPage1.WebTables.Item(i).Source & vbCrLf & vbCrLf

Next

stream.Write s

End If

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage(strUrl)

on error resume next

' WebPage object to use for parsing

Dim WebPage1

Dim WebASP1

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

WebASP1.Request.Url = strUrl

WebASP1.Get

If WebASP1.Response.Status = 200 then

' set source of WebPage object

WebPage1.Source = WebASP1.Response.Body.ReadString

Response.Write "<h3>Table Report for " & strUrl & "</h3>"

' iterate through WebTables collection and display results

For i = 1 to WebPage1.WebTables.Count

Response.Write "Table " & i & "<br>"

Response.Write "Dimensions: " & WebPage1.WebTables.Item(i).ColumnCount & "X" & WebPage1.WebTables.Item(i).RowCount & "<br>"

Response.Write "Source: " & WebPage1.WebTables.item(i).Source & "<br><br>"

Next

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


Source Property Example (WebTable Object)

Visual Basic Example

Private Sub PrintTableReport(strUrl As String)

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

' datastream for file writing

Dim stream As New DartStream

Dim s

stream.FileName = "C:\temp\tempfile.txt"

' set request url

WebASP1.Request.Url = strUrl

WebASP1.Get

' check for good response from server

If WebASP1.Response.Status = 200 Then

' set WebPage source with html content from the response

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through WebTables collection, adding each to s

For i = 1 To WebPage1.WebTables.Count

s = s & "Table " & i & vbCrLf

s = s & "Dimensions: " & WebPage1.WebTables.Item(i).ColumnCount & "X" & WebPage1.WebTables.Item(i).RowCount & vbCrLf

s = s & "Source: " & WebPage1.WebTables.Item(i).Source & vbCrLf & vbCrLf

Next

stream.Write s

End If

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage(strUrl)

on error resume next

' WebPage object to use for parsing

Dim WebPage1

Dim WebASP1

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

WebASP1.Request.Url = strUrl

WebASP1.Get

If WebASP1.Response.Status = 200 then

' set source of WebPage object

WebPage1.Source = WebASP1.Response.Body.ReadString

Response.Write "<h3>Table Report for " & strUrl & "</h3>"

' iterate through WebTables collection and display results

For i = 1 to WebPage1.WebTables.Count

Response.Write "Table " & i & "<br>"

Response.Write "Dimensions: " & WebPage1.WebTables.Item(i).ColumnCount & "X" & WebPage1.WebTables.Item(i).RowCount & "<br>"

Response.Write "Source: " & WebPage1.WebTables.item(i).Source & "<br><br>"

Next

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


Summary Property Example (WebTable Object)

Visual Basic Example

Private Sub GetTableInfo(strUrl As String, lngTable As Long)

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

' set request

WebASP1.Request.Url = strUrl

WebASP1.Get

' check for good server response

If WebASP1.Response.Status = 200 Then

' set WebPage object source

WebPage1.Source = WebASP1.Response.Body.ReadString

Text1.Text = "Table Caption: " & WebPage1.WebTables(lngTable).Caption & vbCrLf

Text1.Text = Text1.Text & "Table Summary: " & WebPage1.WebTables(lngTable).Summary

End If

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage(strUrl)

on error resume next

' WebPage object to use for parsing

Dim WebPage1

Dim WebASP1

set WebPage1 = Server.CreateObject("Dart.WebPage.1")

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebAsp1.Timeout = 30000

' set request url

WebASP1.Request.Url = strUrl

WebASP1.Get

' check for good server response

If WebASP1.Response.Status = 200 then

WebPage1.Source = WebASP1.Response.Body.ReadString

Response.Write "Table Caption: " & WebPage1.WebTables(1).Caption & "<BR>"

Response.Write "Table Summary: " & WebPage1.WebTables(1).Summary

End if

if err <> 0 then

Response.Write err & " " & err.Description

end if

End Sub

%>


Count Property Example (WebTables Object)

Visual Basic Example

Private Sub PrintTableReport(strUrl As String)

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

' datastream for file writing

Dim stream As New DartStream

Dim s

stream.FileName = "C:\temp\tempfile.txt"

' set request url

WebASP1.Request.Url = strUrl

WebASP1.Get

' check for good response from server

If WebASP1.Response.Status = 200 Then

' set WebPage source with html content from the response

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through WebTables collection, adding each to s

For i = 1 To WebPage1.WebTables.Count

s = s & "Table " & i & vbCrLf

s = s & "Dimensions: " & WebPage1.WebTables.Item(i).ColumnCount & "X" & WebPage1.WebTables.Item(i).RowCount & vbCrLf

s = s & "Source: " & WebPage1.WebTables.Item(i).Source & vbCrLf & vbCrLf

Next

stream.Write s

End If

End Sub

ASP Example


WebTables Object Example

WebTables Example

Visual Basic Example

Private Sub PrintTableReport(strUrl As String)

' WebPage object to use for parsing

Dim WebPage1 As New WebPage

' datastream for file writing

Dim stream As New DartStream

Dim s

stream.FileName = "C:\temp\tempfile.txt"

' set request url

WebASP1.Request.Url = strUrl

WebASP1.Get

' check for good response from server

If WebASP1.Response.Status = 200 Then

' set WebPage source with html content from the response

WebPage1.Source = WebASP1.Response.Body.ReadString

' iterate through WebTables collection, adding each to s

For i = 1 To WebPage1.WebTables.Count

s = s & "Table " & i & vbCrLf

s = s & "Dimensions: " & WebPage1.WebTables.Item(i).ColumnCount & "X" & WebPage1.WebTables.Item(i).RowCount & vbCrLf

s = s & "Source: " & WebPage1.WebTables.Item(i).Source & vbCrLf & vbCrLf

Next

stream.Write s

End If

End Sub

ASP Example


Command Method Example (WebASP Control)

Visual Basic Example

Sub CommandTest_Click()

Dim s as String

' Example of using a non-standard command

' Let's say this server supports a "LOG" command that causes

' the server to return its internal log of certain data

WebASP1.Timeout = 30000

WebASP1.Redirect = FALSE

' fill in the request body

WebASP1.Request.Url = "www.test.com/testweb.html"

' add a custom header for this request

WebASP1.Request.Header.Add httpNull, "X-Log: Hits, Errors", TRUE

WebASP1.Request.UrlPort = 81

WebASP1.Request.Username = "Dart1"

WebASP1.Request.Password = "Dart1"

' send the LOG command along with the information in the request

WebASP1.Command "LOG"

' check the result

If WebASP1.Response.Status = 200 Then

'good response from server

WebASP1.Response.Body.Read s

Text1.Text = s

End If

' Try a standard command

' The HTTP/1.1 protocol also specifies that the DELETE command

' may be used to remove files from a server

WebASP1.Request.Content = ""

WebASP1.Request.Url = "www.test.com/testweb.html"

WebASP1.Command "DELETE"

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

Dim s

' Example of using a non-standard command

' Let's say this server supports a "LOG" command that causes

' the server to return its internal log of certain data

WebASP1.Timeout = 30000

WebASP1.Redirect = False

' fill in the request body

WebASP1.Request.Url = "www.dart.com"

WebASP1.Command "LOG"

' check the result

Response.Write "Response: " & WebASP1.Response.Status & "-" & WebASP1.Response.StatusText

' Try a standard command

' The HTTP/1.1 protocol also specifies that the DELETE command

' may be used to remove files from a server

WebASP1.Request.Content = ""

WebASP1.Request.Url = "www.test.com"

WebASP1.Command "DELETE"

Response.Write "Response: " & WebASP1.Response.Status & "-" & WebASP1.Response.StatusText

End Sub

%>


Get Method Example (WebASP Control)

Visual Basic Example

Private Sub GetTest_Click()

WebASP1.Timeout = 30000

'Reset the Request Message

WebASP1.Request.Content = ""

' fill in the request body

WebASP1.Request.Url = "www.test.com/testweb.html"

WebASP1.Get

'check the result

If WebASP1.Response.Status = 200 Then

' good response from server

' save it to a file

WebASP1.Response.Body.Filename = "C:\temp\TestWeb.txt"

End If

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

Dim s

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebASP1.Timeout = 30000

'Reset the Request Message

WebASP1.Request.Content = ""

' fill in the request body

WebASP1.Request.Url = "www.dart.com"

WebASP1.Get

'check the result

If WebASP1.Response.Status = 200 Then

' good response from server

' write result to web page

s = WebASP1.Response.Body.ReadString

Response.Write s

End If

End Sub

%>


Head Method Example (WebASP Control)

Visual Basic Example

Private Sub HeadTest_Click()

WebASP1.Timeout = 30000

' Reset the request

WebASP1.Request.Content = ""

' fill in the request body

WebASP1.Request.Url = "www.test.com/TestWeb.html"

WebASP1.Head

' check the result

If WebASP1.Response.Status = 200 Then

' good response from the server

' dump the headers into a text box

Text1.text = WebASP1.Response.Header.All

End If

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebASP1.Timeout = 30000

' Reset the request

WebASP1.Request.Content = ""

' fill in the request body

WebASP1.Request.Url = "www.dart.com"

WebASP1.Head

' check the result

If WebASP1.Response.Status = 200 Then

' good response from the server

' write the headers to the web page

Response.Write WebASP1.Response.Header.All

End If

End Sub

%>


Post Method Example (WebASP Control)

Visual Basic Example

An example of posting files.

Private Sub Command1_Click()

WebASP1.Timeout = 30000

WebASP1.Request.Url = "www.test.com/postpage.asp"

Dim files As New DartStreams

Dim f1 As New DartStream

Dim f2 As New DartStream

' Files to Post

f1.FileName = "c:\temp\file1.txt"

f1.Ref = "file1"

f2.FileName = "c:\temp\file2.txt"

f2.Ref = "file2"

' Add Files to Collection

files.Add f1

files.Add f2

WebASP1.Request.FilesToPost = files

WebASP1.Post

' check the result

If WebASP1.Response.Status = 200 Then

' good response from the server

' output response

Text1.Text = WebASP1.Response.Header.All

Text2.Text = WebASP1.Response.Body.ReadString

End If

End Sub

An example of posting variables

Private Sub Command1_Click()

WebASP1.Timeout = 30000

WebASP1.Request.Url = "www.dart.com"

' put in the variables

WebASP1.Request.Variables("Name") = "John Doe"

WebASP1.Request.Variables("Company") = "Dart"

WebASP1.Request.Variables("State") = "NY"

WebASP1.Request.Variables("WebSite") = "www.dart.com"

' send the data back to the server for processing

WebASP1.Post

' check status

msgbox WebASP1.Response.Status

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebASP1.Timeout = 30000

WebASP1.Request.Url = "www.dart.com"

' put in the variables

WebASP1.Request.Variables("Name") = "John Doe"

WebASP1.Request.Variables("Company") = "Dart"

WebASP1.Request.Variables("State") = "NY"

WebASP1.Request.Variables("WebSite") = "www.dart.com"

' send the data back to the server for processing

WebASP1.Post

'write response

Response.Write "Response: " & WebASP1.Response.Status & "-" & WebASP1.Response.StatusText

End Sub

%>


Progress Event Example (WebASP Control)

Private Sub WebASP1_Progress(ByVal Method As DartWebASPCtl.WebMethodConstants, ByVal Status As DartWebASPCtl.WebStatusConstants, ByVal Count As Long, ByVal Size As Long)

If Status = webSending Then

lblSend = Count & " of " & Size & " sent."

End If

If Status = webReceiving Then

lblReceive = Count & " of " & Size & " received."

End If

End Sub


Put Method Example (WebASP Control)

Private Sub Command1_Click()

' Clear Request content

WebAsp1.Request.Content = ""

WebAsp1.Request.Version = webHTTP11

' set path to put file in

WebAsp1.Request.Url = "www.test.com"

WebAsp1.Request.UrlPath = "Upload/testfile.bmp"

' set request body to file to put

WebAsp1.Request.Body.FileMode = createExisting

WebAsp1.Request.Body.FileName = "c:\temp\testfile.bmp"

WebAsp1.Request.Body.Ref = "File1"

WebAsp1.Put

' add status to log

AddLog WebASP1.Response.Status & ": " & WebASP1.Response.StatusText

End Sub


Request Property Example (WebASP Control)

Visual Basic Example

Private Sub RequestTest_Click()

WebASP1.Timeout = 30000

WebASP1.Redirect = FALSE

WebASP1.Request.Content = ""

' fill in the request body

WebASP1.Request.Url = "www.test.com/testweb.html"

WebASP1.Request.Header.Add httpNull, "X-MyLabel: New Label", TRUE

WebASP1.Request.UrlPort = 81

WebASP1.Request.Username = "Dart1"

WebASP1.Request.Password = "Dart1"

' send the contents of WebASP1.Request

WebASP1.Get

' check to see if successful

MsgBox WebASP1.Response.Status

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub GetPage()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

WebASP1.Timeout = 30000

WebASP1.Redirect = False

WebASP1.Request.Content = ""

' fill in the request body

WebASP1.Request.Url = "www.test.com/testweb"

WebASP1.Request.Header.Add httpNull, "X-MyLabel: New Label", True

WebASP1.Request.UrlPort = 80

WebASP1.Request.Username = "Dart1"

WebASP1.Request.Password = "Dart1"

' send the contents of Web1.Request

WebASP1.Get

' check the status to see if successful

Response.Write "Response: " & WebASP1.Response.Status & "-" & WebASP1.Response.StatusText

End Sub

%>


Response Property Example (WebASP Control)

Visual Basic Example

Private Sub ResponseTest_Click()

Dim s as String

WebASP1.Timeout = 30000

WebASP1.Redirect = FALSE

' fill in the request body

WebASP1.Request.Url = "www.test.com/testweb.html"

WebASP1.Request.Header.Add httpNull, "X-MyLabel: New Label", TRUE

WebASP1.Request.UrlPort = 81

WebASP1.Request.Username = "Dart1"

WebASP1.Request.Password = "Dart1"

' send the contents of WebASP1.Request

WebASP1.Get

' check the result

If WebASP1.Response.Status = 200 Then

'good response from server

WebASP1.Response.Body.Read s

Edit1.Text = s

End If

End Sub

ASP Example

<%@ Language=VBScript %>

<%

Sub ResponseTest()

Dim WebASP1

On Error Resume Next

set WebASP1 = Server.CreateObject("Dart.WebASP.1")

Dim s

WebASP1.Timeout = 30000

WebASP1.Redirect = False

WebASP1.Request.Url = "www.test.edu/testweb"

WebASP1.Get

' check the result

If WebASP1.Response.Status = 200 Then

'good response from server

s = WebASP1.Response.Body.ReadString

Response.Write WebASP1.Response.Url & "<br>"

Response.Write s

End If

End Sub

%>


ValidFrom Property Example (Certificate Object)

Refer to CertificateStore Object Example for an example of how to use the ValidFrom property.


ValidTo Property Example (Certificate Object)

Refer to CertificateStore Object Example for an example of how to use the ValidTo property.


Version Property Example (Certificate Object)

Refer to CertificateStore Object Example for an example of how to use the Version property.


ServerName Property Example (DNS Control)

Refer to the DNS Control Names Property Example topic for an example of how to use the ServerName property.


Get Method Example (FTP Control)

This VB example shows how to log in (anonymously), get a file, and then log out.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim FileBuf As String ' local scope allowed because Timeout > 0

' Login as anonymous and save the data to a buffer

Ftp1.Get "ftp://ftp.dart.com/ftpchallenge.txt", FileBuf

Text1.Text = FileBuf ' show file data to user

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


List Method Example (FTP Control)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Ftp1.Login "ftp.dart.com", "anonymous", "powertcp"

If Ftp1.State = tcpConnected Then MsgBox "Connected!"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Private Sub Command2_Click()

On Error GoTo OnError ' use intrinsic error handling

Ftp1.Timeout = 1000

Ftp1.List "-lr" ' a full recursive listing is requested

Text1.Text = Ftp1.Listing.Text ' show to user

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Private Sub Command3_Click(

On Error GoTo OnError

Ftp1.Timeout = 1000

Ftp1.List "-lr *.txt" ' a full recursive listing of text files

Dim ListEntry As ListEntry

For Each ListEntry In Ftp1.Listing

Text2.Text = ListEntry.Name & vbCrLf ' show all names to user

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Login Method Example (FTP Control)

This VB example shows how to perform an ftp login.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Ftp1.Login "ftp.dart.com", "anonymous", "powertcp"

If Ftp1.State = tcpConnected Then MsgBox "Connected!"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


NameList Method Example (FTP Control)

This VB example shows how to get a file directory listing without file attributes.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Ftp1.Login "ftp.dart.com", "anonymous", "powertcp"

If Ftp1.State = tcpConnected Then MsgBox "Connected!"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Private Sub Command2_Click()

On Error GoTo OnError ' use intrinsic error handling

Ftp1.Timeout = 1000

Ftp1.NameList

Text1.Text = Ftp1.Listing.Text ' show list of filenames to user

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Progress Event Example (Ftp Control)

Private Sub Ftp1_Progress(ByVal FtpCmd As DartFtpCtl.CommandConstants, ByVal Status As DartFtpCtl.StatusConstants, ByVal Reply As String, ByVal Count As Long, ByVal Size As Long)

On Error GoTo OnError ' use intrinsic error handling

Ftp1.TimeOut = 0

If Status = ftpOk Then

' Use select to control what to do next

Select Case FtpCmd

Case ftpPassword

' we are logged in, so issue Retrieve command

Ftp1.Retrieve "RemoteFile.txt", "LocalFile.txt"

Case ftpRetrieve

' file transfer is complete...close

Ftp1.Logout

End Select

ElseIf Status = ftpInProgress Then

If FtpCmd = ftpRetrieve Then Label1.Caption = Count / Size * 100 & "%" & " done..."

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Retrieve Method Example (FTP Control)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim FileBuf As String ' local scope allowed because Timeout > 0

Ftp1.Timeout = 1000

' Get the data without storing it to file

Ftp1.Retrieve "ftpchallenge.txt", FileBuf

Text1.Text = FileBuf ' show to user

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Site Method Example (Ftp Control)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Result As String ' local scope allowed because Timeout > 0

Ftp1.Timeout = 1000

' get help on the SITE command

Ftp1.Site "Help", Result

Text1.Text = Result ' show to user

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


QuitMessage Property Example (FtpServer Control)

'Send this message when the client logs out.

FtpServer1.QuitMessage = "Bye see you next time!"

This is the protocol example of the above example:

C - Client S - Server

C: QUIT

S: 221 Bye see you next time!


RestartAllowed Property Example (FtpServer Control)

This VB example shows how to enable restarting of file transfers.

'Allow restarting of file transfers.

FtpServer1.RestartAllowed = True

The following protocol demonstrates the above example:

C - Client S - Server

C: REST 100

S: 350 Restarting at 100. Send STOR or RETR command to begin transfer.

This VB example shows how to disable restarting of file transfers.

'Do not allow restarting of file transfers.

FtpServer1.RestartAllowed = False

The following protocol demonstrates the above example:

C - Client S - Server

C: REST 100

S: 502 REST command not implemented.


Start Method Example (FtpServer Control)

This VB example demonstrates starting the server.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

'Set the root directory for the ftp server to be C:\FtpRoot\

'Start the server on port 21

FtpServer1.Start "C:\FtpRoot\"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Status Property Example (FtpServer Control)

' Set the status for the server.

FtpServer1.Status = "Server is running."

The following protocol example demonstrates the above example:

C - Client S - Server

C: SYST

S: 211 Server is running


Stop Method Example (FtpServer Control)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Stop listening and accepting connections

FtpServer1.Stop

' We also want to clear all our sessions

FtpServer1.Sessions.Clear

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


SystemName Property Example (FtpServer Control)

' Set the system name to UNIX Type.

FtpServer1.SystemName = "UNIX type: L8"

The following protocol example demonstrates the above example:

C - Client S - Server

C: SYST

S: 215 UNIX type: L8


WelcomeMessage Property Example (FtpServer Control)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

'Set the root directory for the ftp server to be C:\FtpRoot\

'Start the server on port 21

FtpServer1.Start "C:\FtpRoot\"

' Set the welcome message

FtpServer1.WelcomeMessage = "Welcome to my personal ftp server. Version 1.0"

Text1.Text = FtpServer1.WelcomeMessage

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

The following protocol example demonstrates the above code snippet:

C - Client S - Server

C: (Makes connection attempt to server)

S: 220 Welcome to my personal ftp server. Version 1.0


Add Method Example (HeaderFields Object)

This VB example illustrates how header fields are added to a HeaderFields Object.

Private Sub Command1_Click()

Dim myHeaders As New HeaderFields

myHeaders.Add msgSubject, "This is a test"

myHeaders.Add msgContentType, "text/plain"

' Verify header fields

Text1.Text = myHeaders.All

End Sub


Remove Method Example (HeaderFields Object)

Private Sub Command1_Click()

Dim Msg As New Message

Msg.Load "C:\Temp\Test.msg"

' view the headers

Text1.Text = Msg.Header.All

' remove the Content-Type header field

' and then view the headers less the Content-Type header

Msg.Header.Remove msgContentType

Text2.Text = Msg.Header.All

' remove the first header field in the collection

' and then view the headers less the Content-Type and first header

Msg.Header.Remove msgNull, 1

Text3.Text = Msg.Header.All

End Sub


ListEntry Object Example

This VB example shows how to add listing filenames to a list box.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Entry As ListEntry

Ftp1.List

For Each Entry In Ftp1.Listing

List1.AddItem Entry.Name

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Add Method Example (Mailboxes Object)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim mbox As New Mailbox

Imap1.Refresh

' Set the name property to the name of the mailbox to create

mbox.Name = "Temp"

' Now add to the collection to create the mailbox

Imap1.Mailboxes.Add mbox

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Add Method Example (PhoneBookEntries Object)

This VB example shows how to invoke system dialog boxes to create a new RAS phonebook entry.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Ras1.PhoneBook.Add

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Send Method Example

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Count As Long

Tcp1.Timeout = 0

Count = Tcp1.Send("C:\Test.Text")

' SendBufferCount will normally be 0, indicating the data was accepted

If Tcp1.SendBufferCount > 0 Then

MsgBox "System didn't immediately accept data"

Else

MsgBox "Message accepted!"

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

In addition, you can send binary data types and structures. The following VB code snippet shows how user-defined types and the Lset command can be used to send data in binary formats (in C++, a union construct or a simple cast would be used to accomplish the same thing):

Private Type MyStruct

i As Integer

l As Long

End Type

Private Type ByteStruct

b(6) As Byte ' b MUST be the same length as i and l from MyStruct

End Type

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Count As Long

Dim x As MyStruct, y As ByteStruct

x.i = 127 ' a binary integer

x.l = 12612324 ' a binary long

LSet y = x ' move the data into a structure that is a single Byte array

Count = Tcp1.Send(y.b) ' send the Byte array that has the binary data in it

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


State Event Example (TCP Control)

This VB example shows how to verify the value of the State property.

Private Sub Tcp1_State()

' State of the Tcp1 connection has changed...put up user feedback

Select Case Tcp1.State

Case tcpConnecting

Label1.Caption = "Client Connecting..."

Case tcpConnected

Label2.Caption = "Client Connected to " & Tcp1.RemoteAddress

Case tcpClosing

Label3.Caption = "Client Closing..."

Case tcpClosed

Label4.Caption = "Client Closed"

End Select

End Sub


Trace Method Example

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Tcp1.Trace "Debug.txt", True, True, vbCrLf & "Sent: ", vbCrLf & "Recv: "

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Private Sub Command2_Click()

On Error GoTo OnError ' use intrinsic error handling

Tcp1.Trace

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Addresses Property Example (System Object)

Private Sub Command1_Click()

Dim Address As Variant

Dim System As New System

For Each Address In System.Addresses

List1.AddItem Address

Next

End Sub

The count of IP addresses is returned by:

Dim AddressCount As Long

AddressCount = System.Addresses.Count

such that:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim System As New System

Dim AddressCount As Long

AddressCount = System.Addresses.Count

List1.AddItem AddressCount

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Therefore, the above iteration could also be performed as:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Dim Address As Variant

Dim System As New System

Dim I As Integer

For I = 1 To System.Addresses.Count

List1.AddItem System.Addresses(I)

Next

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Close Method Example (TCP Control)

Blocking Example:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Timeout value indicates a 1 second blocking operation

Tcp1.Timeout = 1000

Tcp1.Close

' didn't go to OnError, so we closed before 1 second elapsed!

MsgBox "Graceful Closed!"

Exit Sub

OnError:

' no close within 1 second, or other error (Tcp1.State is tcpClosed)

MsgBox "Aborted!"

End Sub

Non-Blocking Example:

Private Sub Command2_Click()

' intrinsic error handling is of limited value for asynchronous connections

Tcp1.Timeout = 0

Tcp1.Close

End Sub

Private Sub Tcp1_State()

If Tcp1.State = tcpConnected Then

MsgBox "Connected!"

ElseIf Tcp1.State = tcpClosed Then

MsgBox "Closed!"

End If

End Sub


Connect Method Example (TCP Control)

Blocking Example:

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Tcp1.Timeout = 1000

Tcp1.Connect "www.dart.com", 80

' didn't go to OnError, so we connected before 1 second elapsed!

MsgBox "Connected!"

Exit Sub

OnError: ' Any error jumps here

' no connection within 1 second, or other error (Tcp1.State = tcpClosed)

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Non-Blocking Example:

Private Sub Command1_Click()

' intrinsic error handling is of limited value for asynchronous connections

Tcp1.Timeout = 0

Tcp1.Connect "www.dart.com", 80

End Sub

Private Sub Tcp1_State()

If Tcp1.State = tcpConnected Then MsgBox "Connected!"

End Sub


Socket Property Example

Private Sub Daemon1_Accept()

' Timeout property MUST be set to 0 for server operation

Tcp1.Timeout = 0

Tcp1.Socket = Daemon1.Accept

End Sub


Close Method Example (Telnet Control)

This VB example shows how to close a Telnet connection.

Private Sub Command1_Click()

On Error GoTo OnError

Telnet1.Close

If Telnet1.State = tcpClosing Then

Label1.Caption = "Connection transitioning gracefully from tcpConnected to tcpClosed."

End If

Exit Sub

OnError:

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Command Event Example (Telnet Control)

Private Sub Telnet1_Command(ByVal Command As DartTelnetCtl.CommandConstants, ByVal Opt As DartTelnetCtl.OptionConstants, SubOption As Variant)

On Error GoTo OnError ' use intrinsic error handling

Select Case Command

Case telnetSubOption

' server wants to negotiate a sub-option

If Opt = telnetTerminalType Then

' negotiate TermType suboption for VT320

Telnet1.SendCommand telnetSubOption, Opt, Chr$(0) & "vt320"

ElseIf Opt = telnetWindowSize Then

' want the server to set a window size of 80x32

Telnet1.SendCommand telnetSubOption, Opt, Chr$(0) & Chr$(80) & Chr$(0) & Chr$(32)

End If

Case telnetDo

' server wants us to enable an option

If Opt = telnetTerminalType Then

' want to subnegotiate TermType

Telnet1.SendCommand telnetWill, Opt

ElseIf Opt = telnetWindowSize Then

' want to subnegotiate Window Size

Telnet1.SendCommand telnetWill, Opt

Else

' refuse any other option being requested

Telnet1.SendCommand telnetWont, Opt

End If

Case telnetDont

' server wants to disable option&ldots;agree to it

Telnet1.SendCommand telnetWont, Opt

Case telnetWill

' server wants to enable an option

If Opt = telnetSuppressGoAhead Then

' do suppress go-aheads

Telnet1.SendCommand telnetDo, Opt

ElseIf Opt = telnetEcho Then

' do echo characters sent

Telnet1.SendCommand telnetDo, Opt

Else

' we don't agree to anything else

Telnet1.SendCommand telnetDont, Opt

End If

Case telnetWont

' fine with us

Telnet1.SendCommand telnetDont, Opt

End Select

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Connect Method Example (Telnet Control)

This VB example shows how to establish a Telnet connection.

Private Sub Command1_Click()

On Error GoTo OnError

Telnet1.Connect "catalogue.library.ubc.ca"

If Telnet1.State = tcpConnected Then

Label1.Caption = "Connection is active and can send/receive data."

End If

Exit Sub

OnError:

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Echo Property Example

Echo Property Example (Telnet Control)

Private Sub Command1_Click()

On Error GoTo OnError

Telnet1.Echo = False

Telnet1.Connect "myhost"

' the host should not echo received data

Exit Sub

OnError:

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Receive Event Example (Telnet Control)

Private Sub Telnet1_Receive()

On Error GoTo OnError ' use intrinsic error handling

Dim s As String

Telnet1.Receive s ' receive as much data as is available into a String

Text1.SelText = s ' append received data to text in the text box

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Send Method Example (Telnet Control)

This VB example shows how to send data after a connection is established.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

' Text1.Text property is necessary!

' Enter "Hello" as the Text1.Text property

Dim Count As Long

Count = Telnet1.Send(Text1.Text)

' SendBufferCount will normally be 0, indicating the data was accepted

If Telnet1.SendBufferCount = 0 Then

MsgBox "System immediately accepted data"

ElseIf Telnet1.SendBufferCount > 0 Then

MsgBox "System didn't immediately accept data"

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


State Event Example (Telnet Control)

This VB example shows how to verify the value of the State property.

Private Sub Telnet1_State()

On Error GoTo OnError ' use intrinsic error handling

' State of the Telnet1 connection has changed...put up user feedback

Select Case Telnet1.State

Case tcpConnecting

Label1.Caption = "Client Connecting..."

Case tcpConnected

Label2.Caption = "Client Connected to " & Tcp1.RemoteAddress

Case tcpClosing

Label3.Caption = "Client Closing..."

Case tcpClosed

Label4.Caption = "Client Closed"

End Select

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


TermType Property Example (Telnet Control)

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Telnet1.TermType = "vt320"

Telnet1.Connect "myhost"

' VT320 terminal type is requested

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Click Event Example (VT Control)

This VB example shows how to display that a user has clicked the mouse button on the VT Control window.

Private Sub Vt1_Click(ByVal xPos As Long, ByVal yPos As Long, ByVal Click As DartVtCtl.ClickConstants, ByVal Keys As DartVtCtl.VirtualKeyConstants)

On Error GoTo OnError ' use intrinsic error handling

If Keys Or vtControl Then

MsgBox "The mouse was clicked inside the VT Control window."

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Display Method Example (VT Control)

This VB example shows how to display a text string.

Private Function CSI(s As String) As String

CSI = Chr(27) & "[" & s 'CSI = Esc [

End Function

Private Sub Form_Load()

On Error GoTo OnError ' use intrinsic error handling

Vt1.TermType = vt320_7 'Set terminal type to VT320 7-bit emulation

Vt1.Display CSI("4m") 'Underline Mode

Vt1.Display "This text is underlined and displayed on screen"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


HostCommand Event Example (VT Control)

HostCommand Event (VT Control)

Private Sub Vt1_HostCommand(ByVal Attr As DartVtCtl.AttributeConstants, Value As Variant, Ignore As Boolean)

On Error GoTo OnError ' use intrinsic error handling

Select Case Attr

Case vtTabs

MsgBox "Host is setting tabs to " & Value

Case vtTerminal

If Value = vt100 Then

MsgBox "Host is changing terminal emulation to vt100"

Else

MsgBox "Host is changing terminal emulation to non-vt100"

Ignore = True ' prevent host from changing to non-vt100

End If

End Select

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


KeyDown Event Example (VT Control)

This VB example shows how to display the keycode for any key a user presses, including SHIFT, CTRL, and ALT.

Private Sub Vt1_KeyDown(KeyCode As Integer, Shift As DartVtCtl.ShiftConstants, ByVal Extended As Boolean)

On Error GoTo OnError ' use intrinsic error handling

MsgBox "Key pressed was " & Str(KeyCode)

If Shift = vtShift Then

MsgBox "The SHIFT key was held down as well"

ElseIf Shift = vtControl Then

MsgBox "The CTRL key was held down as well"

ElseIf Shift = vtAlt Then

MsgBox "The ALT key was held down as well"

End If

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


KeyPress Event Example (VT Control)

This VB example shows how to display text in the Immediate window when a user presses a key.

Private Sub Vt1_KeyPress(KeyAscii As String)

On Error GoTo OnError ' use intrinsic error handling

Telnet1.Send KeyAscii

Debug.Print "Data sent to host>" & KeyAscii

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

For example, pressing w displays Data sent to host>w in the Immediate window.


NewLine Event Example (VT Control)

This VB example shows how to append to a file the line of text the cursor was positioned at before the cursor changed rows.

Private Sub Vt1_NewLine(Data As String)

On Error GoTo OnError ' use intrinsic error handling

FileNumber = FreeFile

' Open file for output - file will be created automatically if it does not exist

Open "C:\Test" For Output As #FileNumber

Print #FileNumber, "Line at " + Str(Now) + ">" + Data ' Append to file

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Vt1.Clear 'Clear the display

Vt1.Display "Hello"

Vt1.Display vbCrLf

Vt1.Display "This is a screenful!"

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


PrintCursorLine Method Example (VT Control)

This VB example shows how to send a copy of the line the cursor is currently on to the default system printer.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Vt1.Display vbCrLf & "Hello"

Vt1.PrintCursorLine 'Print the Hello

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


PrintScreen Method Example (VT Control)

This VB example shows how to send a copy of the current display screen to the default system printer.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

Vt1.Clear 'Clear the display

Vt1.Display "Hello" + vbCrLf + "This is a screenful!" + vbCrLf

Vt1.PrintScreen 'Print the entire screen, consisting of the two lines

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Resize Event Example (VT Control)

Private Sub Command1_Click()

Vt1.Rows = "10"

End Sub

Private Sub Vt1_Resize()

On Error GoTo OnError ' use intrinsic error handling

Me.Height = Vt1.Height

Me.Width = Vt1.Width

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


WebServer Control Example

You can use the WebServer Control to build integrated web-based applications containing dynamic content or build simple web servers to return static web pages. This VB example shows how to build a simple web server.

Private Sub Command1_Click()

On Error GoTo OnError ' use intrinsic error handling

'Use documents in the C:\WebPub directory - create this if necessary

WebServer1.RootDirectory = "C:\WebPub"

'Use CertificateStore to look-up security certificate desired

Dim Store As New CertificateStore

'Get the desired certificate

WebServer1.Certificate = Store.Find("ROOT", locationLocalMachine, g_SavedIssuedBy, g_SavedSerialNumber)

' Listen for secure connections on default port 443

' Listen for non-secure connections on default port 80

' Start processing requests&ldots;

WebServer1.Start

Exit Sub

OnError: ' Any error jumps here

Debug.Print "Error #" + CStr(Err.Number) + ": " + Err.Description

End Sub


Address Formats

Email addresses can be specified in three ways:

Type | Format | Example
Simple direct address | username@domain.ext | "president@whitehouse.gov"
Compound name and address with address using brackets | Name <username@domain.ext> | "Bill Clinton <president@whitehouse.gov>"
Compound comment (name) and address with comment in parenthesis | (comment) username@domain.ext | "(Bill Clinton) president@whitehouse.gov"

Multiple address strings can be specified on a single line by separating them with commas (for example, "jones@dart.com, wilson@dart.com").

When the SMTP Control sends a message, envelope information (that specifies recipient and sender addresses) is normally taken from the To, Cc, Bcc and From header labels. When this is done each address is formatted as: "<username@domain.ext>".


Default Response Headers

Default Response Header

When your applications returns from the Head Event, Get Event, Post Event, Put Event and Request Event, the WebServer control will automatically generate a response header. If you provide any of these in your event processing, they will not be replaced.

The Last-Modified header field will be constructed from the date found on the file referred to by Response.Body.UniqueName. If this is an empty string (the body is in a memory buffer), then the current date is used:

"Last-Modified: <RFC1123 Date/Time Format>"

The Date header field will be constructed from the system time:

"Date: <RFC1123 Date/Time Format>"

The Server header field will look like:

"Server: PowerTCP Web Server/1.0"

The Content-Length header field is computed from Response.Body.Size:

"Content-Length: <number of bytes>"

The Content-Type header field is constructed from the file suffix found in Response.Body.FileName if it matches one of the following values:

{".txt", "Content-Type: text/plain"},

{".doc", "Content-Type: application/msword"},

{".mcw", "Content-Type: application/msword"},

{".exe", "Content-Type: application/octet-stream"},

{".wav", "Content-Type: audio/microsoft-wav"},

{".wri", "Content-Type: application/microsoft-group"},

{".zip", "Content-Type: application/zip"},

{".rtf", "Content-Type: application/msword"},

{".pdf", "Content-Type: application/pdf"},

{".ps", "Content-Type: application/postscript"},

{".eps", "Content-Type: application/postscript"},

{".jpg", "Content-Type: image/jpeg"},

{".jfif","Content-Type: image/jpeg"},

{".tif", "Content-Type: image/tiff"},

{".mpg", "Content-Type: video/mpeg"},

{".mpeg","Content-Type: video/mpeg"},

{".mov", "Content-Type: video/quicktime"},

{".qt", "Content-Type: video/quicktime"},

{".htm", "Content-Type: text/html"},

{".html","Content-Type: text/html"},

{".lst", "Content-Type: text/plain"},

{".asc", "Content-Type: text/plain"},

{".bas", "Content-Type: text/plain"},

{".bat", "Content-Type: text/plain"},

{".c", "Content-Type: text/plain"},

{".cmd", "Content-Type: text/plain"},

{".cp", "Content-Type: text/plain"},

{".cpp", "Content-Type: text/plain"},

{".faq", "Content-Type: text/plain"},

{".for", "Content-Type: text/plain"},

{".h", "Content-Type: text/plain"},

{".hpx", "Content-Type: application/mac-binhex40"},

{".ini", "Content-Type: text/plain"},

{".m3", "Content-Type: text/plain"},

{".me", "Content-Type: text/plain"},

{".mak", "Content-Type: text/plain"},

{".met", "Content-Type: text/plain"},

{".out", "Content-Type: text/plain"},

{".p", "Content-Type: text/plain"},

{".pas", "Content-Type: text/plain"},

{".prn", "Content-Type: text/plain"},

{".tx8", "Content-Type: text/plain"},

{".wp", "Content-Type: application/wordperfect5.1"},

{".wp5", "Content-Type: application/wordperfect5.1"},

{".qcp", "Content-Type: audio/vnd.qcelp"},

{".xls", "Content-Type: application/vnd.ms-excell"},

{".ppt", "Content-Type: application/vnd.ms-powerpoint"},

{".arc", "Content-Type: application/x-gzip"},

{".art", "Content-Type: application/x-gzip"},

{".822", "Content-Type: message/rfc822"},

{".eml", "Content-Type: message/rfc822"}};


Enhanced Status Codes

Enhanced Status Codes

The enhanced mail system status codes take the general form of "class.subject.detail". The first field "class" being 2, 4, or 5 indicates whether the delivery attempt was successful. The second sub-code indicates the probable source of any delivery anomalies, and the third sub-code indicates a precise error condition. The class sub-code provides a broad classification of the status. The enumerated values of the class are defined as:

2.X.X Success

Success specifies that the DSN is reporting a positive delivery action. Detail sub-codes may provide notification of transformations required for delivery.

4.X.X Persistent Transient Failure

A persistent transient failure is one in which the message as sent is valid, but some temporary event prevents the successful sending of the message. Sending in the future may be successful.

5.X.X Permanent Failure

A permanent failure is one that is not likely to be resolved by re-sending the message in the current form. Some change to the message or the destination must be made for successful delivery.

A client must recognize and report class sub-codes even where subsequent subject sub-codes are unrecognized.

The subject sub-code classifies the status. This value applies to each of the three classifications. The subject sub-code, if recognized, must be reported even if the additional detail provided by the detail sub-code is not recognized. The enumerated values for the subject sub-codes are:

X.1.0 Other address status

X.1.1 Bad destination mailbox address

X.1.2 Bad destination system address

X.1.3 Bad destination mailbox address syntax

X.1.4 Destination mailbox address ambiguous

X.1.5 Destination mailbox address valid

X.1.6 Mailbox has moved

X.1.7 Bad sender's mailbox address syntax

X.1.8 Bad sender's system address

X.2.0 Other or undefined mailbox status

X.2.1 Mailbox disabled, not accepting messages

X.2.2 Mailbox full

X.2.3 Message length exceeds administrative limit

X.2.4 Mailing list expansion problem

X.3.0 Other or undefined mail system status

X.3.1 Mail system full

X.3.2 System not accepting network messages

X.3.3 System not capable of selected features

X.3.4 Message too big for system

X.4.0 Other or undefined network or routing status

X.4.1 No answer from host

X.4.2 Bad connection

X.4.3 Routing server failure

X.4.4 Unable to route

X.4.5 Network congestion

X.4.6 Routing loop detected

X.4.7 Delivery time expired

X.5.0 Other or undefined protocol status

X.5.1 Invalid command

X.5.2 Syntax error

X.5.3 Too many recipients

X.5.4 Invalid command arguments

X.5.5 Wrong protocol version

X.6.0 Other or undefined media error

X.6.1 Media not supported

X.6.2 Conversion required and prohibited

X.6.3 Conversion required but not supported

X.6.4 Conversion with loss performed

X.6.5 Conversion failed

X.7.0 Other or undefined security status

X.7.1 Delivery not authorized, message refused

X.7.2 Mailing list expansion prohibited

X.7.3 Security conversion required but not possible

X.7.4 Security features not supported

X.7.5 Cryptographic failure

X.7.6 Cryptographic algorithm not supported

X.7.7 Message integrity failure


MIME

Email has been the most popular network application since the invention of computer networks. Originally a way to send simple text, it has grown to send data of arbitrary complexity and form. This flexible mechanism has become a key component of corporate Information Technology everywhere.

Email is a generic term used for several protocols and data formats that describe how a message is created, delivered, and received. These standards allow machines of different hardware and operating system to communicate.

IMAP4 and POP3 protocols retrieve messages stored on an email server. SMTP sends messages from a client to a server. Messages may contain any number of elements but must be in a standard format. This format is called Multipurpose Internet Mail Extensions (MIME), which describes the layout of any mail message.

This topic covers the following:

  • Message Construction

  • Message Header

  • Message Body

  • MIME Overview

Message Construction

There are several rules for constructing valid mail messages. First, a message may only contain 7-bit data. In addition a line may not be longer than 1000 characters. Although there are standards for the transmission of a message with 8-bit data, not all mail servers support it, while all servers support 7-bit data.

A message is comprised of two sections: the header (used to describe the message) and the body (the contents of the message).

Back to Top

Message Header

The header consists of several lines, each representing a header field. A header field is a header label followed by a colon and a space, followed by one or more header values. Fields such as Subject, Date, Sender, To, and message routing information is typically found in the header.

Return-Path: <Hopscotch@dart.com>

Received: from ralph ([26.192.23.255]) by server.test.com

(Post.Office MTA v3.5 release 215 ID# 0-54045U100L2S100V35)

with SMTP id com for <RoundTree@dart.com>;

Mon, 14 Jun 1999 21:19:13 -0400

Message-Id: <4.1.19990614211653.00a4f640@206.64.128.3>

X-Sender: Smokey@214.237.21.149

X-Mailer: QUALCOMM Windows Eudora Pro Version 4.1

Date: Mon, 14 Jun 1999 21:19:20 -0400

To: don@dart.com

From: Smokey@dart.com (Smokey Jones)

Subject: Testing DartMail.dll

Mime-Version: 1.0

Content-Type: text/plain; charset="us-ascii"

Following a header is a blank line and the message body. The body contains the message data. This may be plain text for simple messages or may contain multiple parts with each part containing message text or attached files.

Back to Top

Message Body

The body contains the message data. Message bodies originally consisted of plain text with 7-bit data, like the message shown below:

The will be a staff meeting tomorrow at 10:00 in the cafeteria.

Please be prompt.

John Davis

Director of Marketing

The Widget Factory

(555)555-1234

jdavis@widget.com

Simple messages such as this are represented by the Text property of the Message Object.

As email popularity grew, a more structured form of message was required to overcome some of the limitations of the original format and add new flexibility. MIME defines a structure that allows complex message to be sent and recognized. Most email clients now support MIME messages.

Back to Top

MIME Overview

MIME was created as a standard way to address some of the limitations of the text-only format, while still maintaining compatibility with older non-MIME systems.

MIME is a collection of standard header fields that allow more complex messages to be formed:

  • The Mime-Version label specifies the version of the MIME formatting, and distinguishes a message as being MIME structured.

  • The Content-Type label describes the media type and subtype.

  • The Content-Transfer-Encoding label indicates the type of encoding applied to the message part. Base64 and Quoted-Printable and the two most common forms of encoding that turn 8-bit data into 7-bit data.

  • The Content-ID, Content-Description, and Content-Disposition labels provide additional information about the contents of the message.

  • The Content-MD5 label is used to determine if a message has been received in an unaltered state.

A simple MIME formatted message using these labels is shown below:

Return-Path: <Hopscotch@dart.com>

Received: from ralph ([26.192.23.255]) by server.test.com

(Post.Office MTA v3.5 release 215 ID# 0-54045U100L2S100V35)

with SMTP id com for <RoundTree@dart.com>;

Mon, 14 Jun 1999 21:19:13 -0400

Message-Id: <4.1.19990614211653.00a4f640@206.64.128.3>

X-Sender: Smokey@214.237.21.149

X-Mailer: QUALCOMM Windows Eudora Pro Version 4.1

Date: Mon, 14 Jun 1999 21:19:20 -0400

To: don@dart.com

From: Smokey@dart.com (Smokey Jones)

Subject: Testing DartMail.dll

Mime-Version: 1.0

Content-Transfer-Encoding: Quoted-Printable

Content-Type: text/plain; charset="us-ascii"

This is a test message.

Testing 1,2,3 Testing

Thank you,

Jeff

This message is identified as a MIME message by the presence of a Mime-Version label. The Content-Type label identifies the message as containing text using the ASCII character set. The Content-Transfer-Encoding label identifies the encoding as Quoted-Printable which allows a message to be encoded while maintaining a high degree a readability in an encoded state.

MIME messages also allow more complex messages to be created that include a mix of text, HTML, or file attachments. Each element is called a Part and is stored in the Parts property of the Message Object.

The following is an example of a message with two parts—a text part and a part containing an attached file:

Return-Path: <Hopscotch@dart.com>

Received: from ralph ([26.192.23.255]) by server.test.com

(Post.Office MTA v3.5 release 215 ID# 0-54045U100L2S100V35)

with SMTP id com for <RoundTree@dart.com>;

Mon, 14 Jun 1999 21:19:13 -0400

Message-Id: <4.1.19990614211653.00a4f640@206.64.128.3>

X-Sender: Smokey@214.237.21.149

X-Mailer: QUALCOMM Windows Eudora Pro Version 4.1

Date: Mon, 14 Jun 1999 21:19:20 -0400

To: don@dart.com

From: Smokey@dart.com (Smokey Jones)

Subject: Testing DartMail.dll

Mime-Version: 1.0

Content-Transfer-Encoding: Quoted-Printable

Content-Type: multipart/mixed; boundary="--PTCP_0123456789_PTCP"

--PTCP_0123456789_PTCP

Content-Type: text/plain

Content-Disposition: inline

Content-Transfer-Encoding: 7bit

This is a test message.

Testing 1,2,3 Testing

Thank you,

Jeff

--PTCP_0123456789_PTCP

Content-Type: application/octet-stream; name=agenda.doc

Content-Disposition: attachment; filename=agenda.doc

Content-Transfer-Encoding: base64

/9j/4AAQSkZJRgABAgEASABIAAD/7RS+UGhvdG9zaG9wIDMuMAA4Qkl
NA+kAAAAAAHgAAwAAAEgASAAAAAADAAJM//T/9AMMAlgDRwUoA/wAAg
AAAEgASAAAAAADAAJMAAEAAABkAAAAAQADAwMAAAABAAEAAQABAAAAA
AAAAAAAAAAYAgAGQGQAAAAABAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAA
AAAAAA4QklNA+0AAAAAABAASAAAAAEAAQBIAAAAAQABOEJJTQPzAAAA
&ldots;

&ldots;

AAAAAA4QklNA+0AAAAAABAASAAAAAEAAQBIAAAAAQABOEJJTQPzAAAA
--PTCP_0123456789_PTCP--

The Content-Type label "multipart" in the header identifies this message as a message containing multiple parts. The "boundary" value also identifies the string used to separate the parts.

As you can see from the first part of the message, each part has a header (Header property) that identify the contents of the part. The first portion is a text message; an equivalent part could be created with the AddText method. The second portion of the message include a file attachment (agenda.doc) that has been Base64 encoded to ensure the data is 7-bit data only. An equivalent part could be created with the AddAttachment method.

PowerTCP manages composition with the AddText, AddAttachment, and AddMessage methods. If one on these methods doesn't fit your needs, you may create more complex messages, such as alternative message representations, by directly manipulating the message objects.

Back to Top


Threading Model

Most PowerTCP Controls are marked as Apartment Model Threaded. PowerTCP Controls contain multi-threaded protection for all global and static variables, making it safe for use in applications that use the same component in multiple Single Thread Apartments (STAs).

Single-threaded Applications

Most application developers develop single-threaded applications (the application has only one STA). Most of the sample applications included with PowerTCP Controls are written using this model. When Timeout is greater than 0, the communication components process Windows messages for the thread, allowing the user interface and all other windows to function normally.

Multi-threaded Applications

In Visual Basic you can make a multi-threaded application by creating an ActiveX executable with special objects that are created using CreateObject(). The WebServer application, included with the PowerTCP Winsock Tool, was written using this technique. Each connection is managed within a unique STA, so busy threads do not interfere with the main STA that processes user interface messages and windows.

When you use PowerTCP on Active Server Pages, each page operates within its own STA, making IIS a multi-threaded application.

Within Visual C++, you can likewise create multiple STAs for your application, and safely use one or more PowerTCP Controls within each STA.


Simple SNMP Agent

The following Visual Basic code snippet illustrates how a simple agent might be coded (error checking is omitted for clarity):

Private Sub Form_Load()

' Use non-blocking operation

Udp1.Timeout = 0

' turn on the Udp object...port 161 is used for agents

Udp1.Open 161

End Sub

Private Sub Udp1_Receive()

' an SNMP message has arrived

Dim Packet() As Byte

Dim Address As String

Dim Port As Long

Dim Message As SnmpMessage

' get the message from the system

Udp1.Receive Packet, Address, Port

' decode the message

Message.Decode Packet

If Message.Type = snmpGet1 Then

' use the existing object model to respond with Value info

Message.Type = snmpResponse1

Dim Variable As SnmpVariable

For Each Variable In Message.Variables

' check Variable.Oid for the OID being referenced

' set Variable.Value to the value of the OID

Next

Next

' now, send encoded back to the source address/port

Message.Encode Packet

Udp1.Send Packet, Address, Port

End Sub


Simple SNMP Manager

The following Visual Basic code snippet illustrates how a simple manager might be coded (error checking is again omitted for clarity):

Dim Message As New SnmpMessage

Dim Variable As New SnmpVariable

Dim Udp As New Udp

Dim Packet() As Byte

Message.Type = snmpGet1

' add the OID(s) we wish to get

Variable.Id = "1.3.6.1.2.1.1.1.0"

Message.Variables.Add Variable

' Open a port...any will do for an SNMP manager

Udp.Open

' Encode the packet into a Byte array

Message.Encode Packet

' Send the message to port 161, the default port for SNMP agents

Udp.Send Packet, "my.snmp.agent", 161

' Block for up to a second and get the reply

Udp.Timeout = 1000

Udp.Receive Packet

' Decode the packet

Message.Decode Packet

' Put the variable value into a text box for viewing

Text1.Text = Variables[1].Oid & ": " & Variables[1].Value


stub

This is a stub to act as a placeholder so books without pages will show up when compiled.