You are on page 1of 22

VFP conversion to support SQL server Backend

1. Overview............................................................................................................... 3
1.1. Brief introduction:............................................................................................... 3
1.2. Conversion issues: .............................................................................................. 3
1.3. Data conversion: ................................................................................................ 3
1.4. Data Access Techniques: ..................................................................................... 3
1.5. System design issues: ......................................................................................... 3
1.6. Supporting your application: ................................................................................ 3
2. Before the Conversion............................................................................................. 4
2.1. Will Your Application Survive Conversion?.............................................................. 4
2.1.1. Unconvertable specific Functions, Validations, Data access methods: .................... 4
2.1.2. SQL/VFP Capacity limitation: ............................................................................ 5
2.1.3. Normalization:................................................................................................ 5
2.1.4. Navigation Issues: .......................................................................................... 5
2.2. Data Design Issues ............................................................................................. 5
2.2.1. Data Type Differences ..................................................................................... 5
2.2.2. Logical / Integer:............................................................................................ 7
2.2.3. Text / Character: ............................................................................................ 7
2.2.4. Binary / Image: .............................................................................................. 7
2.2.5. Dates: ........................................................................................................... 7
2.3. International Data and Other Issues ..................................................................... 7
2.3.1. International Data .......................................................................................... 7
2.3.2. Row-Level Access vs. Set Access ...................................................................... 8
2.3.3. Paging Issues, and the Mechanics of SQL Data .................................................. 8
2.4. Nulls, Defaults, and Empty Values ........................................................................ 8
2.5. Indexes ............................................................................................................. 9
3. Data Conversion and Data Access Techniques ......................................................... 10
3.1. Data Conversion ............................................................................................... 10
3.1.1. Bulk Copy Program: ...................................................................................... 10
3.1.2. Data Transformation Services: ....................................................................... 10
3.1.3. The VFP Upsizing Wizard ............................................................................... 10
3.1.4. Writing a Custom Converter ........................................................................... 11
4. Data Access Techniques ........................................................................................ 12
4.1. VFP Remote Views: Pluses................................................................................. 12
4.1.1. Easy Conversion: .......................................................................................... 12
4.1.2. Ability to detect update conflicts:.................................................................... 12
4.1.3. Easily switch Backends: ................................................................................. 12
4.1.4. Automatic handling in Data types: .................................................................. 12
4.2. VFP Remote Views: Minuses .............................................................................. 12
4.2.1. VFP View Designer:....................................................................................... 12
4.2.2. Perfomance: ................................................................................................ 13
4.2.3. Requires VFP Database Container:.................................................................. 13
4.2.4. Cant call SQL Stored Procedures: ................................................................... 13
4.2.5. Data changes takes place on a client: ............................................................. 13
4.3. SQL Pass-Through: Pluses ................................................................................. 13
4.3.1. Multiple connection options:........................................................................... 13
4.3.2. Faster than remote views: ............................................................................. 13
4.3.3. Ability to call stored procedures:..................................................................... 13
4.4. SQL Pass-Through: Minuses............................................................................... 14
4.4.1. More work: .................................................................................................. 14
4.4.2. Have to handle update conflicts: .................................................................... 14
4.4.3. Must know more details about backend table structures:................................... 14
4.4.4. Data translation issues: ................................................................................. 14
4.5. ADO Pluses ................................................................................................... 14

As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.


Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 1 of 22
VFP conversion to support SQL server Backend

4.5.1. ADO data is available as properties within the RecordSet or Command object...... 14
4.5.2. Update conflicts built: ................................................................................... 15
4.6. ADO Minuses................................................................................................. 15
4.6.1. VFP snat iv ec ont rols will not work: ................................................................. 15
4.6.2. Time consuming: .......................................................................................... 15
4.6.3. DLL issues: .................................................................................................. 15
4.6.4. Might require refactoring: .............................................................................. 15
4.7. Which is Best?.................................................................................................. 15
5. Constructing and Supporting the Application............................................................ 16
5.1. More Design Issues .......................................................................................... 16
5.2. Connections ..................................................................................................... 16
5.3. Performance .................................................................................................... 16
5.4. Limit Trips to the Server .................................................................................... 16
5.5. Other Performance Issues ................................................................................. 17
5.6. Metadata ......................................................................................................... 17
5.7. Transaction Processing...................................................................................... 18
5.8. Security........................................................................................................... 18
5.9. Errors & Error Trapping ..................................................................................... 19
6. Supporting the Application..................................................................................... 21
6.1. Development & Testing ..................................................................................... 21
6.2. Installation and Updating .................................................................................. 21
6.3. Database Maintenance ...................................................................................... 22

As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.


Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 2 of 22
VFP conversion to support SQL server Backend

1. Overview
1.1. Brief introduction:

Name : Rahul Desai


Foxpro & VFP experniece: 15+years
Desktop Development Manager at Talman Pty. Ltd.
Developer of KenSys range of Commercial applications http://www.nationalcom.com

Microsoft SQL Server offers the database developer incredible power and flexibility, but learning
to work with it is a lot like learning to play chess. The basics are easy, but mastering the product
takes some effort.
We will not discuss SQL Server in-depth, as there are many excellent books already available on
the subject. Instead, we will discuss the basics of migrating. Microsoft Visual FoxPro (VFP)
application to a client/server platform, specifically with SQL server as the database.

To that end, I will cover the following:

1.2. Conversion issues:


What do your users expect,
What do you hope to accomplish with the conversion, and
Most importantly, can your application be converted?

1.3. Data conversion:


What design issues will you face, and
What are some of the differences between SQL-stored data and VFP-based data.

1.4. Data Access Techniques:


How do you access SQL-stored data from within VFP?
We will investigate
Remote views,
SQL pass-through,
ADO
And how they compare with each other.

1.5. System design issues:


Whatar es omeoft hemor eimport
antper
for
manc
eand
mec
hani
cal
is
sues you will need to
consider?

1.6. Supporting your application:


How to deal with
Table changes,
Updates to the code,
Error reporting,
and so on. This topic is often ignored, but is just as criticalasdec
idi
nghow y
ou
regoi
ng
to get to the data.

As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.


Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 3 of 22
VFP conversion to support SQL server Backend

2. Before the Conversion


I want to begin by talking a little about the expectations you and your users might have
regarding data conversion.

One common misconception that developers have is that moving to SQL Server will increase your
appli
cationsperf
ormanc e.I ngeneral, client/server databases are more efficient than file server-
based systems because only requests and results are traveling across the network.

However, to achieve that efficiency, requests and results must be small and carefully designed. A
lot of requests and large result sets will cause performance problems. It is important to
remember that simply switching to SQL Server from a VFP-based file-server system will not
necessarily result in increased performance for the user. You have to carefully consider which
portions of the system to migrate in order to get the best performance possible.

Before beginning the conversion of your application, you should first consider the future of the
application as well as scalability. Is there a possibility that y
ou
l
lneedtoac cesstot hedat af r
om
outside the system? Do you need to consider alternative interfaces? Do you need to consider
issues regarding replication? Where do you and the client see the application going in the next
several years? If, in the near future, you need to expand the scope or capabilities of the
application beyond its immediate purpose, a conversion, as opposed to replacement or
refactoring, is probably a waste of time and resources. This is not to say that converting an
application is always a waste of time. There are a lot of good, solid reasons to move to an SQL
Server back end, perhaps the most compelling reasons being improved table size and increased
security options. A converted system may also provide you with a platform from which to expand
in the future. The point is that you should at least think about the future before beginning any
conversion project.

2.1. Will Your Application Survive Conversion?

Perhaps the single biggest concern you will face in converting an application will be whether the
application will even survive the conversion. In attempting to address that concern, consider the
following:

Issue Example
1 Unconvertable specific Functions, Validations, Data
access methods
2 SQL/VFP Capacity limitation Row width,Key width
3 Normalization
4 Navigation Issues

2.1.1. Unconvertable specific Functions, Validations, Data access methods:

Are there any VFP-specific functions built into your data access methods or validation
routines? Obviously, these will not translate into SQL Server. If VFP-specific functions do exist,
where are they hidden? They could be in index keys or the business logic. Older VFP applications
often have functions deeply embedded in critical areas of the system.

Where is the business logic embedded in your application?


Will you be able to alter it to deal with differences in SQL syntax and data access
techniques? Business rules in the user interface (UI) can also relate to more trips to the server,
As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.
Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 4 of 22
VFP conversion to support SQL server Backend

which affects performance. If you do have business logi ci nUIf or


msori fy oudon tknow wher
e
it is located, it might be prudent to think about rewriting everything from the ground up.

2.1.2. SQL/VFP Capacity limitation:


You also need to consider SQL capacity limitations. This might seem like a strange concern, given
that the data storage capacities of SQL 2000 are measured in the thousands of terabytes
(1,048,516 TB to be exact). However, certain aspects of its components, like tables and
index keys, do have limits that differ from VFP. Perhaps the most notable is row width.
Row width in SQL Server is limited to 8096 bytes. VFP row width can be up to 65,500
bytes. That
sabi gdi ff
erence( alt
hough,r ealist
icall
y,itisli
mi t
edbyt heallowabl etablesi
z eand
number of fields allowed). Key width is a similar problem. Again, SQL is more limited than
VFP, with an upper limit of 16 columns per index and 900 bytes per key. Both of these
issues, if they exist in your application, need to be addressed before you move forward.

2.1.3. Normalization:
Also consider the degree of normalization in your application.
Do the current tables have compound primary keys?
Are they optimized for data storage or constructed for easy reporting?
SQL Server performs best with highly normalized tables, but there are often very sound
business reasons for not doing that. In considering this issue, keep in mind that legacy VFP
applicat
ionst end to hav e normaliz at
ion i ssuess impl ybec aus
ethe ori
gi nalpr
ogrammerdi dnt
know any better.

2.1.4. Navigation Issues:


Lastly, you need to consider the data access issues. As an example,
Does the application have navigation toolbars?
Does your system provide total access to all the records in all the tables?
This is very common in VFP applications, but can be the kiss of death for client/server
applications with high record counts. Even moderate numbers of records, in the order of tens of
thousands of records, will be difficult to navigate simply due to the amount of data that
needs to be sent to the client.

2.2. Data Design Issues


Another bump in the road that you will likely encounter is the issue of differences between VFP
and SQL Server with data types and data behavior. In my projects, these differences have almost
always been evident. These include:

Differences in data types, including definitions and values stored in SQL Server

Dealing with null values, empty values, and the importance of default values

The importance of key definitions and the options offered by SQL Server

Differences in index types available in SQL Server

I will discuss each of these in the next few paragraphs.

2.2.1. Data Type Differences

As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.


Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 5 of 22
VFP conversion to support SQL server Backend

Field Type Sql Server VFP Remarks


1 TimeStamp SQL Server Generated Unreadable binary Data
2 Logical Bit Logical No indexing available
Logical TinyBit Logical Indexing available
3 Memo Text Memo
4 Char Char Character Data length is of
consistent length
5 VarChar Varchar Char (Upto VFP 8) Data length is Variable
Varchar in VFP 9
6 General Binary General For values with the same
fixed length
General VarBinary General For values with Variable
length
7 Images Image General Variable Values in
excess of 8K
8 Date DateTime Date No Date equivalent in
SQL- uses DateTime
9 DateTime DateTime or DateTime Use different type in SQL
SmallDateTime depending on the
precision requirement

Fir
stI
lldiscusst hedat at ypesthatIc allthe SQLoddi ti
es .Thes ear ethedat at
ypesf
orwhi
ch
there are no equivalents in VFP and, therefore, probably will not be used much.

The first data type I will discuss is TIMESTAMP, which is a unique, eight-byte binary value
generated by SQL Server. Its extensively usedt
o brandr ecordswhen they are created, the
value translates into unreadable binary data for VFP. However, in certain circumstances,
having a TIMESTAMP column can help increase query performance on an SQL table.

The other similar data types are Cursor, Table, Uniqueidentifier.

The second data type is CURSOR, which holds a reference to a special SQL data type used to
access data at individual row levels. Related to CURSOR is the third type, TABLE, which is used to
store result sets for later processing. TABLE is not available for definition within permanent tables
(only for temporary tables), and is also used, for example, for processing within a stored
procedure. Both of the CURSOR and TABLE data types are resource-intensive and you should use
them sparingly.

The last data type is UNIQUEIDENTIFIER, which actually is a very useful data type that I will
cover later.

SQL Server supports all of the other data types that VFP developers are familiar with,
but in some odd flavors. Obviously, the first question you have to ask when defining SQL table
columnsi swhatt y peoff ieldt ous e.Thenex tques ti
ont oas k,andi fyouhav entpl ay
edar ound
with SQL yet this is going to seem a strange question, is what size field? By t
he si
z eofthefield
Iam notr eferri
ngt ot helengt hoft hef i
eld,that
sadi ff
erenti ssue.I ns t
ead,Iam r efer
ri
ngtot he
fact that SQL offers several field sizes for a given data type, each with different minimum and
maximum capacities.

As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.


Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 6 of 22
VFP conversion to support SQL server Backend

2.2.2. Logical / Integer:


For example, consider the integer field. SQL actually supports five sizes of integer fields.
The smallest integer field, called BIT, is equivalent to the VFP logical field because it can store
only values of 1 or 0. The other integer fields, TINYINT, SMALLINT, INT, and BIGINT, support
progressively larger ranges of values. All of these options make the issue of field size an
important one. In general, you will want to use the smallest field type possible. Doing so reduces
storage requirements and can improve performance.

Speaking of the BIT data type, I want to discuss it in a little more detail. VFP ODBC translates
BIT values to True or False, even though they are stored in SQL Server as 0 or 1
values. In addition, unlike in VFP tables, you cannot index BIT columns, which means that
queries on them will be inherently slow. On the other hand, you can index TINYINT columns. So,
for a small storage cost, the TINYBIT column is a good alternative to the BIT column.

2.2.3. Text / Character:


Another data type that offers a variety of capacities is the character data type. There are two you
will be most familiar with, CHAR and TEXT. TheTEXTt ypei st heequi val entofVFP sMEMO
type. SQL of fer
sa t hirdt ype,c alled VARCHAR,whi chs tandsf or variablec haracter.The
VARCHAR data type performs like the TEXT type, in that the length stored in a row varies
according to the data. VFP treats this, for display purposes, as a MEMO data type. However,
unlike the TEXT data type, VARCHAR columns are searchable (TEXT data types are
searchable as well, but only if you enable SQL full-text search abilities, which is a topic unto
itself) So, which data type should you use? Microsoft recommends using the CHAR data
type for columns where the data is of a consistent length (like a Social Security or
telephone number) and the VARCHAR data type for varying-length values (like names and
addresses). However, there can be performance issues with VARCHAR columns due to the way
SQL stores the data.

2.2.4. Binary / Image:


Similar to CHAR, there are three different sizes for binary data types (BINARY, VARBINARY,
and IMAGE), as opposed to the single GENERAL type in VFP. Again, the difference is capacity.
BINARY is recommended for values with the same fixed length while VARBINARY is
for variable-length values. Both BINARY and VARBINARY have an upper limit of 8K. The
IMAGE data type, on the other hand, is variable-length and can be used for values in
excess of 8K.

2.2.5. Dates:
Dates are another important area of difference between VFP and SQL Server. SQL always uses
the DATETIME data type for dates. There are two data types, DATETIME and
SMALLDATETIME, which differ in their precision as well as their upper and lower limits, but
there is no DATE equivalent. This is important to remember when constructing select
statements, because actual date ranges often have to be specified when building queries.

2.3. International Data and Other Issues

2.3.1. International Data


Another level of complexity is in dealing with international issues, and in particular storing
international characters. Remember the varieties of character data types we just discussed?
As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.
Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 7 of 22
VFP conversion to support SQL server Backend

Ac t
ually,t
her e
smor e:theUni codedat at ypesNCHAR,NVARCHAR,andNTEXT.Thes estor
edat a
in Unicode form based on the UNICODE UCS-2 character set. VFP treats them as the equivalent
non-Unicode character types, but in actuality the storage cost is double that of CHAR and
VARCHAR. These data types should only be used when absolutely necessary.

2.3.2. Row-Level Access vs. Set Access


One other important difference that I would like to highlight is how you access the data within
the two different databases. VFP developers are used to having access down to the individual
rowsofat abl e.SQLSer ver,ont heot herhand,deal swi t
hdat aass etsofrecords.SQL select
statements return results in sets, and operations are (in general) performed on these sets. This
difference is transparent when accessing SQL-based data through VFP remote views or ADO;
however, within an SQL stored procedure, for example, you cannot get to a specific row without
loadingt hedat as etintoaCURSOR dat at ype.( Remember ,t het erm c
ursorhasanent i
rely
differentmeani ngi nSQLt hani thasi nVFP) .Althought hi
sis n
ts oi mportantify ouar eus i
ng
remote views, it can be a stumbling block when writing stored procedures that have to process
records one by one.

Whatt hismeansi st hatt her ei sno equi valentt o VFP sGO TO,SKI P,and SCAN/ ENDSCAN
commands. Even if your data is physically ordered in the way it would be accessed, you still have
to execute some type of query to get the next record.

Thati s,ofc ourse,unles syouloadtheresul


tseti
ntoaCURSOR vari
abl
etype.Youcan
walk
throughc ursors,si
milart oVFPtabl
es.However
,usethem s
par
ingl
ybecaus
ec ur
sor
sarec
ost
ly
in terms of performance.

2.3.3. Paging Issues, and the Mechanics of SQL Data


How SQL stores records can also affect system performance. Remember what I mentioned earlier
aboutt hemax i
mum t ablewi dthbei ng8K?SQLSer v er
sbas icuni tofdat astor
agei sapage,
which just happens to be 8K, and any given row cannot span a page. SQL crams as many
contiguous rows as it can onto one page before having to find space on another. As you can
imagine, having row data scattered over many different pages can affect performance, and this will
happen in systems with intense data input and modification.

This paging issue is why variable character fields can cause performance issues. If you update a
row with a VARCHAR field, and the row no longer fits the page it was originally on, SQL will have
to move it to a different page. In an active system with lots of data changes, this increases the
number of required operations (thus affecting performance).

2.4. Nulls, Defaults, and Empty Values


Besides differences in data types, there are a number of differences in the way SQL stores data
internally within a table, which can cause some migration problems. Null tolerance is one such
issue. Even though VFP has been able to deal with NULL values for some time, older applications
cantdealwi t
ht hem,andt hismayc ausey ous omeheartache when trying to adapt to the new
database.

Nullt ol
eranc edoes nts i
mpl ymeant hatt heUIwi lldis pl
ayt hem ass pac esinst
eadof .
NUL L .

(al
thought hisi soneas pec tofi t).Morei mpor tant l
y,you l
lneedt ot ake nul lpr
opagat
ion
(meaning, X + .null. = .null.) into account in computations. Dealing with this issue may involve a
great deal of code refactoring if you decide to allow null values in the data.

Byt hesamet oken,y ouc an


ts impl yex c
ludenul lv al
uesfrom y ourt abl
esbec aus eofthepr oblem
with empty field values. While it is allowed in VFP, SQL Server does not understand empty values

As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.


Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 8 of 22
VFP conversion to support SQL server Backend

in some circumstances. Columns and variables have to either be populated or have null values
(although spaces are valid values for character fields). This is a particular problem with
DATETI MEf i
elds,asat t
empt i
ngt os tor eanemptyval
uei ntoaSQLc olumnr esul
tsinthe base
def aul
tv al
uebei ngs tored.For DATETI MEc ol
umns,t
heres ul
tisas toredv al
ueof 01/01/ 1900,
which is probably not the desired result.

This illustrates the importance of properly setting up default values in your table definitions.
Somef ieldshav ea naturaldef aultval uewhennul lsar enotal lowed;c harac t
ercol
umnscan
s t
or eempt ycharacterstri
ngs( ),numer i
csc ans torez eros .Twof i
eldsdon t
:DATETI
ME,as
we just covered, and UNIQUEIDENTIFIER. DATETIME fields, when not-nullable and consistent
with your business model, should have a default value specified. For example, you can use the
GETDATE() function to store the current date-time when the row is created. UNIQUEIDENTIFIER
fields, like DATETIME, must either be null or have a value that fits the algorithm.

Ther e
soneot herc ol
umnt hatIus ual
lyrecommendasbei ngnon-nul labl
e,andt hat
stheBI T
field. Null is valid,butusual
l
ydoes n
tmak emuc hbusi
nes ss ense.Abet terdefaulti seit
heroneor
zero. In general, specifying a default value on non-nullable columns is good practice, as it
shortens the number of columns required when inserting new records, which is important if you
are doing this with SQL pass-through.

2.5. Indexes
Let
sgoov eroneaddi tionaldatades igni ssuey ouneedt okeepi nmi nd:i ndex es.For
tunately,as
VFP developers, we have long been aware of the impact of good table indexing, as that is key to
Rushmore optimization and fast queries. Good indexes have just as direct an impact on SQL
Server database performance; in fact, this is the one of the first places to look when you have a
performance issue with a SQL-based system.

SQL Server offers some options for indexes that you may not be familiar with. The first is making
theindexa cl
usteredi ndex .Thi smeanst hatther owsi nt het ablear ephy sicall
ys ortedint he
index key order for faster access time. Only one clustered index is permitted per table,andy oud
want to build it on a key pattern that is the most likely search path (last name/first name on a
customer table, for example). Building a clustered index on a surrogate primary key field is
usually not recommended, as it will not increase performance.

Oneot heropt iont haty ouneedt obeawar eofwhenc onstruc t


ingi ndex esi s fi
llfactor.Ins hort,
this determines the amount of space available for adding new keys within an index before
performance starts to degrade. If you anticipate adding a lot of records to a table, you want a
high fill factor. Relatively static table indexes should be built with a low fill factor to reduce space
requirements. This option really illustrates some of the complexities of constructing SQL
databases; never rush into this blindly.

Fortunately, SQL Server offers several tools to help you optimize your indexes (and the queries
that use them) for best performance. These include the Query Analyzer, SQL Profiler, and the
IndexTuni ngWi zar
d.Ti medoes ntper mi tust ogo into these in detail; I recommend that you
spend time experimenting with them on your own, or hire a DBA to assist you. The long and
short of it is that good index construction is key to getting the most out of SQL Server.

As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.


Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 9 of 22
VFP conversion to support SQL server Backend

3. Data Conversion and Data Access Techniques


3.1. Data Conversion
So how do you get the data in your current system over to SQL Server?
Just as importantly, how do you get the data out again for use within your application? We are
going to spend the next several paragraphs examining these crucial issues, since they are
related.

3.1.1. Bulk Copy Program:


Plus : Offers ability to load data into existing tables from Comma delimited text files
Minus: Data has to be in the right format

Firs
t,let
sex amines omeoft heopt ionst hatSQLSer v
erhasf orpopulating data. There are a
couple of built-in options available, but in my experience these are less than optimal when
working with VFP tables for a variety of reasons. Thef ir
sti st he oldst andbyBul kCopy
Program, or BCP (this is actually a command-line interface that harkens back to DOS days),
and the newer BULK INSERT command. Both of these offer the ability to quickly load
data into existing SQL tables from comma-delimited text files, but only if the data is
already in the right format. If you have t odoanydat at ransformation,t hi
swon tbemuc h
use to you. The one advantage this has is that it will bypass the logging of new records. When
bulk-l
oadingdat a,therer eallyisn
tmuc hpointtol oggi ngthet ransacti
ons .

3.1.2. Data Transformation Services:


Plus: Suppor
twider angeofopt i
ons ,Dat as our c
est owor kwi
th
Can be scheduled to run at off-peak hours

The second, and Microsoft-recommendedopt i


on,ist ous eDat aTrans f
ormat ionServices(DTS).
DTS has a wide range of options and types of data sources that it can work with. It can be
scheduled to run at off-peak hours and can use VB-Script to transform data into the format
expectedbyy ourt ables.Howev er
,y ouc an
tdynami call
yalterexist
ingSQLdat abaseobj ectsas
DTS only imports data. Furthermore, when importing from a VFP data source, DTS uses ODBC,
whichdoes ntproperlyhandl eemptydat esthatmayc omei nf r
om y ourVFPt ables.

There are two other methods, though, that we will look at in more detail: using the VFP upsizing
wizard and writing your own data import program.

3.1.3. The VFP Upsizing Wizard


Plus: Automatically generates table structures, index, defaults, RI, validation rules etc

Minuses:
a. Does not upsize free tables
b. Does not upsize triggers , Stored procedures as they have VFP centric function
calls
c. Table/field/index names that are reserved words in SQL will be created using the
word plus an underscore

The VFP Upsizing Wizard does a decent job of porting over simple, DBC-bound VFP tables and table
data (one of its failings is that it will not import free tables). It will, unlike DTS, generate table
str
uctures,index es ,def aul t
s,RIi nfor mat ionandv al
idati
onr ules ,meani ngt hedat abasedoes nt
even have to exist in SQL at the point you run the wizard. It will not upsize triggers or stored
procedures, which makes sense because these are most likely to have VFP-centric function calls
As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.
Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 10 of 22
VFP conversion to support SQL server Backend

(
whi
ch,nat
ural
l
y,won
tpor
tov
er)
.

When running the wizard, you have the option of specifying individual tables or groups of tables
to upsize, but the data within each table is all-or-nothing, and there are few data transformation
options beyond specifying the field type on the back end. So, for complex imports that involve
some degree of data remapping or value changes (like dealing with empty dates), this is not your
best choice. It does, however, generate the scripts required to do the import, and produces some
us ef
ulr epor ts,whi ch may pr ovi
de y ou wi th a jumpi ng-offpoi ntf orwr i
ting y ourown dat a
conversion routine. In addition, you have the option to replace your local tables with remote
views (more on them later) for relatively seamless switchover of your data source, provided you
have a well-behaved application.

Some words of caution when using the Upsizing Wizard:

Table/field/index names that are reserved words in SQL will be created using the word plus an
underscore.

Tables with capacity issues will not be generated, although the wizard will actually try to
do SOMETHING. But a more serious problem exists in that the Upsizing Wizard thinks table width
is limited to 1962 bytes (instead of 8060 bytes). This may be a holdover from SQL 6.5 days, but
in any event it means that the Wizard will not be able to handle tables of even moderate size.

Changing over to remote views is pretty destructive to your local tables. Make sure you really
want to do this before running this option!

3.1.4. Writing a Custom Converter

Custom Imports
Unmanned installations along with production data

Sooner or later, I think everyone ends up writing their own conversion routine, simply because
thet oolst hatar eav ail
able( DTSandt heUps i
zingWi zar
d)don tmeett her eal-world needs of
get ti
ngc ompl exdat aov eri ntoSQLSer ver.WhatdoImeanby real-world ?Thi nkaboutt he
following:
What is the condition of your data? Can you guarantee that every record in your ten-year-
old application is free of errors or missing key values? Will you need to map to new columns,
break out or combine tables, or change values? In all probably, the answer is yes to all three.

How about the size of thet ablet hatyou llbeimpor t


ing?Porting in large record counts
can be a time-consuming task, and you may need the ability to import only specific amounts of
records at first for prototyping and testing. And remember what has been imported might need
to be deleted when starting over.

How aboutf i
nali nstal
lat
ion orunmanned i nstal
l
ation?Reinstalling?You l
lneed t he abi
l
ityt
o
generate the final databaseand all of its componentsand load it with production.

Fortunately, this is not as complex as it might seem, for two reasons:


One, all SQL Server objects can be generated via scripts.
Secondly, VFP can pass those scripts directly to SQL Server via SQLEXEC() to make the
changes necessary.

As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.


Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 11 of 22
VFP conversion to support SQL server Backend

4. Data Access Techniques


And now the discussion that a lot of you pr obably hav e been wai t
ing for:what
st he bes t
mechanism for getting the data into SQL Server? VFP offers several options here, all with their
good points and bad. These include:

1. VFP remote views

2. VFP SQL Pass-Through, either as dynamically constructed statements or as calls to SQL


stored procedures

3. ActiveX Data Objects, or ADO, using either the RecordSet object or the Command object

With SQL Server 2000, we now also have the ability to accept and generate XML natively;
however, we will not be including this in our examination, as it would require a pretty thorough
overhaul of an existing system to enable it to deal with XML, which is outside the scope of this
discussion / presentation.

4.1. VFP Remote Views: Pluses


Remote views are DBC-defined SELECT statements working thru an ODBC-based connection.
Basically, they are just like local views, except that the data is going through ODBC to a remote
back end. Typically, remote views are predefined in a DBC, although they can be defined on the
fly.
Remote views have gotten a bad rap in the past, but they do have a number of good points to
offer:
They are convenient, because

4.1.1. Easy Conversion:


Remotev iewsar easc los
et o drop-intec
hnol
ogyasy
ouc
angetf
orappl
i
cat
ionc
onv
ers
ion,as
we saw earlier with the Upsizing Wizard

4.1.2. Ability to detect update conflicts:


Remote views also offer the ability to detect update conflicts and revert changes, and will only
send changed data back to the server

4.1.3. Easily switch Backends:


Remote views offer the ability to easily switch back ends (by changing the connection definition)

4.1.4. Automatic handling in Data types:


The ODBC driver automatically handles differences in data types (remember the difference
between bit and logical fields?)

4.2. VFP Remote Views: Minuses


If remote views are so conv
eni
ent
,what
st
hedowns
ideofus
ingt
hem?

4.2.1. VFP View Designer:


For starters, the VFP View Designer, which most developers start out using, has a few wellknown
faults. Complex views, which are joins of three or more tables, tend to be difficult to do because
theVi ew Des i
gnerof tendoes n
tgener atet heSQLs tat
ementqui t
er ight.I naddi ti
on,y ouc an
create views, using perfectly legal SQL exec statements and DBCSETPROP(), that the Designer
simply will not be able to deal with. This will cause anyone problems if they try to open the view
As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.
Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 12 of 22
VFP conversion to support SQL server Backend

in the Designer.

4.2.2. Perfomance:
Performance used to be a big issue with remote views, but with SQL Server 2000 and VFP 7
onwards this has become less of a problem, although remote views are still typically slower when
compared to the other data access techniques.

4.2.3. Requires VFP Database Container:


Remote views require the use of a VFP database container. This can cause you grief in a couple
ofdi f
ferentway s.Mos tnotably,ifther emot ev i
ewss peci
fyaf i
eldl i
st,theDBCc anbreak ifthe
table structure changes on the server. If you allow dynamic creation of remote views (for user-
modi fi
abl ev i
ews )youl
lhavet obec onc ernedwi thDBCbl oat.

4.2.4. Cant call SQL Stored Procedures:


Remot eviewsc antcal
lSQLs toredprocedur es .Thi sisa problem, because right there you lose a
lot of the power of SQL Server and nearly all of the inherent horsepower that SQL hardware can
offer.

4.2.5. Data changes takes place on a client:


But the biggest issue, in my opinion, is that if you want to make changes to the data, it has to
take place on the client. This means that you could be passing lots of data back and forth to the
server, which has a direct impact on performance. Every trip to the server affects performance.
Server-based operations are faster, and speed is something you need to keep thinking about in
client/server operations. This is also a problem in that remote views are basically unaware of
data changesdefault values, key generation, and so forththat may occur on the server side.
While true for any data on the client side (no matter how you got it there), if you APPEND BLANK
in a remote view, you stand a good chance of accidentally overwriting default values with blank
or null values.

4.3. SQL Pass-Through: Pluses


VFP provides a second method to get at SQL-based data, called SQL Pass-Through (SPT). SQL
statements are sent through the connection to run directly against the server, via the SQLEXEC()
function.

4.3.1. Multiple connection options:


Connections can be DBC-defined (using ODBC), or opened either thru SQLCONNECT (again,
using ODBC) or SQLSTRINGCONNECT (for DSN-less connections).

4.3.2. Faster than remote views:


SPT calls are typically faster than remote views, although this is not as dramatic as it was with
earlier versions of VFP.

4.3.3. Ability to call stored procedures:


But the big advantage of SPT over remote views is their ability to call stored procedures. SQL
stored procedures are stored in the database in an optimized or compiled form. Just like a
compiled VFP program, stored procedures execute faster than ad hoc queries (which must be
compiled before running). In general, you will get better performance, not to mention flexibility,
by using stored procedures instead of building select statements dynamically and passing them
directly through SQLEXEC(). The exception to this is in building simple, one-line SQLEXEC()
statements. There appears to be no noticeable difference between single-line statements and
stored procedures in terms of speed.

As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.


Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 13 of 22
VFP conversion to support SQL server Backend

SPT gives you the ultimate flexibility in terms of what to do with the data. Normally, returned
result sets are passed into a VFP cursor; however, with the use of the SQL OUTPUT parameter,
single-row results can be passed directly to VFP variables when executing a stored procedure.

Youdon thavet ogener at


ear esult;statements like INSERT and UPDATE can execute directly
against the backend. However, for interactive changes, the data still needs to be sent to the
client.

4.4. SQL Pass-Through: Minuses

4.4.1. More work:


SPT has its downsides as well, is the top one being that there is more work required on your
part.

4.4.2. Have to handle update conflicts:


SPThasnoneoft he
knowl edgeofhow t oc ommuni c
ater esult
sbac kt ot hes erv er.Wher et hi
s
is handled automatically by the remote view, you will have to work out the details of updates and
conflict resolution.
Her esanex ampl e:wheny oufire an SQLEXEC call, the resulting cursor is non-updating, and by
thatIdon tmeany ouc antmodi fyt hedat a,itmeanst hatify oudomodi fyt hedat ay ouar e
responsible for passing the updates back to the server. To get around this, you can use
CURSORSETPROP method calls to tell the cursor how to communicate back to the server.

4.4.3. Must know more details about backend table structures:


One other disadvantage is that you are required to know more of the details regarding the back-
endt ables tructur
es.Per sonal lyIdon thav eapr oblem withthi
s,andwi ththeimpr ovementst o
the Enterprise Manager, it is a lot easier to examine the components of an unfamiliar database.

4.4.4. Data translation issues:


A more import
antpr
obl
em i
sthaty
oumayhavesomedat
at r
anslat
ioni
ssues
.Namesli
keO
Niel
canc aus eapr
obl
em,si
ncethedat
aof
tenneedst
obewrappedinastr
ingtobepas
sedbackto
the server.

4.5. ADO Pluses


ADO is a collection of COM objects published by Microsoft and used to access any data source that
has an OLE-DBpr ovideravailable.ThePEM sav ai l
ablei nADO of feral otofpower&f lexi
bili
tyt o
the developer, while hiding the complexity of dealing with OLE-DB.

4.5.1. ADO data is available as properties within the RecordSet or Command


object
ADO is the choice for n -tier development, but shoehorning it into an existing application can be a
difficult chore. Most VFP controls will work with ADO recordset objects; ADO data is available as
properties within the RecordSet or Command object, so it is easy to use these properties as
cont r
oldat as ources.Theex cept i
onar egr i
ds ,andy oul
lhavet os ubsti
tut ethird-party classes
for the native VFP grid control if you want to display ADO-bound data that way.

Like SPT, changes to the data can be made on either the client side or server side. However,
ADO handles SQL data on either side more like VFP developers are used to. What do I mean by
that? As mentioned earlier, SQL is constructed to handle data in sets not in individual records.
This is great for batch processing a single command, for instance, can make changes across an
entire table but interactive manipulation requires the data to be brought to the client with a
As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.
Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 14 of 22
VFP conversion to support SQL server Backend

remote view or SPT (think performance). If you need to navigate through a result set, the ADO
RecordSet object has native methods that allow you to do that with either client-side or server-
sidecursors,soy oudon thav et obri
ngt hedat adown.

4.5.2. Update conflicts built:


One other advantage that ADO has is that transaction processing and update conflict detection
are built-in. Remember, with SPT, constructing this is on your shoulders.

4.6. ADO Minuses

4.6.1. VFP
snat
ivecont
rol
swi
llnotwor
k:
As I just mentioned, one of the principle objections many developers have to ADO is that some of
VFPsnat i
vec ontrol
swi l
lnotwor kwi thADOr ec ordset
s.

4.6.2. Time consuming:


A bigger pr oblem,t hough,i st hat t he results ets may need t o be conver ted to VFP-
understandabl ecursorsinor dertot akeadv antageofs omeofVFP sdata handling abilities. This
can be a time-consuming business, and not one I recommend doing on large result sets.

4.6.3. DLL issues:


As with any Active-X object, you can run into DLL issues with ADO. There have been a number of
different releases, and you can fi ndy ours
el fi
n DLLHel lt ryi
ngt omak es urethec
li
entmac
hines
have the right version with all of the PEMs that you are calling in your system.

4.6.4. Might require refactoring:


Lastly, ADO takes some work to implement, and that may require a great deal more refactoring
that you (or your budget) may want to do.

4.7. Which is Best?


So,whi chist
hebestmethod?Ther
eisno r
ight
answerher
e.Ifyouwereexpec
tingadefi
nit
ive
wor dont hesubj
ect
,Ic
antgiv
eittoyou.Themethodyouchooseneedstobebas edons
everal
factors:

Your immediate needs, such as how fast do you want to be able to switch from VFP to
SQL? Remote views may be the best option, although you can construct your own classes to use
SPT as well to deal with many of the data handling chores.

How much refactoring do you want to do now? Obviously ADO has some strengths you
may want to exploit, but it will take a lot more work to make it fit into an existing application.

What is the future scalability of the application? If you anticipate going to a distributed
platform or need access through a Web interface, ADO is your best choice.

Again, what I hope I have done here is make you aware of the differences and relative
performance of the various data access methods you can use. Ultimately, your business
requirements should drive the decision and not a personal preference to one method over any
other.

As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.


Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 15 of 22
VFP conversion to support SQL server Backend

5. Constructing and Supporting the Application


5.1. More Design Issues
So, what else is there besides knowing about data differences and getting the data into SQL?
Wel l
,lots,es pecial
lyi fyouar etak i
ngadv antageoft hec hangeov erto addr es
saf ew pr oblems
withiny ourex ist
ing s ystem.Bef ore getti
ng started,l etme poi ntoutt hatt he issuesI
llbe
covering in the next few paragraphs will be concerned more with OLTP (on-line transactional
processing) systems rather than decision support systems. Decision support systems, such as
data warehouses, have different construction and optimization requirements, which are outside the
scope of this discussion / presentation.

5.2. Connections
No matter what data access technique you decide to use, all require some type of connection
being made to the back end. Remote views are limited to using ODBC through a defined DSN;
SPT can use that, or make its own DSN-less connection depending on the operating system; ADO
can go directly through OLE-DB.

If
,forwhat ev erreason,y oudec idet hatdef i
nedODBCDSNsar ewhaty ouneed,her esabi tof
warning: defining a DSN during installation is a pain. It is possible, but the code required is
operating-system specific. If, on the other hand, you have decided to go with SPT as your data
access method, you can bypass this by using a DSN-less connection. The output parameters
example above contains an example of this.

One of the things that really surprised me when I first started experimenting with SQL is that there
is no native VFP function to determine whether a connection is still good. This is especially
important with interactive data changes (data in grids, for example).

One obvious solution to some of these problems is to have a defined connection class.

5.3. Performance
Performanc ei sthe holygr ai
lofc li
ent /serverappl ications .We vet al
ked aboutper formanc e
throughoutt hiswhitepaper ,and I
m goi ngbeatt hes ubj ectt odeat hher e.Pure and simple,
performance dictates the success or failure of your application in the eyes of the end user, and
correcting performance problems down the road can be costly and painful.

Her
ear
emyt
hree
gol
denr
ulest
oremember
aboutc
li
ent
/ser
verper
formance:

Every trip to the server affects performance

Limit your trips to the server for better performance

You can improve system performance by limiting trips to the server

5.4. Limit Trips to the Server


We vement
ionedaf
ew oft
hes
eear
li
er,buther
ear
e a few of the ways you can limit trips to the
server:

Pass only the smallest result set required to accomplish the mission. Never give the user full
access to a table. Remember our discussion regarding navigation bars? There is usually no good
business reas on t o mai
ntai nt hese,othert han we
veal way sdonei tthi sway .Thi nkoft he
capacities to which SQL will allow your tables to grow. Does the end user really need to be able
As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.
Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 16 of 22
VFP conversion to support SQL server Backend

to go top/go bottom on a million-record table?

Keep static tables on the client if possible. This is more of an option for fat-client systems. Some
table data hardly ever changes, such as system codes, state abbreviations, and industry
acronyms, so there is no reason to be constantly passing these back and forth. Normal system
maintenance patches can handle exporting the revisions out to the clients.

Do as much processing on the server as possible. Take advantage of SQL views, stored
procedures, and triggers to prepare result sets, populate default values, create child records, and
so forth. Think about separating some of the business logic related to preparing and maintaining
data onto the server and out of the client.

5.5. Other Performance Issues


As I mentioned previously, table design has an impact on SQL performance. Using the right size
fields for the job is one area; proper normalization is another. Overall database design is also a
factor; by that, I mean how and where the database files are stored in relation to each other?
SQL databases can be split into physically separate files on different platters of a RAID 5 system,
for example, to speed up access. Here we are getting into the more esoteric aspects of SQL
Server, and if your client or corporation can afford to do it, having a DBA will be a big help.

Query efficiency is also very important. Use the execution plan and trace monitoring tools in the
Query Analyzer to help determine if your queries are performing at their best. Just like VFP, SQL
performance can be dramatically improved by having the right indexes available. Some very good
tips for query performance can also be found on http://www.sql-serverperformance.com/.

Writing to the transaction log can also affect performance, although in general you will want to
do this. Under certain conditions, you may want to avoid writing changes to the log (for example,
doing a bulk delete of table rows prior to a data import). SQL 2000 also provides three different
recovery models with varying degrees of transaction logging. If you are really having
performance problems, this may be worth investigating. Again, under most circumstances, you
will want to go with the default full-logging option.

The server itself can also be a place to look for performance improvements. SQL Server is a
resource hog, and although you can install other software packages on the same box, running
them simultaneously with SQL Server will slow things down. I strongly recommend running your
production SQL Server database on a dedicated machine with the most hard drive space and
RAM you can afford. Believe me, it will make a difference. SQL Server Enterprise Edition is also
capable of running on multi-processor machines, and for very large installations, this is worth
considering.

Lastly, one of the things mos tVFPdev el


oper sdon tt akeintoac counti sc apac i
typl anning.Wi th
SQLSer ver6. 5andear li
er,t hiswasamuc hl argeri s s
ue,asadat abas esmax imum s i
zehadt o
be established at the time it was created. Expanding its size was very difficult. With SQL 7.0 and
SQL 2000, this is no longer the case, but if you fail to take database growth into consideration
beforehand, you will see occasional performance slowdowns as SQL adjusts the size of the
database. Capacity planning is also important in setting up clustered indexes. Since rows in a
table will be stored in the clustered index order, it is important to allow for a certain percentage
ofgr owt h when c onstructi
ng t hei ndex( donebyadj ust
ing the fi
llfactor).Ex ceedingt hef i
ll
factor will not prevent new records from being added; however, it will fragment the data, causing
slow queries.

5.6. Metadata
Metadata is data about data information about the tables, columns, procedures, and other
As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.
Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 17 of 22
VFP conversion to support SQL server Backend

component sofadat abas e.AsVFPdev elopers


,wereus edt oc ert
ainaspects of metadata being
available for UI and report construction, maintenance, and so on. SQL Server does have this
information available, but not quite in a manner we are used to.
First,let
sgetonet hingoutoft heway .Youmayhavenot icedi nexperi
menting with or reading
aboutSQLSer vert hatt her ei ss omet hingc al
ledMet aDat aSer vi
ces.Unfor t
unately,itisnot
met adataasweVFPdev el
oper smi ghtunder standi
t.Inf ac
t,iti sas epar
atel
yi nstal
l
eds ervicefor
us emor ei ndat awar ehous ing.I tsadead end if you are looking for information about table
structures and so forth.

Real
met
adat
aisac
ces
sibl
evi
acal
l
stos
yst
em t
abl
esats
ever
all
evel
s:

The mas t
er databas ec
ont
ainsi
nfor
mat
ionont
hedat
abas
es(
onanygi
vens
erv
er)ands
ome
replication information

The ms dbdat abas


econt
ainsi
nfo on al
ert
s& j
obsmanaged bySQL
Ser
ver
Agent
,bac
kup &
restore info, etc.

The
dis
tri
but
iondat
abas
econt
ainsi
nfoonr
epl
i
cat
ions
chedul
es&t
rans
act
ions

Within a database are several tables with info on column sizes, indexes, etc

MS warns, however, that calls to the system tables are unsupported. Specifically, they do not
guar anteet hatthesystem t ablesstructureswon tchange( makinganyc odethaty oumi ghthav e
that relies on them unstable). Another very grave warning MS issues is about changing the data
withins ys t
em t abl
es.I n a wor d,DON T.The onl y ex cepti
on Ic an t hink ofwoul d be t he
sysmes sages tabl
e,whi chwewi lltal
kaboutl ateron.

Having said all of that, the system tables have all of the information you might need except one
i
mpor tantpiec ewe vec omet or el
yonf orUIandr epor ts:fieldcaptions.Unfortunatel
y,y ou
reon
your own here.

5.7. Transaction Processing


Aswe venot edbef or
e,VFPr emot ev i
ewsandADO hav et hei rownt r
ansactionprocessing (TP)
abilities built-in. However, if you are constructing a SPT-based application, you will need to
handle this on your own. SQL Server has excellent transaction processing mechanisms very
simi lart oFox Pro
s.Althought herear emi nors yntact
ical differences (and other commands for
distributed transactions), the concepts of BEGIN/COMMIT/ROLLBACK should be familiar to most
dev el opers.But ,thereareac oupleofpoi ntsthatI
dliket omak e:

First, TP can greatly affect system performance. Microsoft recommends the following strategies
for ensuring TP efficiency:

Keept ransactionss hor t


,andper f
ormt hem wi thi
nones t
oredpr
ocedur
e.Conv
ers
ely
,ther
esno
reason to wrap single SQL statements with a transaction.

Dontall
ow us eri nt
er venti
ondur i
nga transaction.
Frequently-used tables should be referenced at the end of a transaction.

5.8. Security

SQL Server has a very robust security model that offers a lot of flexibility to the database
developer. Not only is the data protected, but you can also establish rights for particular classes
ofusersdownt ot hec olumnl evelf orparticulartables.Wewon tc overSQLs ecuri
tyi ndet ailI
As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.
Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 18 of 22
VFP conversion to support SQL server Backend

really recommend having a DBA assist you in developing and implementing a good security plan -
but there are a few things t
hatI
dliket ohi ghlight,es peci
all
yi fyouintendt ous eSPTt ohandl e
database maintenance:

On installation, the system administrator password is set to nothing. Empty. And everyone knows
it. Be sure to change it.
Database objects tables, views, etc are defined as belonging to a user. Depending on your
security plan, most items are going to be assigned to the default DBO (database owner) account.
You will want to keep this in mind if you are constructing database objects programmatically,
because if they do not belong to DBO, then other users will not be able to access them.
Here are a couple of security features that you might want to take advantage of
SQL7i ntroduc edt hec onceptofr olesintot heSQLs ecuritymodel .Appr olesar e tempor ary
roles that you can assign for the duration of a connection to perform a variety of tasks that might
beout si
deaus er
snor malr ights.Forex ampl e,ifatabl es tr
uctur eneedst obec hanged,y ouc an
set the app role to allow the change to take place (under carefully-constructed conditions, of
course).
If you are concerned with clients reverse-engineering your stored procedures, SQL offers the
ability to encrypt the source code. However, this should be implemented with caution. The actual
code will need to be stored somewhere. One possible solution: you can keep the code external
(in a VFP table, checked into Visual Source Safe), and create the procedures programmatically
wi tht heENCRYPTEDs etti
ng.Howev er,keepi nmi ndt hatenc r
y ptedSPsc annotber epli
cated.

5.9. Errors & Error Trapping

Error Types Solution


1 Connection errors Have Application level Connection
class/handler
2 SQLExec returns negative Value (Only Use VFP query analyzer to sort out such
for SPT issues

3 Server side errors (Returns error Analyse / Modify error handling routines to
#1526) handle this

Let
st al kbr i
eflyaboutonemor edes i
gni s suey ou l
lhav et odealwi th,andthati
swhatt
odo
about errors. Because you are now dealing with at least two levels the client side and the
server side your work load for error trapping and reporting has doubled, at a minimum. If you
have any kind of mature VFP app, you probably already have the ability to deal with client-side
application errors. But surfacing server-side errors are a little more difficult.

To begin with, there are really three different types of errors related to the new data layer you
haveaddedwi thSQLSer ver.Thef ir
stwe vedis cuss
edal itt
leal ready ,andt hatiswhent herei sa
problem with a connection. Your system will need to know what to do if a connection is severed
or times out, which is why having a connection class (or some type of application-level
connection handler) is a good idea.

Another type of error, which really only applies if you are using SPT, is what to do if SQLEXEC
returnsanegat i
vev al
ue.I ft hestatementy out riedt opas sc antex ecute,SQL EXECr eturns1
with no clue as to why this happened. This can really be considered a system bug, and treated as
such with ASSERT statements. One habit I have adopted is to always put store the statement to
beex ec utedint oal oc alvariabl
e,t henpopt hatv ari
ablesv al
uei nto_CL IPTEXTi ftheSQLEXEC
result is negative (see the EXECUTE() method in the connection class outlined above). This way,
you can immediately paste the offending statement into the Query Analyzer to figure out what
went wrong.
As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.
Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 19 of 22
VFP conversion to support SQL server Backend

The last type of error problems that may occur on the server side when data is being updated
is where you will need to do the most work when modifying your error handling routines. For
starters, although VFP knows that an error occurred, the message number returned is always the
same (#1526), and the message itself is usually very technical. It may make perfect sense to
you, but to a user, it will be incomprehensible.

In fact, VFP knows more about the error than is immediately reported, which you can access thru
the AERROR() function. The fifth column of the array will give you the SQL Server error number;
the second row of the array will tell you what SQL Server did about the offending statement. If
yourer rorhandlerisntcapturi
ngt hev al
ueoft hatar r
ay,y oullneedt oi ncludeit.Ther eisn
tmuc h
more you can do here, except to display something a little less scary to the users. One way that
you can do that is by customizing the messages that SQL Server itself generates if you are using
stored procedures. The RAISERROR command allows you to construct your own error messages
on t he f ly, or y ou c an per manent l
yinstallt hem i nt he sysmes s agest able us i
ng t he
sp_addmes sagessys t
em s t
oredpr oc edure.

As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.


Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 20 of 22
VFP conversion to support SQL server Backend

6. Supporting the Application


So wi thallthatwe vec ov ereds of ar
,whatel s
ec ouldt her
ebet otakecareof ?Pr obablymore
than you think. If you are making the leap to client/server, the reach and scope of your
applicationisprobabl yal otlar gert hanwhaty ouvedeal twithbef
ore.Youwi llneedt odevel
op
strategies for testing, installation (both on the client and on the server), and database
mai ntenanceandbac kupst hatmaybedi ff
erentfr
om whaty ou
vedoneupt othis point.

6.1. Development & Testing


Testing is a sore point with me; one of the first client/server projects I was involved in was
hampered by a penny-pi nc hing manager who di dntunder stand t he need f or a separ at
e
developmentandt estings er ver.I
twasntuntil a runaway process locked up the SQL Server box
we only had one that he finally found the funds for a separate computer for development.
Fortunately, SQL can now be installed locally for prototyping, development, and testing
independently of any server.

Version control is going to be a little more complex than what you are used to. You will need to
make sure that the client or middle tier pieces are compatible with the version of the database
that you are working against. And conversely, as new pieces of code are migrated from local
wor kstationstot he t estpl at
form( ortestt o producti
on),y oullhav et o mak es uret hatthe
database is updated (if necessary). This can be a real challenge if you have multiple developers
involved.

Again, because there are now at least two layers to the system, testing is also more complex,
andi fyourdev elopmentt eam ordepar tmentdoes n
thav eany thingmor ef or
malpr
ocessthan
ohy eah,It es t
edt hat,theresbi gt r
oubl el urki
ngar oundt hec orner.Atami ni
mum,y ouwill
need the ability to recreate the database and repopulate the tables from a known baseline, so
that you can get consistent results when testing complex parts of the system.

Lastly, there are a couple of good tools to help you with database design and development. First,
SQL itself comes with a very good Database Diagram tool that you can use to create tables,
establish relationships between them, and most of the other developmental stuff you might need
to do. However, it will not allow you to make modifications to existing objects in a diagram
without changing the actual database objects themselves when the diagram is saved (although
you can save the changes to a script to be run later). This feature is specific to SQL Server, and
the diagrams are kept within the database itself. There are several database design tools on the
market, but the one I have most familiarity with is xCase (www.xcase.com) from Resolution Ltd.
xCase has excellent diagramming abilities, can construct the diagrams independently of the
database, will reverse- and forward-engineer models for VFP and Oracle as well as SQL, and the
diagram files are external, meaning they can be shared and protected by your version control
softwar e.Andi fyoudon tthink that is important, I have some real estate to sell you.

6.2. Installation and Updating


Installation and updates are another area where having more than one layer will change the way
you wor k.Itpr obablygoeswi thouts ay i
ng thaty ou l
lhav e di
ff
erentins
tall packages for the
varioust ier
s,butmor eimpor tantly,y ouwi l
lhav edifferentupdat emec hani
smsaswel l
.Let
st al
k
about installs and update to the client software here for the moment.

VFP comes with its own application builder, but it includes all possible VFP runtime files which
makes the installation set pretty big bigger than what you might want to download across a
network. Again, there are a number of third-party tools you can use (Tarma Installer- Australia
based, InstallShield and Wise Install are few to name) to create smaller install sets and handle all
As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.
Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 21 of 22
VFP conversion to support SQL server Backend

of the details of a client installation (like putting an icon on the desktop).

Updat esar eal itt


letrickier,bec aus ey oupr obabl ydon
twantt ohav et or edis
tri
butet heent i
re
install set every time a change is being made. rtPatch by PocketSoft (www.pocketsoft.com)
produc es small patchf i
les by c ompar ing ex ec
utabl
ev ersions and bui lding a separ at ef i
le
containing only the changes, without requiring you to know where all of those changes might
exist within the application. It was relatively simple to use, requiring only a couple of files to
resideont hec l
ient(whi c hy ouc ani nc ludewi ththeinst
allsetwhatac onc ept).Pl anf ort his
now because having to fit this in later is painful.

How you distribute the patch files will most likely depend on your business infrastructure, but it is
important to note that you will probably need to coordinate a revision on the client side to a
change in the underlying database.

6.3. Database Maintenance


This brings us to the topic of database maintenance. SQL Server is a very robust product, but
even it needs occasional tune-ups. Depending on your system size, many routine maintenance
items, such as backups, reindexing, and replication, can be scheduled for off-peak hours to
minimize the impact on users. SQL has excellent tools for setting up these tasks, but even so, a
large database can take the efforts of a full-time DBA to maintain it in peak condition.

Non-routine maintenance, such as making structural changes to a table, are a little more difficult
to handle. No system is static; changing business requirements might require revisions to the
underlying tables and stored procedures that comprise a software database system. Hopefully,
you are developing a well-documented system and know all of the possible places a table change
mi ghtaf f
ectthec li
entcode( youar e,aren
tyou?),andhopef ul
lyy ouar ek eepi ngc hangesl i
ke
this to a minimum. Coordinating a change to the server with revisions to client software can be
difficult, because no matter how many advanced notices you send out, someone will go home
with their system up and locks on a table.

If you are building more of a traditional client/server application (as opposed to an n-tier app
with a browser interface) you will need to have the ability to lock out clients for the time it takes
to apply change scripts or revise data within SQL. How you implement that is really going to be
decided by your business needs. You can take the brute-force approach and simply go through
the SQL Enterprise Manager, find out who is doing what through the Current Activity option, and
kick them out. But this is pretty traumatic for the users, who may have a perfectly valid reason
for being in the system at the time. A better solution would be to build some type of gatekeeper
device that refuses access for users when database maintenance is going to occur.

As Presented at OZFOX 25th-26th March 2006 by Rahul Desai.


Email: rahul.desai@talman.com.au / rahul@nationalcom.com
Page 22 of 22

You might also like