Zip, Scan, and more - Deutschsprachige FoxPro User...

11
May 2011 FoxRockX Page 1 The dFPUG.fll has grown up. The little FLL with functions for compressing and decompressing files has become an ample collection of functions indis- pensable for many purposes. FoxPro developers are offered capabilites hitherto unknown. The History The first version of the dFPUG.fll was published in January 2004. It provided a simple ZIP functio nality. Owing to the huge feedback from developers, the second version was released in March 2005. That one made many further features of the ZIP algorithm available. Now the third version of the dFPUG.fll pro- vides substantially more functions from various functional areas. In its first two versions, the dFPUG.fll contained merely functions for creating and extracting ZIP archives. Of course those functions stay available. The ZIP functions have been described extensively in the two previous articles. Therefore they won’t be treated here in depth. New Functions The new functions may be divided into four func- tional areas. At first, there are scanning functions. They permit to control TWAIN scanners from VFP applications and to scan images. The second functional area comprises Internet and Windows API programming. Sometimes you need functions which convert a string in such a manner that it can be used as a parameter in a URL. Now there is a function for that purpose, and of course another one to execute the conversion the other way round. In a further area, entries can be added to the Windows Event Viewer. A real alternative to own log files. These functions become particularly interesting if you develop COM servers or Windows services which shall log information about their current state or errors. dFPUG.fll Version 3 – Zip, Scan, and more Venelina Jordanova, Uwe Habermann, Erich Todt And finally we have a set of functions that provide Windows system information. Dependencies The new dFPUG.fll has been written in C like its previous versions. MSVC71.dll can be registered at the target machine; if it is not registered, it must reside in the same folder as the dFPUG.fll. In both cases the dFPUG.fll can be used from any VFP 9 application from any folder on the target machine. If a MSVC71.dll is stored in a different folder and is registered there, it will be recognized by the dFPUG.fll, and it can be used from that folder. In case you want to use the dFPUG.fll together with older versions of VFP, you’ll normally have to copy the file MSVC71.dll to the target PC. For the scanning functions the file GDIPLUS. DLL is needed. Since Windows 98, that file has been present in every Windows installation, so we need not worry about it. For the individual functions, further DLLs or other files of Windows are required if need be. Those files are being loaded dynamically during runtime. Thus, to our advantage, the dFPUG.fll may in any case be loaded without problems via the command SET LIBRARY TO dFPUG.fll If in using a function a dependent DLL cannot be loaded, a corresponding return value is yielded. So the developer need not worry about error messages due to missing dependencies. The ZIP functions continue to be contained unchanged in the FLL, making the new version 3 fully upward compatible to the previous one. A sample application Naturally we have a sample application for this version of the dFPUG.fll, too. It demonstrates how to use the functions. Screenshots of the sample app are shown in the course of this article. And there are further examples about some of the functions.

Transcript of Zip, Scan, and more - Deutschsprachige FoxPro User...

Page 1: Zip, Scan, and more - Deutschsprachige FoxPro User Groupportal.dfpug.de/dfpug/Dokumente/Silverswitch/2011 FoxRockX/FR2011… · FoxPro developers are offered ... and Windows API programming.

May 2011 FoxRockX Page 1

The dFPUG.fll has grown up. The little FLL with functions for compressing and decompressing files has become an ample collection of functions indis-pensable for many purposes. FoxPro developers are offered capabilites hitherto unknown.

The HistoryThe first version of the dFPUG.fll was published in January 2004. It provided a simple ZIP functio­nality.

Owing to the huge feedback from developers, the second version was released in March 2005. That one made many further features of the ZIP algorithm available.

Now the third version of the dFPUG.fll pro-vides substantially more functions from various functional areas.

In its first two versions, the dFPUG.fll contained merely functions for creating and extracting ZIP archives. Of course those functions stay available. The ZIP functions have been described extensively in the two previous articles. Therefore they won’t be treated here in depth.

New FunctionsThe new functions may be divided into four func-tional areas.

At first, there are scanning functions. They permit to control TWAIN scanners from VFP applications and to scan images.

The second functional area comprises Internet and Windows API programming. Sometimes you need functions which convert a string in such a manner that it can be used as a parameter in a URL. Now there is a function for that purpose, and of course another one to execute the conversion the other way round.

In a further area, entries can be added to the Windows Event Viewer. A real alternative to own log files. These functions become particularly interesting if you develop COM servers or Windows services which shall log information about their current state or errors.

dFPUG.fll Version 3 – Zip, Scan, and moreVenelina Jordanova, Uwe Habermann, Erich Todt

And finally we have a set of functions that provide Windows system information.

DependenciesThe new dFPUG.fll has been written in C like its previous versions.

MSVC71.dll can be registered at the target machine; if it is not registered, it must reside in the same folder as the dFPUG.fll. In both cases the dFPUG.fll can be used from any VFP 9 application from any folder on the target machine.

If a MSVC71.dll is stored in a different folder and is registered there, it will be recognized by the dFPUG.fll, and it can be used from that folder.

In case you want to use the dFPUG.fll together with older versions of VFP, you’ll normally have to copy the file MSVC71.dll to the target PC.

For the scanning functions the file GDIPLUS.DLL is needed. Since Windows 98, that file has been present in every Windows installation, so we need not worry about it.

For the individual functions, further DLLs or other files of Windows are required if need be. Those files are being loaded dynamically during runtime. Thus, to our advantage, the dFPUG.fll may in any case be loaded without problems via the commandSET LIBRARY TO dFPUG.fll

If in using a function a dependent DLL cannot be loaded, a corresponding return value is yielded. So the developer need not worry about error messages due to missing dependencies.

The ZIP functions continue to be contained unchanged in the FLL, making the new version 3 fully upward compatible to the previous one.

A sample applicationNaturally we have a sample application for this version of the dFPUG.fll, too. It demonstrates how to use the functions. Screenshots of the sample app are shown in the course of this article.

And there are further examples about some of the functions.

Page 2: Zip, Scan, and more - Deutschsprachige FoxPro User Groupportal.dfpug.de/dfpug/Dokumente/Silverswitch/2011 FoxRockX/FR2011… · FoxPro developers are offered ... and Windows API programming.

Page 2 FoxRockX May 2011

GetWinErrorStringConverts a Win32 oder COM/OLE error number into the equivalent error message of the operating system.

Windows Event ViewerRegisterEventSourceAdds the necessary entries to the Windows registry so that event numbers can be convert-ed into a message text by the Event Viewer.

UnregisterEventSourceDeletes entries from the Win-dows registry which enter event numbers into the Event Viewer.

ReportEventAdds an entry to the Windows event list.

Windows System InformationCheckAdminRightsTells whether the user running the current thread has adminstrator rights.

ComputerNameReturns the NetBIOS or DNS name of the local computer.

GetShortPathConverts a long path name or file name into its short equivalent (MS DOS 8.3 convention).

IsWinNTTells whether the operating system is based on Windows NT (WinNT, 2000, XP, 2003, Vista).

ShellFolderThis function yields the paths to various Windows system folders.

UserNameReturns the name of the user or of the security policy under which the current thread is being executed.

ReferenceThis chapter introduces all functions in detail with their parameters and return values.

dFPUGFllVersionReturns the version number of the dFPUG.FLL or of some dynamically loaded system files. dFPUGFllVersion([nFormat])

Return valueSee table 1.

ParameterIf you don’t provide the optional parameter nFormat, the return value is identical to the value given in table 1 under nFormat = 0.

Functions by categoriesThe dFPUG.FLL provides the following functions.

GeneraldFPUGInitializeCall at initializing.

dFPUGUnInitializeCall at release.

dFPUGFllVersionReturns the version number of the dFPUG.FLL or of some dynamically loaded system files.

Compressing or extracting filesCreateZipArchiveServes to create ZIP archive files.

ExtractZipArchiveServes to extract ZIP archive files.

Scanner SupportGetTWAINSourcesDisplay the available scanners.

GetTWAINImageTrigger the scanning.

InternetUrlEscapeConverts characters which are not allowed in URLs into the respective escape sequences (“%xy”).

UrlUnescapeConverts Escape sequences (“%xy”) in a URL into readable text.

Windows API ProgrammingGetNullSAThis function returns a pointer to a SECURITY_ATTRIBUTES structure with a null­security descriptor. With this function you can, by means of Windows API functions, create files, create folders, or create kernel objects etc. with the permission All – Full access.

Figure 1. – determining the version number

Page 3: Zip, Scan, and more - Deutschsprachige FoxPro User Groupportal.dfpug.de/dfpug/Dokumente/Silverswitch/2011 FoxRockX/FR2011… · FoxPro developers are offered ... and Windows API programming.

May 2011 FoxRockX Page 3

ComputerNameReturns the NetBIOS name or DNS name of the local computer. ComputerName([nFormat])

Return valueCharacter.

CheckAdminRightsTells whether the user excecuting the current thread has administrator rights.CheckAdminRights()

Return valueLogical.

CommentsThis function only makes sense with Windows NT­based ope­rating systems (WinNT, 2000, XP, 2003, Vista).

In Windows 9x systems (Win95, 98, ME) the function always returns .T. because the operating system does not support anything we may call a real administration of user rights.

To ask for the OS platform, you can use either IsWinNT() or the FoxPro function OS(6). A return value of “2” (Look out: string!) indicates that it is a Windows NT­based operat-ing system.

Parameter nFormat

Data type Return Value Description

0 Character dFPUG Funktions- Bibliothek 03.00.7071.0

Description and complete version number. The output does not have a standardized format. If you want be able to evaluate a query about the version in a programme, better call the function with the parameter 4 or 5.

4 Character 03.03.6029.0002 Version number in a standardized format: MM.mm.YDDD.nnnnMMMain versionmmMinor versionYDDDBuild numberNNNNSerial number

5 Numeric 300 Numerical version number, calculated by the formula (100* Main version) + Minor version.

105 Numeric 600 Numerical version number of shlwapi.dll, calculated by the formula (100* Main version) + Minor version. The functions UrlEscape() and UrlUnescape() require the file shlwapi.dll version 5.0 or higher. This file is part of the operating system or is installed with the Internet Explorer respectively.

205 Numeric 700 Numerical version number of wininet.dll, calculated by the formula (100* Main version) + Minor version. The function CrackUrl() requires the file wininet.dll version 3.0 or higher. This file is part of the operating system or is installed with the Internet Explorer respectively.

Table 1. – Parameters and return values of dFPUGFllVersion

Figure 2. – display of the computer name

Page 4: Zip, Scan, and more - Deutschsprachige FoxPro User Groupportal.dfpug.de/dfpug/Dokumente/Silverswitch/2011 FoxRockX/FR2011… · FoxPro developers are offered ... and Windows API programming.

Page 4 FoxRockX May 2011

delimited from each other by periods, for example “www.dfpug.de”.

A cluster is a group of two or more servers (aka nodes) which cooperate and appear in the network as one single virtual server.

With DNS names, uppercase and lowercase spelling are not discerned.

The fully qualified DNS name is a combination of the DNS host name and the DNS domain name, written in the form HostName.DomainName. For instance, if the DNS host name is “corporate­mail­server” and the DNS domain name is “dfpug.de”, then the fully qualified DNS name will be “corporate­mail­server.dfpug.de”.

NetBIOS names consist of up to 15 bytes of OEM characters, and as a rule one character equals one byte. However, some country­specific OEM characters can be two bytes long.

With NetBIOS names, uppercase and lower-case spelling are in principle not discerned, but uppercase spelling is preferred, especially so if the conversion from lowercase to uppercase letters is dependent on the OEM character set.

The NetBIOS name and the DNS host name depend on each other. Whenever you change the DNS host name, the NetBIOSname is changed as well and truncated to 15 bytes. E.g. if the DNS name is “corporate­mail­server”, the NetBIOS name “corporate­mail­” will result from this.

If you change the name of a computer, you will have to restart it to let the changes take effect. The NetBIOS name is read from the Windows Registry during startup.

CreateZipArchiveServes to create ZIP archives.CreateZipArchive( cPath, cFileSkeleton, cArchiveFullPathName, cFeedbackFunction, nCompressionLevel, lResurseSubfolders, cPassword )

ParameterWhen you call the function without parameters, it yields the NetBIOS name of the local computer. If the local Computer is a node in a cluster, the function will return the NetBIOS name of the virtual cluster server.

By providing the optional parameter nFormat you can determine not only the NetBIOS name, but also the DNS name of the computer, of the host or of the domain. This applies to Windows 2000 or higher versions. In the table below you find the valid values for nFormat and the respective return values. If the local computer is a node in a cluster, the function yields the value shown in the column “node”.

In case the name of the computer cannot be determined in the given format, or if the value for nFormat is not valid, the function will return an empty string.

CommentsSystem requirements: The optional parameter nFormat is only supported on Windows NT­based operating systems from Windows 2000 upwards. With all other operating sysystems (Win95, 98, ME, NT4) the function produces the FoxPro error 1098 with a matching error message text, e.g. ”This function is not supported by the operating system”.

Calling this function without the optional parameter nFormat is supported in all Windows operating systems on which Visual FoxPro can run.

You may either use IsWinNT() or the FoxPro function OS(6) to inquire about the OS platform. A return value of “2” (Attention: string!) means that it is a Windows NT­based opearting system.

You can employ the FoxPro function OS(3) to determine the main version number of the operating system. E.g. in Windows 2000, OS(3) returns the string “5”.

DNS names constist of one or several components, each one up to 63 characters long and

Parameter nFormat Return value node

N/A NetBIOS name of the local computer. NetBIOS name of the virtual cluster server.0 NetBIOS name of the local computer. NetBIOS name of the virtual cluster server.1 DNS host name of the local computer. DNS host name of the virtual cluster server.2 DNS domain name of the local computer. DNS domain name of the virtual cluster server.3 Fully qualified DNS name which uniquely

identifies the local computer.Fully qualified DNS name of the virtual cluster server.

4 NetBIOS name of the local computer. NetBIOS name of the local computer.5 DNS host name of the local computer. DNS host name of the local computer.6 DNS domain name of the local computer. DNS domain name of the local computer.7 Fully qualified DNS name which uniquely

identifies the local computer.Fully qualified DNS name of the local computer.

Table 2. - Parameters and return values of ComputerName

Page 5: Zip, Scan, and more - Deutschsprachige FoxPro User Groupportal.dfpug.de/dfpug/Dokumente/Silverswitch/2011 FoxRockX/FR2011… · FoxPro developers are offered ... and Windows API programming.

May 2011 FoxRockX Page 5

The archive file 1. cArchiveFullPath-Name already exists.Beginning to add the file 2. tcCurrent-OperatedFile to the archive.Finish of adding the file t3. cCurrent-OperatedFile to the archive.The file 4. tcCurrentOperatedFile could not be added to the archive.The creation of the archive was com-5. plete and has been concluded.The creation of the archive could not 6. be concluded.No valid path name or file name was 7. given, or there are no files to be put into the archive.

tnAllFilesSize Total size of all files which shall be added to the archive.

tnZIPedFilesSize Size of the files that have already been add-ed to the archive.

tnArchiveCurrentSize Current size of the created archive file.nResult The return value controls the further behaviour of the function CreateZipArchive():

0 The process shall be aborted.1 The files have been added to the archive.2 The process is being continued.

nCompressionLevel The ZIP algorithm permits different levels of com-pression. The values ­1 to 9 are allowed. The values mean:

-1 Standard compression (identical to the value 6)

0 No compression 1 Maximum speed 6 Standard compression 9 Best compression

lResurseSubfoldersIf the value of this parameter is .T., sub­folders are recursively included. The files selected as cFileSkeleton are being taken care of in the sub­folders, too.If the value of this parameter is .F., sub­folders are not included.

cPassword Here a password must be put in if the archive shall be protected. In case you do not need a password protection, an empty string must be put in here. For the password, all characters except for CHR(0) are permissible.

Return valueNot defined. Status messages are given via the FeedBack function.

Parameters

cPath Character. Path of the folder which is to be archi­ved.

cFileSkeletonCharacter. Names of the files to be archived. The wildcards “?” and “*” can be used. Several file names may be given, separated by semicolon.

Example: “*.dbf;*.fpt;*.cdx”

cArchiveFullPathNameCharacter. Complete path name and file name of the ZIP archive to be created.

cFeedBackFunction Character. Name of a function or method which is called by CreateZipArchive() to reveal information about the progress. This function or method must be declared thus:[Object.]<FeedBackFunction_Name>( tcCurrentOperatedFile, tnState, tnAllFilesSize, tnZIPedFilesSize, tnArchiveCurrentSize ): nResult

tcCurrentOperatedFile name of the file which is currently being pro-cessed.

tnState Current state:

Figure 3 .– Example of creating ZIP archives

Page 6: Zip, Scan, and more - Deutschsprachige FoxPro User Groupportal.dfpug.de/dfpug/Dokumente/Silverswitch/2011 FoxRockX/FR2011… · FoxPro developers are offered ... and Windows API programming.

Page 6 FoxRockX May 2011

The process could not be finished.6. Reserved.7. Invalid password.8.

tnArchiveFilesSizeSize of the archived files.

tnUnZIPedFilesSize Size of the files already unpacked.nResult The return value controls the further behaviour of the function ExtractZipArchive():

0 The unpacking shall be aborted.1 The process shall be continued.

2 Overwriting the existing file with the archived file.

cPassword Here a password must be put in if the archive is protected by a password. In case you do not need a password protection, an empty string must be passed here. For the password, all characters except for CHR(0) are permissible.

CommentsAs the return value is not defined, you should never try to evaluate or save the result of this function.

GetTWAINSourcesGetTWAINSources(@tcTwainSources) – Returns a list of the available TWAIN devices connected to the computer.

Return value0 – If the operation has been completed success-fully.

CommentsAs the return value is not defined, you should never try to evaluate or save the result of this function.

ExtractZipArchiveService to unpack ZIP archive files. ExtractZipArchive( cExtractFilesFolder, cFileSkeleton, cArchiveFullPathName, cFeedBackFunction, cPassword )

Return valueNot defined. Status messages happen via the FeedBack function.

ParameterscExtractFilesFolder Character. Folder where the unpacked files are being stored.

cFileSkeleton Character. Names of the files to unpack. The wildcards “?” and “*” may be used. Several file names can be given, separated from each other by semicolons.

Example: “*.dbf;*.fpt;*.cdx”

cArchiveFullPathName Character. Complete path and file name of the archive file to be unpacked.

cFeedBackFunction Character. Name of a function or method which is called by ExtractZipArchive() to yield information about the progress. This function or method must be declared as follows: [Object.] <FeedBackFunction_Name>( tcCurrentOperatedFiles, tnState, tnArchiveFiles-Size, tnUnZIPed-FilesSize ): nResult

tcCurrentOperatedFiles Name of the file which is cur-rently being unpacked.

tnState Current state:

The file to be 1. unpacked does alerady exist.Begin of the 2. unpacking of the file tcCurrentOperatedFile.End of the unpacking of the file 3. tcCurrentOperatedFile.The file 4. tcCurrentOperatedFile could not be unpacked.The process has been finished 5. successfully

Figure 4. – The Scan dialogue of the sample application

Page 7: Zip, Scan, and more - Deutschsprachige FoxPro User Groupportal.dfpug.de/dfpug/Dokumente/Silverswitch/2011 FoxRockX/FR2011… · FoxPro developers are offered ... and Windows API programming.

May 2011 FoxRockX Page 7

ParameterIn case you call the function without a parameter, the element bInheritHandle of the SECURITY_ATTRIBUTES structure created is initialized as FALSE. lInheritHandle

lInheritHandle Description.F. The element bInheritHandle of

the SECURITY_ATTRIBUTES structure created is initialized as FALSE.

.T. The element bInheritHandle of the SECURITY_ATTRIBUTES structure created is initialized as TRUE.

The exact meaning of the element bInheritHandle is mostly different among the individual Windows API functions. You will find further information in the documentation of the respective Windows API functions.

Example of usageA typical example would consist in using FoxPro as a debugger to which other applications are sending information. As a communication interface you could use e.g. a Named Pipe or a FileMapping object. The latter is being created by the debugger with a null­security descriptor; thus it can be opened to write by the single applications, independent of their user context.

CommentsThe memory reserved by this function is released automatically upon the release of the dFPUG.FLL.

It can constitute a considerable security risk to permit every user full control of a file, a folder, or a kernel object. Therefore you should only consider doing this in particular cases and deliberate it thoroughly.

You should never store the return value of this function in a variable, but always call this function and pass the result directly to your Windows API function.

If you declare a Windows API function in FoxPro with DECLARE­DLL, you have to declare the data type Integer for lpSecurityAttributes.

If you pass 0 (zero) for lpSecurityAttributes to a Windows API function, this usually means that the file to be created (or the folder or the kernel object) takes the security attributes of the current thread or the superior object. But in any case it does not mean that the permissions are set to Everyone. Further information you will find in the documentation for the respective Windows API functions.

In practice you can mostly leave out lInheritHandle and thus initialize the element bInheritHandle of the SECURITY_ATTRIBUTES structure with FALSE.

nErrorNumber – If an error has occurred. Cf the TWAIN error messages.

ParametertcTwainSources – A string, passed via a reference. In this string, a semicolon­delimited list of available TWAIN devices is returned.

GetTWAINImageGetTWAINImage(tcFileName, tcFileFormat, tlUseDefaultTWAINSource, tcTWAINSource, tlDisplayAdvancedSettingsDialog, tlDisplayprogressDialog) – Scans an image and stores it in the file tcFileName.

Return value0 – If the process has been executed successfully.nErrorNumber – if an error has occurred, TWAIN error message.

ParameterstcFileName – Complete path and file name of the file in which the scanned image shall be stored.tcFileFormat – Name extension of the file format. The value can be BMP, JPG, GIF, PNG, or TIFF. When this parameter is empty, the standard value is TIFF.tlUseDefaultTWAINSource – If the value is .T., the default TWAIN device will be used. When this parameter is empty, the default value .T. is applied.tcTWAINSource – string with the TWAIN source to be used. If the value of tlUseDefaultTWAINSource is .F. and if the value of the property tcTWAINSource is empty and more than one TWAIN device is connected, a dialogue to choose the TWAIN device is shown.tlDisplayAdvancedSettingsDialog – When this value is .T., a dialogue with advanced settings shows. De-pending on the TWAIN source used, this dialogue may possibly not be available. If this parameter is empty, the default value .F. is used.tlDisplayprogressDialog – When this value is .T., a progress bar is displayed. If this parameter is emp-ty, the default value .T. is used.

GetNullSAReturns a pointer to a SECURITY_ATTRIBUTES structure with a null­security descriptor.

You can pass this pointer as a LPSECTURITY_ATTRIBUTES parameter to Windows API functions in order to create files, folders, or kernel objects etc. to which all users have access without limitation (Permissions: Everyone – Full Control). GetNullSA([lInheritHandle])

Return valueNumeric.

Page 8: Zip, Scan, and more - Deutschsprachige FoxPro User Groupportal.dfpug.de/dfpug/Dokumente/Silverswitch/2011 FoxRockX/FR2011… · FoxPro developers are offered ... and Windows API programming.

Page 8 FoxRockX May 2011

ExampleIn the following example we create two new folders, one of them with the standard permissions and the other with Everyone – Full Control. SET LIBRARY TO dfpug.fll

DECLARE Integer CreateDirectory ; IN WIN32API ; String lpPathName, ; Integer lpSecurityAttributes

*-- Create a folder with standard access*-- rights:CreateDirectory(SYS(2015)+”_Standard”,0)

*-- And now a folder with full access for all *-- users:CreateDirectory(SYS(2015)+”_Everyone”,GetNullSA())

You can check the difference between the two folders by marking one in the Windows Explorer and a right mouse click to open the Properties in the context menu.

NoteIn some newer operating systems (like Windows XP Professional without domain membership), in order to see the above mentioned tabs Sharing and Security in the Properties window, you will have to deactivate “use simple file sharing” in the folder options in the Windows Explorer.

GetWinErrorStringWhen an error occurs, many Windows API functions and COM/OLE objects return a numerical value which represents an error code or a status code, though in some cases it can mean a warning or a message about a successful operation (e.g. 0 = ERROR_SUCCESS).

This function converts such a Win32 or COM/OLE error number to the corresponding error message of the operating system. Apart from this, up to three parameters can be passed which are inserted in place of the wildcard characters [1], [2], and [3], provided that the message text contains these wildcards.

Note: The Win32 error numbers are completely different from FoxPro or TWAIN error numbers as regards their scope and their meaning. They must not be mixed up.GetWinErrorString( nErrorCode [, [cParam1] [, [cParam2] [, cParam3 ]]] )

Return valueCharacter. If the operating system provides no error message for nErrorCode , the function returns the empty string.

Some Win32 error messages contain wildcards to be replaced by application­specific strings, e.g.

nErrorCode = 34 (ERROR_WRONG_DISK). If the optional parameters cParam1 to cParam3 are not given, the returned message text contains the wildcards, e.g. [1], [2] or [3].

ParametersnErrorCode Numeric Win32 error number between ­2147483648 and 2147483647 (0x00000000­0xFFFFFFFF). COM/OLE error numbers are by definition negative number values which can also be stated as hexadecimal. For example, E_OUTOFMEMORY is defined as 0x80000002, and it can be passed to the function either as 0x80000002 or as ­2147483646. Values between 2147483648 (0x80000000) and 4294967295 (0xFFFFFFFF) automatically get converted into negative number values.

cParam1 Optional. When the message text contains a wildcard “[1]” and a string is given for cParam1, the function replaces the wildcard with the string.

cParam2 Optional. When the message text contains a wildcard “[2]” and a string is given for cParam2, the function replaces the wildcard with the string.

cParam3 Optional. When the message text contains a wildcard “[3]” and a string is given for cParam3, the function replaces the wildcard with the string.

CommentsIn case the operating system supports several language versions, the function will search for the message text in the following sequence:

Current Visual FoxPro localization 1. Language­neutral2. Language setting of the threads3. Default language setting of the user 4. Default language setting of the system 5. English (USA) 6.

In addition to this, if the system itself supplies no message text, the function tries to load the following file and to retrieve the message text in it:

Module Error numbers Declaration Comments

wininet.dll From 12000 to 12999

wininet.h Microsoft Win32 Internet API

If the message text concludes with one or several of the characters CR, LF, TAB, or SPACE, the function automatically chops them off.

With an OLE error you can determine the COM/OLE error number via AERROR() and pass it to this function as nErrorCode, e.g. 0x080020005 for a type conflict.

Page 9: Zip, Scan, and more - Deutschsprachige FoxPro User Groupportal.dfpug.de/dfpug/Dokumente/Silverswitch/2011 FoxRockX/FR2011… · FoxPro developers are offered ... and Windows API programming.

May 2011 FoxRockX Page 9

Most Windows API functions do not return error numbers directly. Instead they retrun a value defined as invalid, like NULL, FALSE, or ­1. Only calling the Windows API function GetLastError() yields the actual error number. You will find further information in the documentation of the respective Windows API functions.

The FoxPro command ERROR as a clause does not only permit numerical FoxPro error numbers, but also strings. Here you can directly use the return value from GetWinErrorString(). For instance, the command ERROR GetWinErrorString(1223)

will raise the FoxPro error 1098 with the message text (that is localized according to the operating system) “Process aborted by the user“.

ExamplesHere we attempt to create a folder with an invalid path name. When an error occurs, CreateDirectory() returns 0, and the subsequent call of GetLastError() yields the Win32 error number. By means of GetWinErrorString() we convert that error number into a string which we then report to FoxPro via ERROR: SET LIBRARY TO dfpug.fll

DECLARE Integer CreateDirectory ; IN WIN32API ; String lpPathName, ; Integer lpSecurityAttributes

DECLARE Integer GetLastError ; IN WIN32API

IF 0 = CreateDirectory(“Test:\/”,0) ERROR GetWinErrorString(GetLastError())ENDIF

The following example dem-onstrates the behaviour of the function when the message text contains wildcards: SET LIBRARY TO dfpug.fll

#define ERROR_WRONG_DISK 34? GetWinErrorString(; ERROR_WRONG_DISK)? GetWinErrorString(; ERROR_WRONG_DISK,”A:”,,; ”0000-0000”)? GetWinErrorString(; ERROR_WRONG_DISK,”A:”,; Disk 1”,”0000-0000”)

GetShortPathConverts a long path name or file name into its short equivalent (MS­DOS 8.3 convention). GetShortPath( cFileName | cPath )

Return valueCharacter.

ParametercFileName, cPath Character. Absolute oder relative path name or file name. The folder or file must exist.

CommentsIf the given path name or file name already fulfills the MS­DOS 8.3 convention, the function returns the path name or file name unchanged.

In case the drive supports no 8.3 file names and the path length exceeds 67 characters, the function will produce the FoxPro error 1098 with an appro-priate message text such as “Wrong Parameter.”

ExampleSET LIBRARY TO dfpug.fll

?getshortpath(“C:\Programme”) && C:\PROGRA~1

Figure 5. – Example about the Windows System Info

Figure 6. – Example of an entry in the Windows Event Log

Page 10: Zip, Scan, and more - Deutschsprachige FoxPro User Groupportal.dfpug.de/dfpug/Dokumente/Silverswitch/2011 FoxRockX/FR2011… · FoxPro developers are offered ... and Windows API programming.

Page 10 FoxRockX May 2011

RegisterEventSourceAdds those items to the Windows Registry which are necessary so that the Event Viewer can convert event numbers into a suitable message text. Note: Generally you need administrator rights to be able to execute the function successfully. RegisterEventSource( [ cSourceName ] [,nTypes-Supported] )

Return valueNumeric. If it has been executed successfully, the function returns 0 (ERROR_SUCCESS).If an error has occurred, the function returns a Win32 error code which you can convert into a message text through GetWinErrorString().

ReportEventAdds an entry to the Windows application log. Note: The concept “ReportEvent” means “report an event” and has nothing to do with the concepts “Report” or “Event” as they are used in FoxPro! The name of this function was deliberately chosen because (a) the underlying Windows API function also bears the name ReportEvent(), and (b) because presumably in many projects there are already functions or methods with the name “Log”, and therefore conflicts or mix­ups would be quite likely if similar names were used.ReportEvent( [cUNCServerName] , [cSourceName] , [nType] , nErrorCode [ , [cParamCode] [ ,cRawData]] )

Return valueNumeric. If it has been executed successfully, the function re-turns 0 (ERROR_SUCCESS).If an error has occurred, the function returns a Win32 error code which you can convert into a message text through GetWinErrorString().

UrlEscapeConverts characters which are not allowed in URLs into the respective Escape sequences (“%xy”). UrlEscape( cURL [,nFlags] )

UrlUnescapeUrlUnescapeConverts Escape sequences (“%xy”) in a URL into readable text. UrlUnescape( cURL [,nFlags] )

IsWinNTTells whether the operating system is based on Windows NT (WinNT, 2000, XP, 2003, Vista).IsWinNT()

Return valueLogical.

CommentsOn Windows 9x systems (Win95, 98, ME) , the func-tion always returns .F.

Alternatively to this function you may also use the FoxPro function OS(6) to query the OS platform. The return value “2” (Caution: String!) indicates that it is a Windows NT­based operating system.

UserNameReturns the name of the user or of the security policy by which the current thread is being executed.

This need not necessarily be the name of the currently logged­in user. On Windows NT­based operating systems (WinNT, 2000, XP, 2003, Vista) you can run programs under different login credentials (“Execute as...”). UserName( [nFormat] )

Return valueCharacter.

ParametersWhen you call the function without any parameter, it returns the user name under which the current thread is being executed.nFormat In Windows 2000, by providing the optional parameter nFormat you can determine the user name of the name or the security principal in various formats.

The function returns an empty string if the user name cannot be determined in the

given format, or if the domain controller is not available for a request, or the value for nFormat is invalid.

Figure 7. – Converting URLs into Escape sequences

Page 11: Zip, Scan, and more - Deutschsprachige FoxPro User Groupportal.dfpug.de/dfpug/Dokumente/Silverswitch/2011 FoxRockX/FR2011… · FoxPro developers are offered ... and Windows API programming.

May 2011 FoxRockX Page 11

CommentsSystem requirements: The optional parameter nFormat is only supported on Windows NT­based operating systems from Windows 2000 onwards. On all other operating systems (Win95, 98, ME, NT4) the function triggers the FoxPro error 1098 with a matching message text, e.g. “This function is not supported by the system.”

The calling of this function without the optional parameter nFormat is supported by all operating systems Visual FoxPro can run on.

You can apply either IsWinNT() or the FoxPro function OS(6) to query the OS platform. A return value of “2” (Caution: String!) means that it is a Windows NT­based operating system.

You may use the FoxPro function OS(3) to re-trieve the main version number of the operating system. E.g. in Windows 2000, OS(3) yields the String “5”.

At a single workplace PC without a domain membership and without an Active Directory, generally only function calls with nFormat = 2 or without nFormat will return a sensible value.

A security principal is an account owner to whom a security ID for the access to resources is being assigned automatically. A security principal can be a user, a group, a service or a computer.

Defined names are strings according to the RFC 1779.

MemberwareFoxRockX subscribers can download the dFPUG.fll and the sample application described from http://portaladmin.dfpug.de/ dokumente/foxtalk/member-ware/. FoxRockX subscribers may use the dFPUG.fll in their own applications and also hand it over to their customers. The code from the samples, and the wrapper class for the encapsulation of the ZIP functionality and provision of the progress bar may also be integrated into own applications and may thus be handed over to customers.

The license of the memberware is valid as long as the FoxRockX subscription exists. The license ex-pires at the end of the subscription.

Have fun using the dFPUG.fll!

nFormat Description ExampleN/A User name. JohnDoe1 CN=John Doe, OU=Software,

OU=Engineering, O=Widget, C=USFully qualified defined name.

2 Windows NT 4.0 compatible SAM account name.

Engineering\JohnDoe

3 Complete name. As a rule, this name consists of the first name and the surname. It does not necessarily have to match the value CN of the fully qualified defined name.

JohnDoe

6 GUID {4fa050f0-f561-11cf-bdd9-00aa003a77b6}7 Canonical name engineering.widget.com/software/John Doe8 User Principal Name (aka UPN). [email protected] Same as canoni-cal name (nFor-mat=7) except

that the first slash from the right is replaced by a line feed character.

engineering.widget.com/software John Doe

10 Generalized ser-vice principal name. www/srv.engineering.com/engineering.com12 DNS domain name followed by a backslash ("\")

and the SAM user name.engineering.widget.com\JohnDoe

Figure 8. – display of the user name