Using the jsHTTP2.EXE Component

Version 1.12.826 (now supports Windows Vista/7)

JSWare   •   www.jsware.net   •   jsware@jsware.net


Introduction


Download files...
Downloader Object  
Using jsHTTP2.Downloader

Properties:
Port
Online
ProxyConnection
Busy
CurSize
CurFileAsString
ServerHeader, ServerCode
ErrorString

Methods:
RequestFile
WriteTextFile
WriteBinaryFile
DisconnectNetwork

Events:
OnConnect
OnDisconnect
OnDownloadFinish

Get remote host name and geographical
location from an IP address...
IPInfo Object  
Using jsHTTP2.IPInfo

Properties:
Timeout
Busy
ErrorString

Methods:
EnableHostNameData
GetHostNameFromIP
EnableLocationData
GetLocationFromIP

Events:
OnHostNameResult

Location Object
Create/extract from .gz files.
Plus numerous functions for high-efficiency
binary file read/write from script...
FileOps Object  
Using jsHTTP2.FileOps

Properties
ErrorNumber
ErrorString
FileSize

Methods:
OpenFile
FileRead
FileWrite
StoreBytes
StoreString
CopyBytes
ReplaceBytes
GetBytes
GetStoreSize
StoreExists
Zip
Unzip
GZipFile
GUnzipfile
CloseFile
DeleteFile
DeleteStore, ClearStorage

BytesToLong
LongToBytes
License

Introduction

   jsHTTP2.exe is an ActiveX EXE that has three objects:

jsHTTP2.Downloader can be used to download files via HTTP using script.

jsHTTP2.IPInfo has functions to translate IP addresses to host names and to find the location (city, state, country) of specific IP addresses. jsHTTP2.IPInfo is designed especially for use with web server "raw" logs. Anyone who has a hosted website will generally have access to the server logs. jsHTTP2.IPInfo can be used in writing scripts to process those logs for information about website visitors.

jsHTTP2.FileOps provides methods to read/write files and to compress/decompress with GZip compression.

   The three objects have different functionality and work separately. See each "Using...." topic for a more detailed introduction to each object.

Using jsHTTP2.exe:

   An ActiveX EXE is a COM object. It must be registered on the system, either by running the EXE once before use, or by using the RegSvrEXE.vbs script. If it is not registered you will receive an error: "Could not create ActiveX object..." when using CreateObject.

   The three objects can be created with CreateObject and provide various properties and methods that are available to any COM compatible programming system, such as VBScript. (jsHTTP2 can also be used by compiled software written in VB, C++, etc., though it is not optimized for that purpose. It uses variant data types and extensive "wrapping" of functionality in order to provide a simple and intuitive set of functions for scripting.)

   As an EXE, jsHTTP2 can also provide events, used in the process of downloading files, and also used in the process of translating IP addresses to host names. So using jsHTTP2.exe is somewhat like using InternetExplorer.Application, as opposed to using a COM/ActiveX DLL.

jsHTTP2 Requirements:

   jsHTTP2.exe should run on all Windows versions, from at least Win98 upward. With version 1.12, Windows Vista/7 is supported. Not all functions have been thoroughly tested on Vista/7, but it should work fine. The only likely problems would be those related to Vista/7 restrictions. (For instance, if you try to download files to a location where you don't have write permission it may not work.)


   See the accompanying sample scripts for code that demonstrates the use of jsHTTP2. The downloader.vbs sample demonstrates downloading files. The IPInfo.vbs sample will process a log file dropped onto it, writing a second version where the IP addresses have been converted to host name/location data. (Both files may need minor editing before use. See the comments at the top of each file for explanation.) The other two .vbs files demonstrate usage of the newer FileOps object.


Using jsHTTP2.Downloader

   jsHTTP2.Downloader uses Windows "sockets" functionality - winsock - to download files. It inititiates contact with the remote server and carries out the "conversation" required to retrieve a file via http or ftp. Using winsock is efficient because it "cuts out the middleman". (Most popular download techniques rely on Internet Explorer functionality.)

   Winsock must be initialized before use and disconnected after. When downloading files with the RequestFile method, winsock will be started on the first download, without any need to specifically start it. The best way to use jsHTTP2.Downloader is to check the error code returned on the first download attempt. Any single-digit errors will indicate that the method failed while starting winsock, before the download was attempted. In that case the problem must be resolved before again attempting a download. (Check the ErrorString property for a description of the error.) Once winsock has been initialized, any number of files can be downloaded by using the RequestFile method and then waiting for the OnDownloadFinish event. The Busy property provides a way to keep the script looping between the time a server request is made and the time that download is completed (or fails). The Downloader object sets Busy to True when beginning a download attempt and sets it to False when finished.
   When all downloading is finished, ideally DisconnectNetwork should be called. While winsock will be disconnected and "cleaned up" when the object is set to Nothing, it's best to specifically disconnect if the object is not being immediately disposed of.

Important: The object should always be set to Nothing before ending your script. As an ActiveX EXE, it may remain running otherwise.

Back to Top

Properties, Methods and Events of jsHTTP2.Downloader
Property Port
• Sets the port number for connection. Default is 80.
ex.:
TP.Port = 81

Back to Top

Property Online
• Whether there is currently an online connection. Boolean. Read-only.
ex.:
If TP.Online = True Then ...

Notes: An online connection must be present for jsHTTP2 to work. There is no connecting or dialup functionality.


Back to Top

Property ProxyConnection
• Whether the online connection is through a proxy. Boolean. Read-only.
ex.:
If TP.ProxyConnection = True Then ....

Notes: There may be special considerations if you are using a proxy connection. jsHTTP2 contacts a specified server address to request files for download. It may not always work through a proxy connection.


Back to Top

Property Busy
• Whether jsHTTP2 is currently busy with a server transaction. Boolean. Read-only.
ex.:
If TP.Busy = True Then ....

Notes: Property Busy is used to keep a script alive while using jsHTTP2. Since it takes time to contact a server and download a file, a script waiting for the download to finish must have a way to maintain the pause without quitting. Busy provides that method. When jsHTTP2 successfully sends a file request Busy is set to True. When the OnDownloadFinish event occurs, Busy is set to False. The script can therefore be made to wait during downloads by using the following:
   While TP.Busy = True
    Wend
Back to Top

Property CurSize
• Returns size of current file download in bytes.
ex.:
Num = TP.CurSize

Notes: The CurSize property refers to the current download. The property is only valid after a download has finished and before another download is attempted. If you want to know the file size CurSize should be used in the OnDownloadFinish event. If it is used before that it will return 0. jsHTTP2 does not ask the server for the file size. It just records the number of bytes received. So it cannot return an accurate file size until the download is completed.

None of the file properties or functions should be used before OnDownloadFinish has occurred. They could conflict with the download process.


Back to Top

Property CurFileAsString
• Returns current file download as a single string.
ex.:
s = TP.CurFileAsString

Notes: Returns the current file download. This property must not be used before the OnDownloadFinish event. If it is used before download is completed it will return "".
   The current file is available from the time the download is completed until the time that another download is attempted.

None of the file properties or functions should be used before OnDownloadFinish has occurred. They could conflict with the download process.


Back to Top

Property ServerHeader, ServerCode
• Returns information from server.
ex.:
s = TP.ServerHeader

Notes: When a file is requested from a server online, the server returns an error code that indicates the status of the request. For example, 200 means "OK", 404 means "no such file", etc. (ServerCode is the same thing as ResponseCode returned by the OnDownloadFinish event. The ResponseString parameter in that same event returns the equivalent of Err.Description -- the text description of ServerCode.)

   The server also returns a "header", prepended to the requested file, which consists of several lines of descriptive text. The server header may or may not be useful. It generally contains data such as date/time, file type, etc. The file type, returned in the field "Content-Type", may be useful if you want to automate multiple downloads and design the script to decide whether the files should be written to disk as text or as binary. For example, if the server returns
Content-Type: text/html then the file is clearly text. (While all files can be saved as binary files, only text should be saved as a text file. The difference is that when saving a text file, jsHTTP2 adjusts the line returns to fit the Windows standard format. If you download a text file from a Unix/Linux server and save it as a binary file you will find that you have a text file with lots of little "boxes" in the text and no line returns. That is because Unix format uses Chr(10) - vbLf - as a line return while Windows uses Chr(13) Chr(10) - vbCrLf.)

Back to Top

Property ErrorString
 • Holds an error description when the functions RequestFile, WriteBinaryFile, or WriteTextFile fail.

Back to Top

Sub DisconnectNetwork
• Disconnects Windows socket connection
ex.:
TP.ShutDown

Notes: DisconnectNetwork should ideally be called when download(s) are completed so that jsHTTP2.Downloader can disconnect from the Windows Socket service used for network communication.


Back to Top

Function RequestFile(Server, FilePath)
• Connect to specified server and request a file.
ex.:
LNumber = RequestFile("www.somewhere.com", "/index.html", sErr)

Server is server URL. It should be formatted as shown. Do not include "http//" or double slashes.

FilePath is the path of file on server. A file path starts with the slash after URL. For example, the file http://www.somewhere.com/articles/help/help2.html would be requested with: RequestFile("www.somewhere.com", "/articles/help/help2.html") A URL's homepage can be requested by using simply "/". Ex.:
RequestFile("www.somewhere.com", "/")

Return:
0-Request sent successfully. (This does not mean the file has been downloaded. It only means that the server was contacted and the request was sent.) Any return other than 0 will be an error code. The ErrorString property will then contain an error description. Common errors are as follows:

    Errors related to initializing Winsock:

1-System not ready for network communication.
2-Winsock version 1.1 not supported.
3-A blocking winsock is already in use.
4-The limit on number of winsock tasks has been reached.
5-Error with parameter of WSAStartup call.
6-Unknown error.
7-Windows Vista not supported.

    Errors related to requesting file:

99-SendData failed to send server request.
106-No Internet connection active.
107-Internet connection is via proxy server.
109-Winsock error - Failed to create socket. Error number:
110-Winsock error - Failed to connect to server. Error number:
111-Winsock err - Failure with WSAAsyncSelect. Error number:
112-Failed to resolve server IP address.
113-Server parameter is blank.
114-FilePath parameter is blank.

With errors 109-111 the Error number returned in the error string is a Winsock error number. The Winsock error code numbers are included in the Winsock errors.txt file.

Notes: Once a request is sent successfully the next step will be to check the returns in the OnDownloadFinish event.


Back to Top

Function WriteTextFile(Path, IfDelete)
• Writes current file download to disk as text file.
ex.:
LNumber = TP.WriteTextFile("C:\webpage.html", True)

Path - Full path of file to write.
IfDelete - Whether to overwrite if file exists.

Return:
0-Success.
With non-zero errors, the ErrorString property will contain a description.

Notes: A file can be written any time after the OnDownloadFinish event occurs with a successful result, until another download attempt is made. Save the file with this function when it is text-based and may need line return correction. (If the file originated from a Unix server, for instance, the line returns need to be "fixed".)

None of the file properties or functions should be used before OnDownloadFinish has occurred. They could conflict with the download process.


Back to Top

Function WriteBinaryFile(Path, IfDelete)
• Writes current file download to disk as binary file.
ex.:
LNumber = TP.WriteBinaryFile("C:\pic.jpg", True)

Path - Full path of file to write.
IfDelete - Whether to overwrite if file exists.

Return:
0-Success.
With non-zero errors, the ErrorString property will contain a description.

Notes: A file can be written any time after the OnDownloadFinish event occurs with a successful result, until another download attempt is made. Any file can be saved as a binary file. The WriteTextFile method just adds extra functionality to check the format of line returns in text files and "fix" them if necessary. (In some cases, such as with files originating from Unix servers, line returns may not display properly until the file's line returns have been converted to Windows format.)

None of the file properties or functions should be used before OnDownloadFinish has occurred. They could conflict with the download process.


Back to Top

Event OnConnect(ServerURL)
• Occurs when connection is made with server. In most cases this event will probably not be of use. ServerURL contains URL of server connected to.


Back to Top

Event OnDisconnect
• Occurs when connection is closed with server. In most cases this event will probably not be of use.


Back to Top

Event OnDownloadFinish(ResponseCode, ResponseString)
• Occurs when file download process is complete, regardless of whether it was successful.

Return:
   If connection with server failed, ResponseCode will be -1 and ResponseString will be a text error message.

   If server conversation was completed, ResponseCode will be the server response code and ResponseString will be the server response string. If the file was successfully, completely downloaded, server response will be 200 and the string will be "OK". Other codes can be, for example, 404- "Not found", 301- "Moved permanently", etc.

   If ResponseCode is 200 the downloaded file will be available through the jsHTTP2 file methods and properties (WriteTextFile, CurFileAsString, etc.) It can then be written to disk or returned as a text string.

Notes: In the case of server errors 301-303, which indicate the requested file is at a new URL, the ResponseString will include not only the server error string but also the server Location header, which contains the new file URL in the following format:
    Location: http://www.somewhere.com/newfile.html
So if ResponseCode returns, say, 301, one can parse ResponseString to retrieve the new URL and then repeat the RequestFile call.

Back to Top


Using jsHTTP2.IPInfo

   The jsHTTP2.IPInfo object is designed to provide scripting access to IP translation functions, especially for webmasters. Most webhosting servers will log server activity in a text log that can be accessed on the server. The log is typically formatted with one line for each "GET". In other words, each file request from a website visitor is recorded on a single line. Typically that line includes the visitor's IP address, time, file requested and size of file, as well as the referrer and userAgent strings sent by the browser. On Unix servers the format is usually very convenient for script processing, with the IP address coming first in each line. Example:
100.100.100.100 - - [28/Jan/2009:00:01:49 -0800] "GET /jsware/linzips/disp.zip HTTP/1.1" 200 ... etc.
jsHTTP2.IPInfo is for getting information from the IP address.

   There are two main operations that can be performed with the IPInfo object: Returning a host name from an IP address, and returning the originating location (city/region/country) from an IP address.

   The method GetHostNameFromIP contacts the computer at that IP address and asks for its host name. That can be a URL, like
server.acme.com or it can be a router ID in the case of high speed internet connections. A typical router ID might be something like c-20-20-20-20.hsd1.ny.comcast.net. Knowing the host name of visitors can often provide an insight into who is visiting your website.

   The method GetLocationFromIP is a second method of translating IP addresses. While GetHostNameFromIP gets the host name by contacting the website visitor's remote computer or modem (in the case of dial-up), GetLocationFromIP uses a database to find the location of your website visitor: city, region and country. The GetLocationFromIP functionality derives from a free product provided by MaxMind, inc. at maxmind.com. MaxMind makes databases for IP/geo-location reference. They also make tools for use with their database. The "Lite" version is available for free.

Important: Requirements for location information functions -

GeoLite City Database
- GeoLite City database be downloaded from maxmind.com. (Approx. 28 MB)

GeoIpComEx.dll - A COM DLL, included in this package, which must be registered.

   MaxMind makes these "Lite" version geo-location tools available for free. The GetLocationFromIP function of the IPInfo object uses GeoIpComEx.dll to read from the database file.



In order to use the IP/Location functions:
1) Go to this URL:
http://www.maxmind.com/app/geolitecity

2) Click the link to "Download the latest GeoLite City Binary Format" to get the GeoLite database.

3) Take the .dat file out of the zip file download and rename it to GeoIPCity.dat. Put that in a safe place.

4) Be sure that the file GeoIpComEx.dll has been put somewhere safe, like the System folder, and then register it by dropping it onto the RegSvr.vbs script.

5) Before attempting to use function GetLocationFromIP, call the function EnableLocationData, passing it the path to the GeoIPCity.dat database file.

The GetLocationFromIP will not work unless GeoIpComEx.dll has been properly registered and the function EnableLocationData has been called with a valid path to the GeoIPCity.dat database file.

Thank you to MaxMind for the use of their database and easy-to-use tools.
Back to Top


Properties of jsHTTP2.IPInfo
Property Timeout
   Timeout is the length of time that IPInfo will wait, after contacting a remote server, before giving up on a response. In cases where a remote server does not respond to a request for its host name, Winsock (the Windows "sockets" networking functionality) has its own internal timeout, which seems to be about 20-30 seconds. As a result, processing a large number of IP addresses can sometimes take a very long time. The Timeout property provides a way to override the standard system timeout. By default, Timeout is 5000, or 5 seconds. (The measure is in milliseconds.) It can be set at any value up to 60000 (1 minute).

   In limited testing, a setting of 2000 seemed to be too short, while 5000 seemed to be adequate, providing enough time to receive a response from virtually all servers that did eventually respond.

Back to Top

Property Busy
   Like the Busy property for the Downloader object, the Busy property of IPInfo is provided for scripting. A request to a remote server for its hostname requires waiting for a response, but a script will quit if it has nothing to do. Busy gets around that problem. When GetHostNameFromIP is called, Busy is set to True. It is set back to False with the OnHostNameResult event. By going into a wait loop after calling GetHostNameFromIP the script can keep going:
While IP.Busy = True
Wend


Back to Top

Property ErrorString
   If the function EnableHostNameData or EnableLocationData fails, ErrorString will contain a description of the error.

Back to Top

Methods of jsHTTP2.IPInfo
Function EnableHostNameData()
• Initializes winsock, a necessary preparation before calling GetHostNameFromIP. This function must be called successfully before calling GetHostNameFromIP
Ex.:
Ret = TP.EnableHostNameData()

Return:
0-success.
With non-zero return the ErrorString property will contain an error description.

Back to Top

Sub GetHostNameFromIP(IPAddress)
• Requests a host name, if possible, from an IPv4 string. This is a sub with no return value because IPInfo must wait for a response from the remote server. The "return", therefore, happens with the event OnHostNameResult.
Ex.:
TP.GetHostNameFromIP "40.40.40.40"

Back to Top

Function EnableLocationData(DBasePath)
• Prepares for location searches by loading the MaxMind library and passing it the location of the database file. A return of 0 from this function is required before calling GetHostNameFromIP.
Ex.:
Ret = TP.EnableLocationData("C:\GeoIPCity.dat")

DBasePath is the full path to the file GeoIPCity.dat. (See above for explanation.)

Return:
0-success.
With non-zero return the ErrorString property will contain an error description.

Back to Top

Function GetLocationFromIP(IPAddress)
• Returns location information, if possible, from an IP address.

IPAddress can be any valid IPv4 IP string, such as "40.40.40.40".

Return: The function returns a Location object. If location info. was obtained, the Valid property will be set to True.

Example:
Set Loc = TP.GetLocationFromIP("40.40.40.40")
  If Loc.Valid = True Then
   '-- Get location info. here. Example:
      MsgBox Loc.Country
  End If
Set Loc = Nothing


Back to Top

Events of jsHTTP2.IPInfo
Event OnHostNameResult(vIP, vHost, vErr)
• Occurs when a result is returned from a call to GetHostNameFromIP.

   This event is caused by either a response from the remote server or a timeout. If the server responds with a host name before Timeout has elapsed, vHost may contain the host name. In either case, vIP contains the IP address sent in the original call to GetHostNameFromIP.

vErr is an error code that can have the following possible values:
0-success. vHost contains the host name for the IP address held in vIP.
1-no winsock initialized. (Be sure to call EnableHostNameData first to prevent this error.)
2-IP address was not valid.
3-Unknown failure with winsock function WSAAsyncGetHostByAddr.
4-No host name. Probably server was contacted but did not provide a host name.
5-Timeout - Designated timeout elapsed without a server response.

   So, error codes 1-3 involve some kind of problem with the function. Error codes 4 and 5 are not actually errors. They indicate that either the remote server did not respond before the timeout expired [5] or the remote host did not provide host name resolution [4]. In the case of error code 4, there may be no host name service. For example, a small private server may not return a host name.

Back to Top

Location Object
   The Location object is returned by the function GetLocationFromIP. Location properties describe the geographical location corresponding to the IP address. Any of the properties may or may not be present. (In the vast majority of cases, if location data is retrieved, at least the City, Region, Country and CountryCode properties will hold data.)

Valid - Boolean. True when location information has been successfully retrieved. False otherwise.

City - City or city area where IP originated. This value seems to generally be accurate within a couple of miles, but may be false within a city. For example, if Toledo, Ohio had areas named Toledo Highlands and Maplewood, an IP originating from central Toledo might nevertheless be reported as "Maplewood". Or an IP in Maplewood might be reported as "Toledo Highlands". Since only Toledo residents are likely to know where "Maplewood" is, that level of accuracy -- or lack of it -- is not very useful, but that's how the MaxMind database has been written. (According to the MaxMind website, people who desire greater accuracy can purchase the full, retail version of the MaxMind tools.)

Region - State or region associated with IP address. Examples: OH (Ohio, US), NY (New York, US), ON (Ontario, CA), Victoria (Australia), Maharashtra (India). With the US and Canada, Region returns a 2-character state or province code.

Country - Country name associated with IP address. Examples: United States, France, Vietnam, Hong Kong.

CountryCode - 2-character country code. Examples: US (United States), MY (Malaysia), NL (Netherlands).

ZipCode - Postal code for City. Only present when Country is United States or Canada.

AreaCode - May be absent or "0" for some countries.

Back to Top

Using jsHTTP2.FileOps

File read/write functions:
   The FileOps object provides a set of functions for reading, writing and editing files. VBScript has very limited functionality for dealing with binary files and that functionality can be very slow. FileOps uses a system of storage, or "stores". A store is any block of byte data that is "in storage" for use. You can create stores by reading the data from a file or copying between stores. You can also store any string or byte array. And you can edit stores by copying between stores or replacing data in stores. You can then write or edit files by writing one or more stores to any offset in an open file. Each store also has a unique string ID.

   The idea with storage is to provide access to binary file read/write functions in a highly efficient way that does not have to be filtered through the limitations of script. Such operations are very slow in script because each byte has to be converted to a variant data type in order for script to be able to handle it. By the same token, arrays of data being sent in from script require that each array element be converted from variant to byte. The storage concept enables script to handle and edit blocks of byte data with little or no need to convert between data types.

Gzip functions:
   In addition to file read/write functions, FileOps also provides gzip functionality. GZip is a common compression method, often used in webpages. The functions here can zip or unzip a "store" or a file on disk.

   One application for the zip functions would be for downloaded files. The Downloader object downloads through a direct conversation with the remote server. Many web servers will gzip-compress web files before sending them. The way it works is that if the requesting party sends an
Accept-Encoding: gzip field in its request header, the server may compress the file before sending, in which case the server header will contain something like Content-Encoding: gzip . The Downloader.ServerHeader property contains that header. Downloader does not send an Accept-Encoding string but in rare cases a server might still send compressed data, expecting it to be handled by a browser.

   The file Decompress Flash.vbs is a demonstration of the ease with which files can be handled using FileOps. The file Decompress Flash.vbs decompresses Flash files dropped onto it. In general there is no advantage to decompressing Flash files, although in some cases when a Flash file is used to stream FLV video files the FLV path may be hard-coded into the Flash file, and that could be useful if you want to download the FLV file directly. But the Flash decompressor script is mostly just for demo. purposes.
   When a Flash file is compressed (which is most of the time) it contains a 4-byte header, then 4 bytes that indicate the full size of the decompressed file. The rest of the file is actually gzipped. The file Decompress Flash.vbs reads the header and size data, decompresses the rest of the file, then writes a decompressed version of the Flash file to disk. That particular task provides a well-rounded emo. of FileOps's functionality.

   In addition to various web-related uses like decompressing downloads or Flash files, the zip functions can be used to provide custom compression files. By creating a very simple file header you can essentially invent your own type of zip file that can be recognized and decompressed using the FileOps zip functions. There is just one notable limitation: If you use the gzip functions as a general purpose file compression tool, you will need to plan a way to include the original file size in your file header, as that is needed for decompression.

Back to Top

Properties of jsHTTP2.FileOps
Property ErrorNumber
 • Holds the error number when functions BytesToLong or LongToBytes fail. ErrorNumber is used for those functions because the return value is data. All other functions of FileOps return the error number in the function return.

Back to Top

Property ErrorString
 • Holds an error description for nearly all functions of FileOps when a function fails. The subs do not have error messages, but they do clear any current ErrorNumber or ErrorString.

Back to Top

Property FileSize()
 • Returns size in bytes of currently open file. This is the current size, taking into account any writes that have been performed.

Back to Top


Methods of jsHTTP2.FileOps
Function OpenFile(Path)
 • Opens a file for read/write operations. Any number of read or write operations may be carried out while the file is open. FileOps opens the file locked so that it cannot be accessed by other processes until the file is closed. It is important to always call CloseFile when operations with a particular file are finished.

Return: 0 on success or error code. On error, ErrorString holds an error description.

Notes: Unlike the Textstream object, FileOps allows for reading, writing and appending with an open file. And it allows those operations any number of times from any offset in the file.

Back to Top

Function FileRead(Start, LengthToRead, StorageID)
 • Reads from an open file.
Start is offset to begin read from. (First byte position is 1, not zero.)
LengthToRead is number of bytes to read.
StorageID is any unique string used to label this byte stream for later retrieval.

Return: 0 on success or error code. On error, ErrorString holds an error description.

Notes: Read operations can start from any offset and be done any number of times with an open file. There is no concept of a file pointer with FileOps.

Back to Top

Function FileWrite(Start, StorageID)
 • Writes bytes to a file.

Start is offset to begin writing. (First byte position is 1, not zero.) To append to end of file use 0.
StorageID is the name of stored byte stream to be written.

Return: 0 on success or error code. On error, ErrorString holds an error description.

Notes: Write operations can start from any offset and be done any number of times with an open file. There is no concept of a file pointer with FileOps. For example, you can read 100 bytes starting from offset 100, then write those bytes to offset 1, then append the same bytes by writing to the end of the file, etc.
   If Start is 0, write will be appended at end of file, enlarging the file automatically. (Note that FileSize returns current size. It will reflect the change resulting from an appending write operation.) If Start is any number higher than the current length of the file, that will have the same effect as 0, appending to the end of the file. Unlike the Textstream object of FileSystemObject, FileWrite can be used to overwrite (or append) any number of bytes, starting at any position in the file, at any time, so long as the file is open.

Back to Top

Function StoreBytes(StorageID, ArrayIn)
 • Provides a way for script to store a specified byte stream. This should not be a "first choice" method because the function must convert an array of variants -- sent in by a script -- to an array of bytes, which is relatively slow. But StoreBytes can be an efficient way to store small arrays that have been constructed for use in file headers, etc.
StorageID is the name of the byte stream being stored. ArrayIn is an array of byte values. (A byte is numeric data from 0 to 255.)

Return: 0 on success or error code. On error, ErrorString holds an error description.

Back to Top

Function StoreString(StorageID, StringIn)
 • Provides a way for script to store a specified byte stream. In cases where the bytes can be formed as a string this method is preferable to StoreBytes because the string can be converted to byte data in one quick step, no matter how large. StorageID is the name of the byte stream being stored. StringIn is any string.

Return: 0 on success or error code. On error, ErrorString holds an error description.

Notes: Most character strings, such as text from a text file, can be thought of as either a series of bytes or a series of characters because there is a 1-to-1 correspondence between bytes and characters. When the local code page (the language used on the PC) is for any country that does not use a "wide" character set (DBCS) there is no problem. (A unicode string has 2 bytes for each character, but in Western languages the second byte is nearly always zero and it would be read as ANSI characters by StoreString.) However, if your computer's default language is set to Chinese, Korean, or Japanese, there may be unexpected results with StoreString because a given character may be represented by 1, 2, 3, or 4 bytes.

Back to Top

Function CopyBytes(IDToCopyFrom, StartFrom, LenFrom, IDToCopyTo, StartTo)
 • Copies bytes between stores. Any number of bytes can be copied from any offset of one store to any offset of another store. CopyBytes can also be used to create a new store composed of part or all of an existing store.

IDToCopyFrom - Name of store to copy from.
StartFrom - Offset at which to begin source copy.
LenFrom - Number of bytes to copy.
IDToCopyTo - Name of store to copy to. (Will be created if not existing and if StartTo = 1.)
StartTo - Offset at which to begin destination copy.

Return: 0 on success or error code. On error, ErrorString holds an error description.

Notes: If IDCopyTo does not exist it will be created and its size will be LenFrom. However, offsets and lengths must be valid or an error will occur. Example:
Ret = Obj.CopyBytes("first", 10, 100, "second", 100)

In the example above, 100 bytes are copied from the store with ID "first" to the store with ID "second". The store "first" must be at least 109 bytes long, since bytes 10-109 will be copied. The store "second", if not being created new, must be at least 199 bytes long, since it will be written with new data from offsets 100-199. If "second" does not exist it will be created at the size of 100 bytes, but in that case StartTo must be 1.

Back to Top

Function ReplaceBytes(StorageID, Start, ArrayIn)
 • Replaces specific bytes in a store with bytes from an array. This is similar to CopyBytes, but the copied data is coming from an input array rather than from another store.

StorageID is the name of the byte stream being edited.
Start is the offset at which to begin byte replacement. (First byte position is 1, not zero.)
ArrayIn is an array of byte values.

Return: 0 on success or error code. On error, ErrorString holds an error description.

Notes: StorageID must be a valid name of an existing store. Other parameters must be valid. Example:
Ret = Obj.ReplaceBytes("first", 10, Array1)

In the example above, there must be a store named "first" and it must be at least as big as UBound(Array1) + 10. If Array1 has UBound(8) that indicates 9 elements to be replaced. If replacement is to start at offset 10 then the "first" byte stream must be at least 18 bytes long to start with.

Back to Top

Function GetBytes(StorageID, Start, Length, ReturnArray)
 • Returns an array of byte values from a store.

StorageID is the name of the store.
Start and Length indicate the starting offset and number of bytes to be copied from the store to ReturnArray.

Return: On success, return is 0 and ReturnArray holds bytes copied. On failure function return is an error code and ErrorString holds an error description.

Back to Top

Function GetStoreSize(StorageID)
 • Returns the size of a given store in bytes.

Return: On success, returns size in bytes of store identified by StorageID parameter. On error, ErrorNumber is non-zero and ErrorString holds an error description.

Back to Top

Function StoreExists(StorageID)
 • Boolean. Tests whether a specified store exists.

Back to Top

Function Zip(StorageID)
 • Compresses a given store with zlib compression. Zip compresses a byte stream, which can then be used in a custom zip-type file format.

Return: 0 on success or error code. On error, ErrorString holds an error description.

Back to Top

Function Unzip(StorageID, OriginalSize)
 • Decompresses a given store that was compressed with zlib compression. OriginalSize is required. It indicates the original size of the data before compression. Unzip decompresses a byte stream, which may have been produced using the Zip function. Unzip can also decompress the content of compressed Flash files (see sample script) and some compressed web files.

Return: 0 on success or error code. On error, ErrorString holds an error description.

Back to Top

Function GZipFile(SrcPath, DestinationZPath)
 • Creates a .gz file at path designated by DestinationZPath, compressing the file indicated by SrcPath. A .gz file uses gzip compression to store a single file. If you want to store multiple files it must be done by first joining the files together, in the manner of CAB or TAR files.

Return: 0 on success or error code. On error, ErrorString holds an error description.

Notes: SrcPath must exist, of course. If DestinationZPath exists it will be deleted.

Back to Top

Function GUnZipFile(SrcZPath, DestinationUnZPath, OverRideName)
 • Extracts the file contained in the .gz file SrcZPath, to DestinationUnZPath. OverRideName is a Boolean parameter. If set to True, the extracted file will be given the name indicated in the destination path parameter DestinationUnZPath. If set to False, the extracted file will be given the name indicated in the destination path parameter DestinationUnZPath ONLY if the .gz file does not contain the original file name. In most cases a .gz file will contain the original name of the file inside. The FileOps.GZipFile follows that standard and also stores the file name in .gz files it creates.

Return: 0 on success or error code. On error, ErrorString holds an error description. Also, on success DestinationUnZPath will hold the resulting file path, so that parameter must not be sent in as a literal. In other words, do not use
   Ret = FO.GUnZipFile("C:\file.gz", "C:\file.txt", False)
Instead use:
   s = "C:\file.txt"
   Ret = FO.GUnZipFile("C:\file.gz", s, False)

When the function returns, s will contain the actual file path, depending on whether the file name was in the .gz file and whether OverRideName was set to True or False.

Notes: SrcZPath must exist, of course. If DestinationUnZPath exists it will be overwritten.

Back to Top

Sub CloseFile()
 • Closes the currently open file. This method is harmless if called when no file is open. It should be called as quickly as possible when done with a file, as OpenFile opens a file and locks it from outside access. Usually no harm will be done by not calling CloseFile because FileOps calls it automatically whenever OpenFile is called and when the FileOps object is unloaded from memory. Nevertheless, it's best practice to call CloseFile whenever finished with a particular file. Also, note that an ActiveX EXE needs to be explicity set to Nothing in order to unload it. If jsHTTP2.FileOps is left running with a file open then that file will not be accessible.

Back to Top

Sub DeleteFile(Path)
 • Deletes a given file.

Back to Top

Sub DeleteStore(ID)     Sub ClearStorage()
 • Clear stored bytes streams. DeleteStore clears/deletes a specified storage item based on ID. There is no error raised by an invalid ID. ClearStorage clears all currently stored byte streams.

Back to Top

Function BytesToLong(Array4In)
 • Convert a series of bytes to a long integer, "little endian" style. Array4In is an array of byte values with UBound 3. The first byte is the "insignificant" byte. That is the way that numbers are normally stored in Windows files. For example, the array 0, 1, 0, 0 would return 256.

Return: Returns an integer value on success. On error, ErrorNumber is non-zero and ErrorString holds an error description.

Back to Top

LongToBytes(Number)
 • Converts a long integer value to an array of byte values with UBound 3. As above, this function is little endian. The long (32-bit) integer is represented like so: Number = Array(0) + (Array(1) * 256) + (Array(2) * 65536) + (Array(3) * 16777216)

Return: Returns an array of Ubound 3 on success. On error, ErrorNumber is non-zero and ErrorString holds an error description.

Notes: This is a signed integer. The upper range of Array(3) is negative. That is, 0, 0, 0, 127 is equivalent to 2130706432. But 0, 0, 0, 128 is equivalent to -2147483648.

Back to Top

License
   You use all script code and components from JSWare at your own risk.

   The components (compiled DLL and EXE files) may be used for personal or commercial purposes. No payment or attribution is required for either use. The components may be redistributed if they are required as support files for scripts or software that you have written.
   Also, the script code may be used freely, in part or as whole scripts, for any purpose, personal or commercial, without payment or attribution.

   I ask only that you not redistribute these scripts and components, except as required for your direct use. Instead, please direct others to obtain copies of JSWare scripts and components directly from www.jsware.net.

   Also, none of the code here may be redistributed under another license. If a work using code from JSWare is distributed with restrictions of any kind the code from JSWare must be kept exempt from those restrictions. This includes, but is not limited to, code sold for profit, code with usage restrictions and code distributed as so-called "Open Source" with redistribution restrictions.

    Joe Priestley


Back to Top

jsHTTP2   •   JSWare   •   www.jsware.net   •   jsware@jsware.net