Contents of the TN0591_T.TXT file

1 Read Me First

This article is reprinted from a recent edition of TechNotes. Due tothe limitations of this media, certain graphic elements such as screenshots, illustrations and some tables have been omitted. Wherepossible, reference to such items has been deleted. As a result,continuity may be compromised.

TechNotes is a monthly publication from the Ashton-Tate SoftwareSupport Center. For subscription information, call 800-545-9364.

2 WHOOPS! Gilbert Catipon

Whoops!Gilbert Catipon

Protection from the Hazards of Accidental Erasure.

Eventually everyone erases a file unintentionally and, oh thefrustration it can cause and it's probably happened to you. At thatpoint, you feel like you've been driving without insurance and havecaused insurmountable damage. It would be helpful to have some way ofprotecting us from our impulsive selves. After all, this is the ageof protection. We need a tool to make our files a little moresecure.

While you could buy a "C" library to acquire a .BIN file capable ofmaking a file read-only and hidden, that would be going a bitoverboard when all you really want is to keep us or someone else fromlooking at or destroying your files. Well in fact, just a few linesof C code, and a quick UDF, and maybe you can save the money to buysome frivilous screen saver software instead. Here is the C code:

The .BIN itself is quite straightforward. All it does is call the_chmod function in Borland TurboC 2.0. If you have a different Ccompiler, your directives may vary. The only tricky part is passingthe necessary parameters back and forth. This method of making a .BINfile was discussed extensively in the Febuary '91 issue ofTechnotes/dBASE IV, but if you can't find that issue then here are thecompiler directives you need to turn Attrib.C to Attrib.BIN.

How do you use Attrib.BIN? Once we've loaded the .BIN to memory wecan call the .BIN directly by passing it a filename and an attribute,such as in the command

CALL ATTRIB WITH "CUSTOMER.DBF",CHR(2)

We send a CHR(2) because the function _chmod() will use 2 as aparameter to set the file attributes of Customer.DBF to Hidden. Themacros that are passed as parameters to _chmod() are in the file#include . If there is an error, the .BIN returns a CHR(255)(a space) otherwise it returns the value we sent it.

To use the CHMOD.PRG, enter the following at the dot prompt:

? chmod("customer.dbf","P")

This will make CUSTOMER.DBF a read-only AND hidden file and return theletter "P". Note that if the file does not exist, then the UDFreturns the string "Customer.dbf?".

To get the file attributes, enter the command

? chmod("customer.dbf","?")

and you get a "P" again. To reset the file attributes, enter thecommand:

Perhaps you don't want to think about it but someone could be lookingover your data files while you are out of the office! Perhaps youdon't have any data that is truly confidential but it's not hard toimagine the sort of information that is best not seen by others. Ifyou are a manager, or you work in Payroll, you will need to preventothers from seeing the private information of other individuals. After all, if Mr. Prehensile were to discover that Miss Halcyon wasmaking more than he, it could cause a major downswing in officerapport.

Perhaps you want to restrict others from entering dBASE IValtogether. That way, all of your data files will be secure.

What if you work on a Local Area Network installation and you sharefiles with others? Everyone must access the same file but you aloneshould see or modify certain fields in the file structure.

Does this sound like a task too big for dBASE IV? It really is simplewhen you use Protect!

Protect is not a new feature of dBASE IV. It's been around sincedBASE III PLUS. However, in dBASE III PLUS, you had to have amulti-user installation (even if it was on your single-user machine)to get Protect to work. Further, you had to exit to DOS to run theProtect program. It was a separate utility.

Now Protect is one of the bevy of utilities available through theTools menu in the Control Center. This new, easier access to Protectmakes it a good topic for review in the context of dBASE IV. Thereare also some new features that were added to make Protect easier touse.

How It Works

The dBASE IV Protect system is based on login names and passwords likemost computer security systems. The dBASE IV login screen is visibleonly after you have set up a Protect system. Once you have it set up,every time you enter dBASE IV you will first see a login screenrequesting a User name, a Password and a Group name. The User nameand Password are used to restrict access to dBASE IV to only thosethat have a user profile within Protect. A Group name is extremelyimportant as it serves as a way to designate a group of database filesthat require access by a particular subset of users. If you are notpart of the group, you will not be able to open the file.

Database files and their contained data, including their memo fieldcontents, are physically encrypted through Protect. Once encrypted,the entire file is unreadable through DOS or other utility programs,except through dBASE IV as one of the users of the Group that has beendesignated to have access to it!

Protect offers a third level of security too. You can assign prioritylevels to your users and restrict access to specific fields within thedatabase structure. This restricted access can span the range fromfull reading and edit capability of all fields in the file, to theability to see only the data in the field but not to change itscontent, to the ability to make a field appear as if it didn't evenexist in the file structure!

All this is possible through Protect. When you run Protect it createsa file called DBSYSTEM.DB. If you are on a single user system, youfind this file in the dBASE IV directory. If you are on a LAN system,the file is created in the DBNETCTL.300 directory which also containsthe login access files. This file contains the user profiles and isitself encrypted using the Protect system administrator I.D. You willwant a copy of this file available in case it becomes inadvertentlydeleted.

A new feature within Protect is the Reports menu which can produce ahard copy listing of your users and their passwords, allowing for fulldocumentation of your Protect system.

Assigning User Groups

As the manual goes into some detail explaining the features ofProtect, it would be more useful to concentrate on some aspects ofProtect that are particularly confusing to some people.

The first thing that you will end up doing in Protect is creating userprofiles. Each user must be assigned to a group (assigning names andpasswords is pretty straight forward). As noted in Using the MenuSystem, pages 14-23, a user can belong to several groups but a filecan be encrypted for only one group to access. If a user needs toaccess files from another group of which he is a member, he must loginagain and therefore maintain two full user profiles. There is nothingwrong with having the same name and password for a particular user,and to have two different group names assigned for each of the twoprofiles. The uniqueness of each user profile is in the combinationof the three required key fields: Name, Password and Group name.

The fact that a file can be encrypted for only one group is crucial toyour understanding of how dBASE IV limits access to encrypted(protected) files. If you have set up a file to be accessed by oneset of users, a new user needing to access that file must belong tothe same group.

The group name is the key to a user being able to access the contentsof a file. To each member of the correct group, the file seems as ifit contains plain English names and data. Anyone outside of the groupwho attempts to access an encrypted file will be stopped by themessage, "File is encrypted" when they try to USE the file. Attempting to view the file from DOS will lead to the samefrustration. Whereas the initial entry to dBASE IV is blocked by theneed for a user profile, even if you find a way to circumvent thelogin, this second level of protection hides your data. That is tosay that even properly logged-in users can be prevented from seeingdata in a file that is encrypted for a different group.

User and File Access Levels

The next issue is one of user access levels. In dBASE IV, a level of1 is the most powerful level. This translates to level one being theleast restrictive level. Level 8 is the most restrictive level. Theabsolute values 1 through 8 have no real intrinsic meaning in and ofthemselves. There may be no practical difference in your systembetween level 7 and 8. Protect merely offers 8 levels of securitydifferences for systems whose security levels must be that complex. It is up to the Protect system administrator to establish theassignments of security equivalence. It is then where the eightlevels can take on a more precise security level based upon whatlevels are higher or lower than any particular level.

Initially, all users are assigned a default level of 1 (highestaccess) and all file privileges are assigned a level of 8 (leastrestrictive). A level 1 user can perform all functions: read, update,extend and delete since the highest level of restriction that can beassigned to each of these operations is one. A user of level five,however, can perform operations assigned to level five through 8 butnot those assigned to level four down to one.

Reviewing the file privileges again, they are, in order of increasingimportance, Read, Update, Extend and Delete. To give a simpledemonstration of the increasing power of these levels, let's say thatRead allows you to read the data only. No changes can be made to datacontained in the file. The Update privilege allows changes to be madeto existing data. Extend privileges provides for the addition of newdata in the form of new records added to the file. The Deleteprivilege means the you can remove records from the file. Thisincreasingly important set of operations is what requires carefulassignment to the various levels of users in your database managementsystem.

Read access is the ability to simply see data in a file. This is thelowest level of all file access privileges. You should realize thatif you have a user who must be prevented from even looking at thecontents of a file, that user really should not be included in thegroup. If a user is part of the group that accesses a file, theminimum ability he will usually have is to see the contents of thefile, though he may be prevented from altering the record contents. Nonetheless, if you assign read access to level 7, your level 8 userswill be unable to do anything to the file.

In a different vein, assigning Read access to a number smaller (morerestrictive) than the level assigned to Update essentially nullifiesthe read-only capability of your Read assignment and causes Update andRead to be granted at the same level. This is okay if you understandwhat you are doing, but for the sake of simplicity, you should assignthe four levels of file privileges in an increasing order to an everdecreasing set of values.

The next level up is that of Update privileges. This is the abilityto change (or edit) the contents of a record. The next level is theability to Extend (or append to) the file. A common question raisedis whether a data entry clerk can have the ability to add new records,but not to change the contents of pre-existing records. Since addingrecords is really the same as editing a blank record (putting contentsinto blank fields), the answer is no. However, to attain this kind ofrestriction, data entry clerks can be given access to special dataentry files that will contain only new records and be denied access tothe main database, preventing the changing of data in that file. Newrecords they enter can later be appended to the master file.

Another, similar, question is whether a data entry clerk can berestricted from viewing data but only allowed to enter new data. Thisis even more impossible given what was discussed above. Remember, theminimum privilege is to view a file (called read-only access). If auser has a higher access right like Delete, the user would, out ofnecessity, retain the rights to the lower, more fundamental accessprivileges.

The highest available privilege is to Delete records. If you want tovisualize how all this fits together, let's try assigning some numbersto the four privileges.

Say that Read is assigned level 6, Update is also assigned level 6,Extend is assigned level 4 and Delete is assigned level 2. A level 8user will not be able to use the file. The same is true for a userwho has a user access level of 7. A user with an access level of 6will have both Update and Read privileges. In this example, there canbe no users that have read-only rights. Data entry must be done bythose with access rights of 4 and above. Deletion can be done only bythose with levels of 2 or 1.

Field Access Levels

The rights and restrictions discussed to this point apply on a fullfile basis. That is, up to now we saw that we could totally restricta user from changing data in a record, or allow them the ability toadd records to a file. dBASE IV also offers the ability to apply aneven finer level of restrictions to a file, on a field by field basis.

Field privileges are not commonly assigned judging from my discussionswith users. I believe that this is due to the fact that the conceptof field privileges is three levels removed. Thinking about loginrestriction, then file access privileges in relation to user accesslevels, then to field level restrictions tends to boggle the mind. It's a level of abstraction that is too much to deal with. Onceagain, user access level is the basis of field privileges just as itis with file privileges. Fields can have three levels of accessprivileges, Full, Read-only, and None. "Full" translates to norestrictions, "Read-only" restricts the user to only viewing thecontents of a field. "None" is remarkable in that fields designatedas such "don't exist" to users of that access level. It's remarkablesince not only can they not see the data, they can't even see thefield in the file's structure. DISPLAY STRUCTURE will not displayfields designated as None, as if the field didn't even exist. It's apretty tricky thing, a potential source of problems.

Field privileges are assigned for each User access level on a field byfield basis. That is, you establish which fields can be modified,viewed only, or not visible at each User level. You might decide thata user of level 8 should not see the Salary field in the Payrollfile. However, this same user might be the one who adds the basicpersonal data to the other fields in the file, having then a mixtureof Full and None field privileges in the file.

Establishing field privileges this way might seem like an alternateway to set up file level privileges since you can establish whichfields are visible and modifiable for all User access levels. Actually, Field access privileges must work in conjunction with Fileaccess privileges. Established File privileges will take precedenceover Field privileges. These in turn must work in conjunction withUser access levels.

Let's look again at our example of this concept. The data entry clerkmust have Extend ability (capability to APPEND to the file). As afine adjustment on this ability, you want to block the data entryclerk from seeing the contents of the Salary field. This fine tuningis what the Field access concept is all about. Note that for HumanResource employees who do not make changes to the data at all and whoare designated as level 7 or 8 users (such as Read-only), assigningFull field privileges to all fields WILL NOT override the Read-onlyrights established on the file as a whole. That is, Field privilegesdo not override File privileges.

This should help to alleviate some of the ambiguity surrounding the use of field level restrictions. It is best used as a fine tuningcapability over the more "coarse" file level restrictions. Fieldlevel access is usually used sparingly, don't try to over use it.

Encrypting the File

Once the File and Field levels are established and you are done, youmust exit from Protect. Of course, you will be Saving all changesmade during the Protect session.

One of the most common "problems" that new Protect users report isthat their new access scheme doesn't work at all. Without exception,this can be attributed to a single cause. When a file is encrypted,it is created as a new file. The original file is left untouched andthe newly encrypted file has the same name as the original file butwith a .CRP extension. Thus, when you use the .DBF, it is availableto any level of user. This is NOT the protected file. This is donefor your protection, but it certainly is confusing to the Protectuser! This simple fact is documented in Using the Menu System under"Other Considerations" in Protect, on page 14-38. It's not really an"other consideration," it's a crucial consideration if you ask me! Atany rate, to use your newly encrypted file you must rename it and giveit a .DBF extension. I'd suggest that you rename it to a new parentfile name and that you make a backup of both the original database andthe .CRP file to boot. Reports of the file access privileges and suchcan only be made from files that have a .CRP file extension.

Another little known and little realized fact is that once a set ofprivileges is established for a file and you exit Protect, the changesare permanently recorded in the .CRP file and if you desire to modifythe access rights established you will have to start over againestablishing all rights to an unencrypted parent file! The .CRP filecannot be modified once saved and only .dbf files can be used as thebasis of setting up new field privileges. For this reason, it isimperative to print a report of the field and file level rights thatwere established within Protect for each file. dBASE IV offers aReports menu for this purpose. The Report menu reads and reports on.CRP files only. If you desire to modify any particular rights inyour file it will help to see graphically what rights were previouslyestablished for the file. It certainly can save a lot of time andgrief in the event of a disaster.

Summary

The abilities of the dBASE IV PROTECT feature is a complicated area tolearn. Protecting your data is crucial in many database systems. Your task is to understand what is going on in the dBASE IV Protectsystem and to try to get the most out of it. Being forewarned aboutthe interrelations between the various aspects of Protect is your bestprotection against frustration with the system. Rest assured that itworks and can be downright powerful once you get the hang of it. Giveit a whirl!

5 Sizing Up an Application Don Powells

Sizing Up an ApplicationDon L. PowellsWhat is an application? This is a very broad question. Can younarrow it a bit? From a developer's perspective, what are thecomponents of a dBASE IV application? This is a fair question. Before you go about developing an application it would seem areasonable prerequisite to know what an application is.

Seeing a completed application running as a whole, we sometimes forgetthat there are discrete parts integrated under the surface, combinedto solve a problem or accomplish a task. This article describes theparts or components that make up an application with the intent todraw attention to many of those elements that go into making anapplication a good one.

Setting the Environment

Most applications are affected by the environment in which they run. It is very important to set the operating system environment so thatyour application will run in it. Under DOS, for example, theConfig.SYS file must contain a large enough value for the FILESvariable to allow you to simultaneously open the maximum number ofrequired files. If your code depends upon the contents of the PATH orother DOS environment variables, they must be set before programexecution.

Configuring the System

The dBASE IV environment must be configured, initially, uponinstallation of your application. The dBASE IV SET commands can beused to determine settings such as whether the clock will be on oroff, displaying 12 or 24 hour format. The SET commands also controlscreen colors, the date and numeric format (especially important withinternational applications), the currency format, the status of thebell, and disk drive/directory search paths.

In conjunction with the SET commands, global variables are often usedto maintain system status information. These variables should besaved to a .MEM file to be restored each time the application is runso that the user does not have to reconfigure the system each time. The SAVE TO command will store all or a portion of variables presentin your system. Unless the variables change regularly, it is notnecessary to SAVE the variables at the end of each session. TheRESTORE command will reset these variables in a new dBASE session andwill be necessary at each start-up. Neither of these processes isautomatic and must be set up in your start-up and exit routines.

To prevent the user from having to worry about what files arenecessary for the application to work, it is a good practice toinclude an initialization routine that checks for the presence of theneeded files and creates them if they are not there. These files mayinclude data or index files, .MEM files as discussed above, memo(.DBT) files, and any special files you may have created. Theinitialization routine opens the files and sets the necessaryrelations and filters, establishing your desired views of the data.

Displaying the User Interface

The user interface is the means by which the user communicates withthe application and, indirectly, the way the developer communicateswith the user. Some of the best rules for user interface design arefrom the Apple User Interface Guidelines. I have paraphrased theseguidelines below.

General Principles of User Interface Design

Use concrete metaphors for computer processes that correspondto the everyday world. A check-writing program, for example, maydisplay an image of a check on the screen as data is being entered.

Provide sensory feedback in response to the user's physicalactions so that they feel they are in charge. Make a noise, make avisible change on the screen, electrically shock the user, dosomething to let them know that you recognize their actions.

Allow the user to select from alternatives displayed on thescreen. Let them use recognition rather than recall. Most peoplelike multiple choice much better than fill-in-the-blank.

Be consistent within and across applications to ensureease-of-learning, and familiarity.

Make sure that what the user sees on the screen does notdiffer significantly from the eventual output.

Let the user initiate and control all actions. Providewarnings for risky activities but allow the action to proceed ifconfirmed by the user.

Keep the user informed of the progress of operations withimmediate feedback which tells how long delays will last and why.

Forgive the users when they make mistakes by allowing theiractions to be reversible. Let them know when their actions are notreversible. In retrospect, perhaps it's better not to shock the useras was previously recommended.

Provide a conceptual sense of stability by maintaining anumber of familiar "landmarks" on the screen and avoid random changesof environment.

Provide aesthetic integrity by making different things lookdifferent on the screen and giving the user some control over the lookof their workplace.

A number of elements are used to build the user interface. Some ofthe major user interface elements are briefly described below.

User Interface Elements

Menus are used to navigate through an application. Pull downmenus have become very popular because they allow the user to see whatfunctionality is available, where he is in the program, and the pathfollowed to get to there and back. Popup menus are great fordisplaying pick-lists from which a single selection is made. Horizontal bar menus prove useful when you need to display a limitednumber of choices in a small space. Menus can be built using thedBASE IV applications generator. Menus and pick-lists provide thatmultiple-choice vs. fill-in-the-blank preference previously mentioned.

Windows allow you to collect and display related informationwhile separating it visually from unrelated items on the screen. Dialog boxes are built from windows and used to ask users questions orto pass along important information. Alert boxes are similar todialog boxes except they are commonly used to issue warnings. Checkboxes are commonly displayed in a window to let the user make multiplesimultaneous selections from a list. A table of data from a relatedfile or a body of text from a memo field may be displayed in a windowas well.

Data input forms let the user enter data on one or more fullscreen pages of data entry blanks. Data input forms can be builtusing the dBASE IV forms generator.

Data display forms display the data on one or more full screenpages without the ability to edit or change the data. Data displayforms can also be built using the dBASE IV forms generator.

Progress indicators include odometers, blinking messages, andthermometer-like bars that show the user how far a process has goneand how far it has to go. Without progress indicators the user isleft to wonder whether the application has failed and locked up thecomputer. Progress indicators help prevent inopportune rebootingwhich can be a source of file loss and corruption.

Data Manipulation and Processing

Once data has been entered through the data input forms or some othermethod, your application will process that data toward your desiredend. A description of some of the more common data manipulation andprocessing functions follow.

Data Verification entails validating the type, format andcontent of the data that is input. This process may be as simple as aPICTURE clause or VALID expression in an @..GET statement or ascomplex as a large user defined function.

Data Storage involves the transference of validated data frommemory or a temporary file to a more permanent master .DBF file. Ifdata storage is localized in one place, any special processingrequired later can be added in one place.

Data Access functions are used to search for requested datarecords by using indexed SEEKs, ad hoc LOCATEs, or sequential stepsthrough FILTERed .DBF files.

Data Retrieval is the opposite of data storage. It involvesthe transference of data from a .DBF file to memory variables, anarray or a temporary file for display or editing.

Data Deletion allows you to remove unwanted records from yoursystem files. Localizing this process lets you put in safeguardsagainst accidental loss of important data. Some developers use thePACK command but others just blank the record out to make their datastorage function more efficient and faster. On large files with manyindexes, PACKING may be less desirable than a blanking method. However, the latter method requires additional programming efforts toignore these blank records in calculations and reports.

Unique Processing may be required for each application youcreate. The processing for preventing duplication of data will mostprobably occur before data storage, during a validation process. However, it is also possible that duplicates are merely omitted fromthe reporting or calculating process by filtering them out beforehand.

Data Output could be called reporting but involves outputtingthe data to not only the printer, but to the screen, a file, or viatelecommunications. The output may take the form of a formattedreport, labels, invoices or other special forms, or specific filetypes that other programs can read. Many of these forms of output maybe generated in dBASE IV via use of the report or label generators orexporting commands such as COPY and EXPORT.

Context-sensitive Help

Nearly all commercial applications sold today providecontext-sensitive help and your user will probably expect no less fromyou. As a minimum, the help system should provide the user withgeneral information about your application and aid when using the mostdifficult portions of the application, however, there may be timeswhen you cannot predict what will be difficult for your users. Therefore, you should make your help system flexible enough to absorbadditions, deletions and edits with relative ease. An advanced helpsystem allows the user to add his own help text to what you provide. If the help is going to be substantially long, it is preferable toinclude help information in a supplemental .DBF file, possibly usingmemos rather than hard-coding the help into the program itself.

Maintaining the System

A group of activities fall within the realm of system maintenance. Auser may decide that one color scheme is no longer attractive and wantto change it. A different user takes over the machine and decides toreconfigure the system totally to their desired state. Printers comeand go, replaced by newer models or substituted by inferior ones whenthey malfunction. A conscientious developer should not make provisionfor only one or two specific printers. You should also accommodatecustomization after installation.

If the index files get corrupted by a power outage during a write, theuser should be able to recreate them from a menu option. Many times,our technicians here will get a call from a dismayed user who can'tmake a custom application work. Often times, it's only a matter ofrebuilding an index file, a function that won't normally take morethan a few seconds. But without proper instruction and a means forrecreating such files, hours of constructive time can be lost.

It makes sense for some applications to allow the user to create anew, empty set of files. If the user wants to practice with dummydata, new files are a great aid for helping them get started with thereal data. Only you should also provide for the erasure of thesefiles so that unneeded practice files do not build up in the user'sdirectory.

Speaking of size, if you anticipate that the size of the system fileswill grow to unmanageable sizes filled with historical data, you maywant to implement an archive and restore system to allow the user toput unneeded records in an archive file until later required. Archiving may also speed up the processing of the application becausethere are less records for your application to maintain.

Provide a means for your users to backup and restore their data aspart of a maintenance menu. This system can be a simple file copy toa user specified drive, or using the DOS commands, or a completesystem that splits files across multiple floppies or other media ifthe file is too large to fit on one. Of all the features of yourapplication, this one is of a critical nature. No insurance forpossible data corruption or erasure is an invitation for inevitabledisaster. As the architect of a system, you should provide the systemfor easy and reliable backup and encourage your users to followthrough regularly.

Handling Errors

You should anticipate and prevent the occurrence of non-criticalerrors. Make sure that only the proper data type can be placed in adata entry field by using formatting and validation. Unfortunately,there are some critical errors that cannot be easily prevented bydBASE IV error trapping (such as backing up to an open disk drive orprinting to a printer that is off). In those cases you should try toallow the user to recover or terminate gracefully under yourapplication's control.

An electronic error log should be automatically generated by yourerror handler to help you to debug problems without having to dependupon the user to describe them. It is easier to handle errors if yougroup them into categories like disk errors, print errors, memoryerrors, and so on. You can then concentrate on handling just that onecategory of errors at a time instead of trying to accommodate everypossible error in one giant CASE construct. Again, if your system isvast and the error messages numerous, consider placing the errors andtheir error numbers in a database that can be called by your programwhen an error occurs.

Technical and User Documentation

The comments in the source code files contain much of the technicalinformation needed to maintain the application, but often, moredocumentation than that is needed to maintain an application. It ishelpful to have a description of the overall application and how allthe pieces fit together. A code analysis utility could prove helpfulin creating flow charts, variable usage tables, and more. Otherutilities can provide "screen-shots" of different screens that appearin your application. The visual association can be helpful inincreasing the understanding of how to operate your application.

User documentation is a combination of what is provided on-line and inprint. As a minimum, the user should be able to understand how to getstarted using your application. Ideally, the user would never have tocall you with a problem that could not be solved by using the programor its documentation. Then again, where would our technical supportdepartment be if that were true.

Miscellany

Additional functions may be added to an application to implementnetworking or password protection. Transaction processing may becomenecessary in a transaction-oriented system like accounting. If yourapplication requires some functionality outside of what dBASE IV canhandle, you may need to include modules written in C or Assemblylanguage to handle those tasks. The pages of TechNotes and theAshton-Tate BBS are excellent sources for such routines.

Summary

So, what is an application? It is a collection of discrete partsintegrated to solve a problem or accomplish a given task. Each parthas a purpose and the absence of even one part increases thelikelihood that your application will not reliably suit those who useit. The parts that have been discussed here are:

Setting the EnvironmentConfiguring the SystemDisplaying the User InterfaceData Manipulation and ProcessingContext-sensitive HelpMaintaining the SystemHandling ErrorsMiscellanyTechnical and User Documentation

When you conscientiously combine these parts and others you findnecessary, you get an application that provides the users with a moreefficient way of processing data and you with a minimum of headaches(from disgruntled and perplexed users calling for technical support)and a maximum amount of cashflow (from lots of orders and/or a raise).

6 Etc.

Etc.Checking For Directory Existence

At some point during the course of application building, it often isnecessary to verify the existence of critical files needed for properprogram operation. This is easily accomplished through use of theFILE() function. A program segment may look something like this:

Checking for directory (or drive) existence can be accomplished in asimilar manner. Ironically, the FILE() function is still thefunction to use. But since the FILE() function needs a file namewe'll have to trick it by using a DOS device name such as NUL, CON, PRN, etc. This is possible since DOS allows you to open a device thesame way you open a file! NUL is the preferred device name to usesince it's not likely to interfere with an operation the way openingCON or PRN may. The following example shows how to accomplish this...

When using the dBASE IV Applications Generator, the Override assigneddatabase or view option allows you to change the active database andits order. However, changing the order of the file to Natural order(no index) once a particular order is in place, is not clearlydocumented. This can be accomplished by entering a left and rightbracket ([]) or two single quotes ('') in the following areas:

In the Set index order option under the Item menu.Under the ORDER option of the Override assigned database orview option of either the Menu or Item menu.

This has the effect in the resultant dBASE code of a SET ORDER TOcommand which resets the file to natural order.

Invoking Print Screen from a Program

Since the Print Screen or Shift-Print Screen key has a special use onPC-compatible computers, it does not return a value to dBASE IV. Thismakes it impossible to invoke a print screen through the use of theKEYBOARD command. Fortunately, printing the screen can beaccomplished through use of a very small .BIN file which is relativelyeasy to create. Either of the following two measures will create thefile Prntscrn.BIN.

At the DOS prompt type COPY CON Prntscrn.BIN and press Return. Then,while holding down the Alt key, enter the numbers 205, 5 and 203 onthe numeric keypad, releasing the Alt key after each number. Lastly,press the F6 key and then Return. This will close and save the file.

The second method for creating this .BIN file must be invoked from thedot prompt or in a program. The dBASE code follows.

SET PRINTER OFFSET PRINTER TO FILE Prntscrn.BIN??? "{205}{5}{203}"SET PRINTER TO

Having created the file, issue the command LOAD Prntscrn. Thereafter, to print the screen, issue the command CALL Prntscrn fromyour program: Seeing Your True ColorsWhile it's true that there is now a way to use the SET() function toreturn the values of your current color settings, it doesn't reallyshow you what these settings are or what they look like. It is not hard to devise a small routine that shows the eightdifferent color settings in the actual colors (on a color monitor ofcourse). However, when the colors for foreground and background arethe same, such as N/N (or black on black), there may be no indicationon screen if your background color is that same color. t* CSHOW.PRGPRIVATE showcolor, cstring, comma, talkwas, cursorwasON ESCAPE KEYBOARD CHR(0)IF SET("TALK") = "ON" SET TALK OFF talkwas = .T.ELSE talkwas = .F.ENDIFcursorwas = SET("CURSOR") = "ON"SET CURSOR OFFDEFINE WINDOW colorshow FROM 5, 10 TO 16, 46 220, 223, 219, 219, 220,220, 223, 223 &&ASCII box characterscstring = STUFF(SET("ATTR"), AT(" &" + "& ", SET("ATTR")), 4, ",")+","ACTIVATE WINDOW colorshowcomma = 0showcolor = ""cntr = 1*--note final comma in following stringpstring ="normal,highlight,border,messages,titles,box,information,fields,"

As we rely more and more on doing various tasks on our computer,several utility-type programs have popped up on the software market. For instance, wouldn't it be convenient to have a utility that wouldpopup a window for you to jot down notes in, record an address, atelephone number or a reminder about some weekly activity? Well Ithought so, so I wrote one and called it NoteIt. NoteIt is based on adatabase with 2 fields: an indexing field and a memo field. UseNoteIt for a address book. Put the name of the individual orcompany, and then contact names, address, phone numbers and anycomments in the memo field. Since it is a memo field, you can enter agreat deal of information.

You might be wondering how do you retrieve all of these random notesof information? To make locating your recorded thoughts easier, thereare three searches in NoteIt:

Quick Search: This is a SEEK of the index line and is thefastest of all of the searches. This requires that you search theentry starting from the leftmost characters in the index field. Forexample, to look up the entry "Doe, John", you would have to startyour search criteria from the last name ("D", "Do" or "Doe", and so on...).

Main Search: This is a search of any data in the index line. For example, using the above information you could type in "John" andit would find "Doe, John" as well as any other records that containedthe word or partial "John".

Comments Search: Like the Main Search but it searches thecomments (memo) field. You can search for any word or set of words inthe memo field.

These last two searches are sequential and will consequently takelonger on some machines, depending upon the size of your database.

You will need to create the simple database, called NoteIt, with thefollowing structure.

Field NameTypeWidthMainLineCharacter30CommentsMemo10

For the program to function correctly, you must add at least onerecord prior to using NoteIt. This initial record can be edited whilein the NoteIt program by the special editing key Alt-E.

Other special editing keys are available on-screen when using NoteItby pressing F1. You still press Esc to abandon a memo edit orCtrl-End to save the changes. One point worth noting here is that thecursor is normally positioned on the memo field in a window. Becauseof this, you will need to press Return to regain access to the popuppicklist of names to the left of the memo window.

Another point that might raise questions is the presence of the rulerin the memo field. When not active, there is no ruler visible. Uponentering the memo field, in edit mode, the ruler appears, shifting thetext down. The question may then be, how do you eliminate the ruler? The only way to do so is through the Words menu (accessible bypressing Alt-W or F10), changing the Hide ruler option to YES. Thissetting is not for the dBASE session but for that particular editingsession. Consequently, the next time you enter a memo for editing,the ruler will once again appear. There is no additional parameterthat can be added to the GET command line of a memo that provides forelimination of the ruler.

All in all, this program provides a handy utility and the code showssome interesting programming concepts as well.

8 UDF Library

UDF Library

"At the tone, the time will be..."Although most of you are aware that you can do basic arithmeticfunctions with date and time fields, it is not as well known that youcan add decimal values to a date field and obtain a timedifferential.

A need for this usually comes when trying to determine an elapsedperiod of time. Functions that accomplish this have been seen in thepages of TechNotes/dBASE IV in the past. Here now is anothervariation on how you might accomplish it.

In the function called Elapsed, the variables sdate and edate are datetype variables while stime, etime and result are character type usingthe template HH:MM:SS. To start the timing sequence, enter x =elapsed(1) at the dot prompt or in a program. To stop or mark thetime, x = elapsed(0). The 0 can be passed repetitively to provide fornumerous time measurements from a singular starting point.

Creating Temporary Files

There are times when you might want your own application to be able tocreate its very own temporary files like dBASE IV occasionally does. The TempFile() UDF below returns the name of a temporary file that canbe used in your program. For example,

TempFile() honors the TMP environmental variable, so that the filethat your program ends up using is created and processed along withthe rest of your dBASE IV temporary files. Be sure that your programerases the temporary files it creates, (as shown in the exampleabove,) or you might end up with a directory filled to the brim withtemp files.

Fonetic Philes

One goal of a developer is to make his software foolproof. If yourapplication has areas of functionality that can dynamically use any.DBF or other file type that the user pleases, then it isn'tunreasonable to assume that the user will not always remember the nameor spelling of a target file. FileHelp() is a real nifty way toensure that a spelling error or lapse of memory will not slow the userdown.

FileHelp() takes two parameters: the filename that the user enters,and a file extension. A list of SOUNDEX() spellings and sound-alikesof filenames with the specified extension pops up. The selectedspelling from the picklist is returned unless no similar spellingsexist or the user presses Esc. In this case, an asterisk (*) isreturned.

FileHelp() makes use of the TempFile() UDF shown above. You must alsocreate a database file called AFILES.LOD. The structure consists of asingle field definition: A character field with a length of 12 andnamed "File".

Using the DOS Path

PathFind() is another way that you can make your application moreiron-clad in the event that the user has no concept of what asub-directory is. You could almost use PathFind() as a substitute forthe FILE() function.

FILE(), of course, returns a .T. or .F. depending on whether or notthe file specified is present in the current sub-directory. PathFind() takes it one step further. If the specified file exists inthe current sub-directory or ANY sub-directory in the DOS PATH, thefilename with the path in front of it is returned. If the file doesnot exist in the current sub-directory or anywhere in the PATH,PathFind() returns a "". For example:

*-- Create a text file containing all files in the current*-- sub-directory that have the specified extension and import*-- the text file into AFILES.LOD.RUN DIR &f_ext2 > &f_tmpRESTORE SCREEN FROM B4popSELECT 10USE AFILES.LODZAPAPPEND FROM &f_tmp TYPE SDF