Sei sulla pagina 1di 51

04-P1914

8/24/2001

11:26 AM

Page 134

SQL Server CE Remote Data Access and Replication

Remote Data Access (RDA) and replication are two techniques that allow you to take data from an SQL Server running on Windows NT or Windows 2000 and use the data in an SSCE database on a Pocket PC or HPC 2000 device. The data can be modied locally, and then changes can be sent back to the SQL Server database. Data conicts (such as when a single record is modied in both the SSCE and SQL Server database) can be tracked and resolved. With both techniques, the Pocket PC or HPC 2000 device connects to the network through an Internet Information Server (IIS) using HTTP, and IIS can be used to apply login authorization and secure the transport of data. In general, RDA is easier to setup and is most appropriate when devices are infrequently connected to the network, and where your Pocket PC or HPC 2000 applications need control on when data will be transferred and complete control over conict resolution. RDA will work with SQL Server versions 6.5, 7.0, and 2000. Replication can be more difcult to setup and requires more SQL Server administration knowledge. It is ideal where a device is nearly always connected (e.g., through a wireless connection such as GPRS), but it can still allow data changes to be made when the device is not connected. Replication only works with SQL Server 2000.

For the sake of clarity, SQL Server for Windows CE will be referred to as SSCE in this chapter, and SQL Server 6.5, 7.0, or 2000 running on Windows NT or Windows 2000 will be referred to as SQL Server.

Some typical uses of RDA and replication include

134

04-P1914

8/24/2001

11:26 AM

Page 135

Remote Data Access

135

G G

Pulling down up-to-date price lists from a central server Recording orders locally on an SSCE database and then sending them to a central SQL Server Pulling down updated customer details, making changes to the customer lists in the SSCE database, and sending changes back to the SQL Server

Because IIS is used to connect to the SQL Server, Windows NT authentication can be used to secure access. Since HTTP is used to transfer data, Secure Socket Layer (SSL) HTTP requests can be used to secure the data in transit. Using HTTP makes deployment easiermost rewalls and proxy servers are congured to allow HTTP requests from outside the organization, so additional ports and protocols do not need to be congured. Finally, the data is compressed in transit, making transmission efcient even over low bandwidth connections. You will need to plan carefully the amount and nature of the data you will be transferring using RDA or replication. Storage on Pocket PC and HPC 2000 devices is limited (your entire customer database may not t!), and the more data you involve in RDA or replication, the slower the transmission will be. In most cases, it is possible to identify subsets of the data, either by selecting rows (select customers assigned to a particular salesperson) or columns of data (only these columns of data are relevant in the mobile situation). Ensure that you test your RDA or replication setup across the typical connection speeds your users will operate over, rather than the fast network connection you may use in development.

Remote Data Access


RDA allows you to pull the entire contents of a table, or selected columns and rows of data, from a Microsoft SQL Server 6.5, 7.0, or 2000 database and store the contents in an SSCE database table. The table in SSCE will automatically be created by the pull operation, and the pull process will convert SQL Server data types to appropriate SSCE data types. Primary key and other constraints will also be created in the local SSCE database table, but relationships with other tables will not be created. Once a table is pulled down into an SSCE database the data can be accessed and manipulated using ADOCE. You can add relationships with other tables, such as declaring foreign keys using ADOXCE. When a table is pulled you can turn on tracking, and this allows you to push the changes you have made to the SSCE table back up to the SQL Server database. You can specify a table name that will contain a list of conicts detected when a push is made. RDA also allows you to execute SQL statements from a Pocket PC or HPC 2000 on an SQL Server. Any SQL statement can be executed, including stored

04-P1914

8/24/2001

11:26 AM

Page 136

136

Chapter 4

SQL Server CE Remote Data Access and Replication

procedures, INSERT, DELETE, and UPDATE statements, so long as the SQL statement does not return a result set. RDA operates through Internet Information Server (IIS) running on Windows NT 4 or Windows 2000 and can use an SQL Server located on the same server as IIS or on a different server. The conguration of RDA can be a little tricky, as you need to congure IIS, SQL Server, and Windows NT or Windows 2000 security, so you should follow the instructions in the next section carefully.

RDA Installation and Conguration


Figure 4.1 shows the RDA architecture, the key elements of which are
G G

SQL Server CE Client Agent SQL Server CE Server Agent

The Client Agent implements the SSCE.RemoteDataAccess.1.0 object that you program against to push and pull tables and to execute SQL statements on an SQL Server database. This functionality is implemented in the le ssceca10.dll, and this should be installed in the \windows directory on the Pocket PC or HPC 2000 device. The Server Agent receives push, pull, and SQL execute requests from the client agent and passes these requests on to the SQL Server. It manages the re-

Figure 4.1

Remote Data Access architecture

04-P1914

8/24/2001

11:26 AM

Page 137

Remote Data Access

137

turned data and conict resolution. This functionality is implemented in the le sscesa10.dll, which is an ISAPI (Internet Server API) application that is installed in a Web virtual directory and is managed by IIS. REQUIREMENTS To install and use RDA you will need
G

G G

A Pocket PC or HPC 2000 with SSCE installed (as described in the last chapter), together with the le ssceca10.dll copied into the \windows directory on the device A Windows NT or Windows 2000 server running IIS An SQL Server 6.5, 7.0, or 2000 server running on either the same server as IIS or a different one

The Pocket PC or HPC 2000 should be capable of connecting to the IIS server. This can be a direct network connection using a network card or a dialup RAS (Remote Access Server) connection. Making RAS connections is described in Chapter 8. Alternatively, you can use the SQL Server Relay through an ActiveSync connection using a serial or USB connection, as described later in this chapter.
While you can use Windows NT or Windows 2000, and either SQL Server version 6.5, 7.0, or 2000, the instructions in this chapter describe setting up RDA on a Windows 2000 Server with SQL Server 2000 running on the same server. Instructions for Windows NT and other versions of SQL Server can be found in the on-line documentation.

The examples in this section will show how to setup RDA to the pubs sample database shipped with SQL Server. The same principles can be applied to any database. The example here uses a Windows 2000 Server called malahide with an IP address of 190.100.100.120. You should change these where appropriate to your server name and address as you follow through these instructions. INSTALLING SSCE SERVER TOOLS You will need to install the SSCE Server Tools on your server running IIS. Note that if you have IIS and SQL Server on separate machines, you need only run the SSCE Server Tools setup on the IIS machine.
G G

Run the ssce11.exe setup application. On the opening screen, ensure that Server Tools is selected and Development Tools is unselected. Click Next.

You can now follow the wizard steps to complete the SSCE Server Tools installation.

04-P1914

8/24/2001

11:26 AM

Page 138

138

Chapter 4

SQL Server CE Remote Data Access and Replication

CONFIGURING IIS The best place to start conguring RDA is with the IIS server. You will need to
G G G G

Create a virtual directory Copy the le sscesa10.dll into the directory Set le and directory access permissions in this directory Specify the authentication control used on the website.

First, run the Internet Information Services application and create the virtual directory:
G

Select the Start Programs Administrative Tools vices Manager menu command. Alternatively, on Windows 2000 Professional you can

Internet Ser-

G G G

Run the Control Panel Double-click the Administrative Tools icon Double-click the Internet Services Manager icon To create the virtual directory

Expand out your server name (malahide in Figure 4.2), and Default Web Site Right-click Default Web Site and select the New Virtual Web Directory menu

Selecting this menu command starts the Virtual Directory Creation Wizard.
G G

Click Next in the opening screen. Enter the alias name for the virtual directory (see Figure 4.3). In this example you should use sscePubs. Click Next. The virtual directory needs a folder that it will map to for content.

Use File Explorer to create a new folder \Inetpub\wwwroot\ssce Pubs. Select this folder in the Web Site Content Directory wizard page (see Figure 4.4). Click Next.

The next screen allows you to specify the access permissions for this website. RDA is implemented through an ISAPI DLL, and so Execute permissions must be enabled. Other permissions are not required.
G

Ensure only Execute (such as ISAPI applications or CGI) is selected in the Access Permissions wizard page (see Figure 4.5). Click Next and then Finish.

The next stage is conguring Directory Security options for this new virtual directory. It is crucial to get this right; otherwise, you will end up with an insecure website or will not be able to access the website at all.

04-P1914

8/24/2001

11:26 AM

Page 139

Remote Data Access

139

Figure 4.2

Internet Information Services

G G

Right-click the new sscePubs virtual directory in the Default Web Site list in the Internet Information Services application. Select the Properties menu command. Select the Directory Security tab in this dialog and click Edit.

This displays the Authentication Methods dialog (see Figure 4.6). By default, anonymous login will be enabled (unless this option is changed in Default Web Site within Internet Information Services), and this species a login that will be used if the application making the HTTP request does not supply a Windows NT or Windows 2000 username and password. By default, the username is IUSR_<servername> where <servername> is replaced with the name of the service IIS is running on (for example, IUSR_Malahide). Clicking Edit allows you to change the login name used for anonymous access. Integrated Windows authentication allows the client application to specify a username and password that will be used to authenticate access to IIS and is more secure than using anonymous login. You should avoid using Basic authentication.

04-P1914

8/24/2001

11:26 AM

Page 140

140

Chapter 4

SQL Server CE Remote Data Access and Replication

Figure 4.3

Selecting the virtual alias name

In this example, anonymous login will be used; however, you may wish to use Integrated Windows authentication in a production system.
G

Click the Edit box in the Authentication Methods dialog and record the name of the anonymous username. Close all the open dialogs.
Note that the Directory Security page allows you to setup certicates for enabling Secure Socket Layer (SSL) for encrypting data in transit. This allows you to use HTTPS rather than HTTP when using RDA. You should enable SSL when transmitting data across public networks such as the Internet.

You now need to copy the ISAPI DLL into the folder used by the virtual directory you have just created and to set the correct permissions on the directory.
G

Run File Explorer and copy the le sscesa10.dll from the install location (which is, by default, in the folder \Program files\Microsoft SQL Server CE\Server) to \InetPub\wwwroot\sscepubs.

04-P1914

8/24/2001

11:26 AM

Page 141

Remote Data Access

141

Figure 4.4

Selecting the Web site content directory

Run a command shell (cmd.exe), navigate to the \InetPub\wwwroot \sscepubs folder, and run regsvr32 on this DLL:

Regsvr32 sscesa10.dll

This registers the COM components in this DLL. This DLL needs to read and write les in the \InetPub\wwwroot\sscepubs folder, so the anonymous user (or other users if you are using Integrated Windows authentication) must be granted access. Note that this is not done though the Internet Information Server administration program, since remote client does not need to perform the reads and writesit is the DLL itself that does.
G G G G

Run File Explorer, and select the \InetPub\wwwroot\sscepubs folder. Right-click the folder sscepubs and select Properties. Click the Security tab (see Figure 4.7). Click the Add button to add another user to list of users granted permissions on the directory. Select your IUSR_<servername> user (e.g., IUSR_MALAHIDE) from the list of users, click the Add button and click OK.

04-P1914

8/24/2001

11:26 AM

Page 142

142

Chapter 4

SQL Server CE Remote Data Access and Replication

Figure 4.5

Selecting the access permissions

Select the newly added user in the Name list, and click Full Control in the Permissions list. Click OK to accept the change to the security settings.

TESTING THE IIS INSTALLATION You can now test the IIS installation at a basic level by attempting to execute sscesa10.dll through Internet Explorer.
G G

Run Internet Explorer on your server PC. Enter http://localhost/sscePubs/sscesa10.dll in the address line and press Enter.

If IIS is congured correctly you should see the word Body being displayed. This indicates that IIS could connect and execute the ISAPI function in sscesa10.dll. If you get an error 500 returned, check that you have copied sscesa10.dll into the virtual directory folder and that you have successfully registered the DLL with regsvr32.dll. If you get a permissions problem, check that you have assigned execute permissions to the virtual directory and read/write permissions on the folder.

04-P1914

8/24/2001

11:26 AM

Page 143

Remote Data Access

143

Figure 4.6

Directory security

You can check the username being used to access IIS through the logs:
G G

Navigate to the folder \winnt\system32\logfiles\W3SVC1 Open the most recently accessed log le with Notepad and scroll to the end. You will see lines like the following:

2001-04-06 12:28:37 190.100.100.98 - 190.100.100.120 80 POST /sscePubs/sscesa10.dll - 200 SSCEReplicationClient

This shows the date and time of the HTTP request followed by the IP address of the requester and the IP address of IIS. The - between the two IP addresses indicates that an anonymous login was used to access IIS. If Windows authentication was used, the domain name and username would be shown:
2001-04-05 18:30:40 190.100.100.98 MALAHIDE\Administrator 190.100.100.120 80 POST /sscePubs/sscesa10.dll - 200 SSCEReplicationClient

TESTING THE POCKET PC OR HPC 2000 CONNECTION You can now test that your Pocket PC or HPC 2000 can connect to your IIS server by using Pocket Internet Explorer.

04-P1914

8/24/2001

11:26 AM

Page 144

144

Chapter 4

SQL Server CE Remote Data Access and Replication

Figure 4.7

Folder security

G G

Run Pocket Internet Explorer on your Pocket PC or HPC 2000 device. Enter the address http://Malahide/sscepubs/sscesa10.dll in the address line, replacing Malahide with the name of your server.

Pocket Internet Explorer should display the text Body if it can connect to sscesa10.dll.
Note that the screen will be blank if you have Fit to Screen turned on, so use the View Fit to Screen menu to turn off this option and ensure that the text Body appears.

If you cannot connect, try using the IP address of your server rather than the server name. For example, enter http://190.100.100.120/sscepubs/

04-P1914

8/24/2001

11:26 AM

Page 145

Remote Data Access

145

sscesa10.dll in the address line, replacing 190.100.100.120 with the IP address of your server. If this solves the problem it is likely that the Pocket PC or HPC 2000 cannot connect to a Domain Name Server (DNS), or the DNS is not congured properly. You can either x the DNS problem or continue to use an IP address in place of the server name. You will need to be careful, though, if your server has a server-assigned IP address rather than a xed IP address the next time the server reboots, the IP address may change, and you will no longer be able to connect. Once you have IIS congured, you can move on to conguring SQL Server.

CONFIGURING SQL SERVER 2000 When conguring SQL Server 2000 there are two types of security you can use:
G

Mixed security (SQL Server and Windows): Users can login either using an SQL Server login identier or using integrated security with an automatic login using a Windows username. Windows only: Integrated security only with a Windows username. This is sometimes known as trusted security.

When using RDA, the type of security is selected through a connection string from within your program. However, you will need to ensure that the connection string you choose uses a security type congured on SQL Server. In this example, Mixed Security will be used so that code using both SQL Server login identiers and integrated security can be shown. To congure security
G

Run the SQL Server Enterprise Manager by selecting the Start Programs Microsoft SQL Server Enterprise Manager menu command. Expand out Microsoft SQL Servers under Console Root in the Tree pane until you locate your server (e.g., Malahide).

If you cannot locate your server, right-click SQL Server Group in the Tree pane, select the New SQL Server Registration menu command, and follow the Register SQL Server Wizard instructions. Next, you will set the security options for your server.
G

G G G

Right-click your server name (e.g., Malahide) in the Tree pane, and select the Properties menu command. Select the Security tab (see Figure 4.8). Ensure that SQL Server and Windows security is selected. Ensure that All is selected for Audit level.

Selecting All for Audit level causes SQL Server to write an event into the application event log for all attempts at logging into the server, regardless of whether they succeed or fail. Using this option when setting up RDA is useful, as you can quickly determine the username being used by IIS to access SQL Server. However, you should remember to reset this option at some stage

04-P1914

8/24/2001

11:26 AM

Page 146

146

Chapter 4

SQL Server CE Remote Data Access and Replication

Figure 4.8

SQL Server security options

to ensure your event log does not become full. Figure 4.9 shows a typical event log for a successful login using integrated (trusted) security for the anonymous login user IUSR_MALAHIDE. You will now need to check that users have the correct access rights to the database being accessed through RDA. In this example the user in question is IUSR_MALAHIDE and the database is pubs.
G

Expand out your server (e.g., Malahide) in the Tree pane so that Security is visible, and then expand out Security so Logins is visible. Single-click Logins to display the current list of logins (see Figure 4.10).

04-P1914

8/24/2001

11:26 AM

Page 147

Remote Data Access

147

Figure 4.9

SQL Server login

Notice that there is not currently an IUSR_MALAHIDE user added to this list. If you were to access the SQL Server through IIS with anonymous login, you would get an error explaining that IUSR_MALAHIDE was not a trusted user of the SQL Server. You now need to add a trusted user.
G

G G

Right-click Logins in the Tree pane and select the New Login menu command. In the SQL Server Login PropertiesNew Login dialog (see Figure 4.11), click the button with the caption . . . to the right of the Name edit box. Double-click IUSR_MALAHIDE from the list of users and click OK. Click the Database Access tab in the SQL Server Login Properties New Login dialog.

04-P1914

8/24/2001

11:26 AM

Page 148

148

Chapter 4

SQL Server CE Remote Data Access and Replication

Figure 4.10

SQL Server logins

G G G

Select the Permit check box for the pubs database. Select the db_owner role for the pubs database (see Figure 4.12). Click on OK to create the login.

Note that the user IUSR_MALAHIDE has had the db_owner role selectedthis grants full access to all objects in this database. You would normally not make a user a db_owner unless the user was a developer. Instead, you should set the permissions on all objects appropriately through the databases user permission settings. That completes the SQL Server conguration and the RDA setupyou now need to execute some RDA code to test the conguration. Remember, if you have trouble logging in to SQL Server or need to check the actual login being used, use the Event Viewer to look at the application event log.

Programming RDA
RDA is programmed through the RemoteDataAccess objects methods and properties. This object is created using the progid SSCE.RemoteDataAccess.1.0. A reference to the library Microsoft SQL Server Control 1.0 should be added to the project using the eVB Project Add References menu command. All the code shown in this section can be found in the project \Ex amples\PocketPC\RDA\RDA.ebp or \Examples\HPC2000\RDA\RDA.ebp on the CDROM. The code to use RDA is the same for Pocket PC and HPC 2000.

04-P1914

8/24/2001

11:26 AM

Page 149

Remote Data Access

149

Figure 4.11

Creating a new SQL login

PULLING DATA The RemoteDataAccess objects Pull method allows a table to be downloaded from an SQL Server database and the data loaded into an SSCE table. The Pull method automatically creates the table in the SSCE database and provides suitable data type conversions where the SQL Server database uses data types that are unsupported in SSCE. The Pull method is passed an SQL statement that will be executed on the SQL Server, and this denes the data to be downloaded. In the simplest case, you can specify a SELECT * FROM table type statement to download all elds and all records from the table. Alternatively, you can specify a list of elds in place of * or add a WHERE clause to lter only particular records. Be-

04-P1914

8/24/2001

11:26 AM

Page 150

150

Chapter 4

SQL Server CE Remote Data Access and Replication

Figure 4.12

Database access for an SQL Server login

cause almost any SQL statement producing a result set can be used, stored procedures, views, or SELECT statements joining several tables can be used. However, if you later want to push data back up onto the server, you should ensure that the recordset resulting from executing the SQL statement is updateable. There are some limitations to be aware of when using the RDA Pull method.
G

With SSCE databases, object names are not case sensitive, whereas SQL Server databases can optionally be congured as case sensitive. You cannot use RDA against a case-sensitive SQL Server database. You cannot pull data from a table having a primary key of type CHAR, NCHAR, VARCHAR, or NVARCHAR where the length of the eld is greater

04-P1914

8/24/2001

11:26 AM

Page 151

Remote Data Access

151

than 255 characters. In a Pull, elds of this type with a length greater than 255 are mapped to NTEXT, and an NTEXT eld cannot be a primary key. When using RDA to pull data from a table that also participates in replication on the server, you must exclude the system column with the ROWGUIDCOL attribute. By default, this column is named RowGuid. The number of columns pulled must be 253 or less. RDA adds two extra columns for tracking changes made to pulled data. You need to apply service pack 6 to SQL Server 6.5 when tracking data changes. Pull can be used with two different data change tracking options:

Tracking Off: The data is pulled from the SQL Server and SSCE does not monitor changes made to the data locally. Changes cannot be automatically pushed back to the server. Tracking On: Data changes made locally will be tracked. At a later stage, the changes can be pushed back to the server. Optionally, a table can be specied into which information on conicts will be added. In the rst RDA example, a new database will be created called

\pubs.sdf, and the three tables authors, titles, and titleauthor will be pulled from the pubs database without tracking. The relationships will not automatically be created between these tables during the Pull operation,

so they will be added using ADOXCE techniques described in the previous chapter. The code for creating the database and pulling the tables is shown in Listing 4.1. This code is associated with a form called frmGetTables in the project \Examples\PocketPC\RDA\RDA.ebp or \Examples\HPC2000\ RDA\RDA.ebp on the CDROM. The form is illustrated in Figure 4.13. The form prompts the user for the name or IP address of the IIS server and allows the SQL Server username and password to be speciedthe code uses an SQL login id rather than integrated security in this example. Clicking the OK button proceeds with creating the database (deleting the old database if one exists) and then pulling the three tables. A label on the form noties the user of progress. The form has a File System object called FileSystem1, and this is used to delete an existing database.
Listing 4.1 Pulling tables with RDA

Option Explicit Private sServer Private sUser Private sPassword Private Sub cmdCancel_Click()

04-P1914

8/24/2001

11:26 AM

Page 152

152

Chapter 4

SQL Server CE Remote Data Access and Replication

Figure 4.13

The form frmGetTables

Me.Hide End Sub Private Sub cmdOK_Click() sServer = Me.txtServerName sUser = Me.txtSQLUser sPassword = Me.txtPassword Call MakeDB Me.Hide End Sub ' makes the SSCE database by copying files from SQL Server ' using RDA. Private Dim Dim Dim Sub MakeDB() ceRDA As SSCE.RemoteDataAccess oCatalog As adoxce.Catalog sSvrCon, sLocalCon

' Delete database if it already exists, and then create On Error Resume Next If FileSystem1.Dir("\Pubs.sdf") <> "" Then FileSystem1.Kill "\Pubs.sdf" If Err.Number <> 0 Then DisplayError "Deleting database: " Exit Sub End If End If Set oCatalog = CreateObject("ADOXCE.Catalog.3.1") If Err.Number <> 0 Then DisplayError "Creating ADOXCE.Catalog object: "

04-P1914

8/24/2001

11:26 AM

Page 153

Remote Data Access

153

Exit Sub End If lblStatus.Caption = "Creating local database" sLocalCon = "Provider=Microsoft.SQLSERVER.OLEDB.CE.1.0;" sLocalCon = sLocalCon & "Data source=\Pubs.SDF" oCatalog.Create sLocalCon ' create the database If Err.Number <> 0 Then DisplayError "Creating Database: " Exit Sub End If Set oCatalog = Nothing lblStatus.Caption = "Connecting to remote server" Set ceRDA = CreateObject("SSCE.RemoteDataAccess.1.0") ' set RDA properties ceRDA.InternetURL = "http://" & sServer & _ "/sscePubs/sscesa10.dll" ceRDA.LocalConnectionString = sLocalCon sSvrCon sSvrCon sSvrCon sSvrCon = = = = "Provider=sqloledb;Data Source=(local);" sSvrCon & "Initial Catalog=Pubs" sSvrCon & ";user id=" & sUser sSvrCon & ";password=" & sPassword

lblStatus.Caption = "Pulling Authors" ceRDA.Pull "Authors", "SELECT * FROM Authors", _ sSvrCon, _ TRACKINGOFF If Err.Number <> 0 Then ReportEngineErrors "Pulling Authors:", ceRDA Exit Sub End If lblStatus.Caption = "Pulling Titles" ceRDA.Pull "Titles", "SELECT * FROM Titles", _ sSvrCon, _ TRACKINGOFF If Err.Number <> 0 Then ReportEngineErrors "Pulling Titles", ceRDA Exit Sub End If lblStatus.Caption = "Pulling TitleAuthor" ceRDA.Pull "TitleAuthor", "SELECT * FROM TitleAuthor", _ sSvrCon, _ TRACKINGOFF If Err.Number <> 0 Then ReportEngineErrors "Pulling TitleAuthor", ceRDA Exit Sub End If

04-P1914

8/24/2001

11:26 AM

Page 154

154

Chapter 4

SQL Server CE Remote Data Access and Replication

Set ceRDA = Nothing Call AddIndexesEtc(sLocalCon) End Sub

The function MakeDB uses the FileSystem1 controls Dir method to determine if the le \pubs.sdf already exists. This method returns an empty string if the le does not exist or the fully qualied lename if it does. The Kill method is used to delete the le:
If FileSystem1.Dir("\Pubs.sdf") <> "" Then FileSystem1.Kill "\Pubs.sdf" If Err.Number <> 0 Then DisplayError "Deleting database: " Exit Sub End If End If

Next, ADOXCE is used to create the new database \pubs.sdf using a connection string specifying the OLEDB SSCE provider and the name of the le, as follows:
sLocalCon = "Provider=Microsoft.SQLSERVER.OLEDB.CE.1.0;" sLocalCon = sLocalCon & "Data source=\Pubs.SDF" oCatalog.Create sLocalCon ' create the database

This connection string will also be used to specify the database into which RDA will place the pulled tables. When calling RDA you will need to create an object using the progid SSCE.RemoteDataAccess.1.0 and specify the URL to the IIS server, including the virtual directory and name of the ISAPI DLL sscesa10.dll. This is assigned to the InternetURL property. The connection string for the SSCE database is specied in the LocalConnec tionString property:
Set ceRDA = CreateObject("SSCE.RemoteDataAccess.1.0") ' set RDA properties ceRDA.InternetURL = "http://" & sServer & _ "/sscePubs/sscesa10.dll" ceRDA.LocalConnectionString = sLocalCon

The Pull method also needs a connection string for connecting to the SQL Server. This connection string will be used on the IIS server, so you can use (local) for the Data Source (that is, the server name where SQL Server is located). If your SQL Server is on another server, you will need to change this to the name of the server. In this case, the initial catalog is set to the pubs database, and the user id and password are taken from the dialog:
sSvrCon sSvrCon sSvrCon sSvrCon = = = = "Provider=sqloledb;Data Source=(local);" sSvrCon & "Initial Catalog=Pubs" sSvrCon & ";user id=" & sUser sSvrCon & ";password=" & sPassword

04-P1914

8/24/2001

11:26 AM

Page 155

Remote Data Access

155

This code, when executed, results in the following connection string being created:
Provider=sqloledb;Data Source=(local);Initial Catalog=Pubs; user id=sa;password=

It is important that Initial Catalog is used to specify the database being used; otherwise, the default database dened for the SQL Server user will be used (which is master by default). The Pull method is now called and is passed the following parameters:
G G

G G

The name for the new table in the SSCE database, Authors in this case. The SQL statement that provides the recordset for the new table. All columns and all rows are selected. The SQL Server connection string created above. The tracking option for changed data. Tracking is not enabled in this case as the TRACKINGOFF constant is specied:
ceRDA.Pull "Authors", "SELECT * FROM Authors", _ sSvrCon, _ TRACKINGOFF If Err.Number <> 0 Then ReportEngineErrors "Pulling Authors:", ceRDA Exit Sub End If Note that the table being pulled must not exist in the SSCE database. In this case the database has been re-created so the tables cannot exist. In your code you may need to drop tables before pulling them.

As you can imagine, there are many things that can (and often do) go wrong with pulling data; therefore, it is essential to provide good error-checking code. In the above code, the subroutine ReportEngineErrors is called if an error is detected, and this is passed the RDA Engine object. Listing 4.2 shows this subroutineit is located in the module utils.bas.

Listing 4.2

Reporting RDA errors

Public Sub ReportEngineErrors(sMsg, oEngine As SSCE.Engine) Dim oEngErr As SSCEError For Each oEngErr In oEngine.ErrorRecords MsgBox sMsg & vbCrLf & _ "SSCE Error: " & vbCrLf & oEngErr.Description _ & vbCrLf & "Number: " & oEngErr.Number & _ vbCrLf & "Native: " & oEngErr.NativeError

04-P1914

8/24/2001

11:26 AM

Page 156

156
Next End Sub

Chapter 4

SQL Server CE Remote Data Access and Replication

The Engine object has an ErrorRecords collection containing one or more SSCEError objects describing the error. The code in Listing 4.2 iterates through the errors, displaying each in a message box. The Description property does not always describe the error fully, so you should look up the NativeError in the SSCE on-line documentation for more information. Search the help le for Client Agent Errors for a list of error numbers generated by the SSCE Client Agent and Server Agent Errors for error numbers generated by the IIS ISAPI agent. Similar code is executed to pull the Titles and the TitleAuthor tables. Once this has been done, the code in Listing 4.3 is called to add primary and foreign keys between the tables. The techniques used in this code are described in Chapter 3, ADOCE and ADOXCE.
Listing 4.3 Adding indexes and keys

Private Sub AddIndexesEtc(sLocalCon) ' add indexes, primary keys etc for these new tables Dim Dim Dim Dim oT As adoxce.Table o As adoxce.Catalog oK As adoxce.Key oIC As adoxce.Column

Set o = CreateObject("ADOXCE.Catalog.3.1") o.ActiveConnection = sLocalCon On Error Resume Next ' set primary key on au_id for Authors table Set oT = o.Tables("Authors") Set oK = CreateObject("ADOXCE.Key.3.1") oK.Type = adKeyPrimary oK.Name = "pkAuthors" Set oIC = CreateObject("ADOXCE.Column.3.1") oIC.Name = "au_id" oK.Columns.Append oIC oT.Keys.Append oK If Err.Number <> 0 Then DisplayError "Authors PK" End If ' set primary key on title_id for titles table Set oT = o.Tables("Titles") Set oK = CreateObject("ADOXCE.Key.3.1") oK.Type = adKeyPrimary oK.Name = "pkTitles" Set oIC = CreateObject("ADOXCE.Column.3.1")

04-P1914

8/24/2001

11:26 AM

Page 157

Remote Data Access

157

oIC.Name = "title_id" oK.Columns.Append oIC oT.Keys.Append oK If Err.Number <> 0 Then DisplayError "Titles PK" End If ' set primary key on au_id, title_id ' for titleauthor table Set oT = o.Tables("TitleAuthor") Set oK = CreateObject("ADOXCE.Key.3.1") oK.Type = adKeyPrimary oK.Name = "pkTitleAuthor" Set oIC = CreateObject("ADOXCE.Column.3.1") oIC.Name = "au_id" oK.Columns.Append oIC Set oIC = CreateObject("ADOXCE.Column.3.1") oIC.Name = "title_id" oK.Columns.Append oIC oT.Keys.Append oK If Err.Number <> 0 Then DisplayError "TitleAuthor PK" End If ' set foreign key on titleauthor table to authors table Set oK = CreateObject("ADOXCE.Key.3.1") oK.Type = adKeyForeign oK.Name = "fkAuthor" Set oIC = CreateObject("ADOXCE.Column.3.1") oIC.Name = "au_id" oIC.RelatedColumn = "au_id" oK.Columns.Append oIC oK.RelatedTable = "Authors" If Err.Number <> 0 Then DisplayError "Author FK" End If oT.Keys.Append oK ' set foreign key on titleauthor table to titles table Set oK = CreateObject("ADOXCE.Key.3.1") oK.Type = adKeyForeign oK.Name = "fkTitles" Set oIC = CreateObject("ADOXCE.Column.3.1") oIC.Name = "title_id" oIC.RelatedColumn = "title_id" oK.Columns.Append oIC oK.RelatedTable = "Titles" oT.Keys.Append oK Set o = Nothing If Err.Number <> 0 Then DisplayError "Title FK"

04-P1914

8/24/2001

11:26 AM

Page 158

158

Chapter 4

SQL Server CE Remote Data Access and Replication

End If End Sub

You can use this code to test your own RDA installation.
G

G G G

Copy the les from the folder \Examples\PocketPC\RDA from the CDROM into a folder on your PCs hard drive. Use File Explorer to remove the read-only settings on these les. Open the project rda.ebp in eVB. Open the code associated with the form frmRDA.ebf and change the constant denition sMyServer to your own IIS server name or IP address of the IIS server:

Const sMyServer = "190.100.100.120"


G G

G G

Run the application on your Pocket PC. Select the Operations Create Tables menu command to display the Get Server Details dialog. Enter your server name (it does not use the constant sMyServer in this case) and enter a valid SQL login and password. Click OK to download the tables. To conrm that the data has been downloaded, select the Operations Show Authors menu command to list the contents of the Authors table (see Figure 4.14).

Figure 4.14

List of authors from a pulled table

04-P1914

8/24/2001

11:26 AM

Page 159

Remote Data Access

159

SQL PASS-THROUGH The RDA Engine objects SubmitSQL method can be used to execute any SQL statement on an SQL Server providing the SQL statement does not return a recordset. The SQL statement could be an INSERT, DELETE, or UPDATE statement or a stored procedure.
Note that you cannot determine the number of rows affected when using SubmitSQL. Therefore, if you delete a number of rows using a WHERE clause, you cannot determine how many, if any, records were deleted.

When calling the RDA Engine objects SubmitSQL method (see Listing 4.4), you will rst need to specify the URL of the IIS server in the Internet URL property and the SSCE connection string in the LocalConnection String property. The format of the URL and connection string is exactly the same as for the Push method. The SubmitSQL method itself is passed two parameters:
G G

The SQL statement to execute The connection string used by IIS to connect to the SQL Server

As usual, you will need to check for errors, and these can be displayed using the ReportEngineErrors method.
Listing 4.4 Using SubmitSQL

Public Sub RemoteSQL(sServer, sSQL) Dim sLocalCon, sSvrCon Dim ceRDA As SSCE.RemoteDataAccess Set ceRDA = On Error Resume sLocalCon = sLocalCon = CreateObject("SSCE.RemoteDataAccess.1.0") Next "Provider=Microsoft.SQLSERVER.OLEDB.CE.1.0;" sLocalCon & "Data source=\Pubs.SDF"

ceRDA.InternetURL = "http://" & sServer & _ "/sscePubs/sscesa10.dll" ceRDA.LocalConnectionString = sLocalCon sSvrCon = "Provider=sqloledb;DataSource=(local)" sSvrCon = sSvrCon & ";Initial Catalog=Pubs;" sSvrCon = sSvrCon & "Integrated Security=SSPI" ceRDA.SubmitSQL sSQL, sSvrCon If Err.Number <> 0 Then ReportEngineErrors "Adding Author:", ceRDA Exit Sub End If End Sub

04-P1914

8/24/2001

11:26 AM

Page 160

160

Chapter 4

SQL Server CE Remote Data Access and Replication

Figure 4.15

Adding an author using

RemoteSQL

In the project RDA.EBP the function RemoteSQL is used by the form frmAddAuthor.ebf to get details for each of the elds in the Author table, to produce an INSERT SQL statement containing these values, and to send the INSERT statement to the server (see Figure 4.15). The Add Author form is accessed from the main form through the Operations Add Author menu command. The following code is executed when the Add button is clicked in the Add Author dialog:
Private Sub cmdAdd_Click() Dim s s = "INSERT INTO Authors " s = s & "(au_id, au_lname, au_fname, phone," s = s & "address, city, state, zip, contract)" s = s & "VALUES(" s = s & "'" & au_id.Text & "'," s = s & "'" & au_lname.Text & "'," s = s & "'" & au_fname.Text & "'," s = s & "'" & phone.Text & "'," s = s & "'" & address.Text & "'," s = s & "'" & city.Text & "'," s = s & "'" & state.Text & "'," s = s & "'" & zip.Text & "'," If contract.Value Then

04-P1914

8/24/2001

11:26 AM

Page 161

Remote Data Access

161

s = s & "1)" Else s = s & "0)" End If RemoteSQL Me.txtServer, s Me.Hide End Sub

This code generates an SQL INSERT statement such as


INSERT INTO Authors (au_id, au_lname, au_fname, phone,address, city, state, zip, contract) VALUES('999-99-9999','First Name', 'Last Name','408 496 7224', '1500 Bridge Street','Oakland','CA','94026', Remember that this results in a record being added to the Authors table on the SQL Server, not on the local SSCE database. You will not see this new record in your Pocket PC or HPC 2000 application unless you again pull the Authors table from SQL Server. There is no automatic update with RDA.

TRACKING DATA WITH PULL In the Engine objects Push example described earlier in this chapter, the TRACKINGOFF option was used. The SSCE client agent does not track changes made on the Pocket PC or HPC 2000 device, so changes cannot automatically be sent back to the SQL Server. When the TRACKINGON option is used, two new elds are added to the table being pulled, called s_BinaryKey and s_Operation. Values are placed in these elds indicating the type of change operation (such as a record being inserted, deleted, or updated). A table with these two elds can be pushed back to the SQL Server, and the SSCE client agent will only send back to SQL Server those records that have been changed in some way. Of course, it is possible that one particular record may be changed in SSCE and on the SQL Server database between the time the table was pulled and the time it is eventually pushed back to the serverthis creates a conict that must be resolved. When calling the Pull method you can specify the name of a table in the SSCE database that will contain records detailing any conicts that have been detected. In the \Examples\PocketPC\RDA\RDA.ebp project on the CDROM, the Stores table from the Pubs database is used to illustrate using the TRACKINGON option and resolving conicts. The Operations Pull Stores menu command executes the code in Listing 4.5 to pull the Stores table using tracking. The code is located in frmRDA.ebf.

04-P1914

8/24/2001

11:26 AM

Page 162

162

Chapter 4

SQL Server CE Remote Data Access and Replication

This code uses ADOXCE to determine if the Stores table already exists in the database. If it does, the table is deleted. This uses the DoesObject Exist function described in Chapter 3.
Listing 4.5 Pulling Stores table

Public Sub PullStores() Dim ceRDA As SSCE.RemoteDataAccess Dim sLocalCon, sSvrCon Dim oCatalog As adoxce.Catalog On Error Resume Next ' first delete the table if it exists Set oCatalog = CreateObject("ADOXCE.Catalog.3.1") If Err.Number <> 0 Then DisplayError "Creating ADOXCE.Catalog object: " Exit Sub End If sLocalCon = "Provider=Microsoft.SQLSERVER.OLEDB.CE.1.0;" sLocalCon = sLocalCon & "Data source=\Pubs.SDF" oCatalog.ActiveConnection = sLocalCon If DoesObjectExist(oCatalog.Tables, "Stores") Then oCatalog.Tables.Delete ("Stores") If Err.Number <> 0 Then DisplayError "Deleting 'Stores' table: " Exit Sub End If End If Set oCatalog = Nothing Set ceRDA = CreateObject("SSCE.RemoteDataAccess.1.0") ' set RDA properties ceRDA.InternetURL = "http://" & sMyServer & _ "/sscePubs/sscesa10.dll" ceRDA.LocalConnectionString = sLocalCon sSvrCon = "Provider=sqloledb;Data Source=(local)" sSvrCon = sSvrCon & ";Initial Catalog=Pubs;" sSvrCon = sSvrCon & "Integrated Security=SSPI" ceRDA.Pull "Stores", "SELECT * FROM Stores", _ sSvrCon, _ TRACKINGON, "tblError" If Err.Number <> 0 Then ReportEngineErrors "Pulling Stores:", ceRDA Else MsgBox "Stores Pulled"

04-P1914

8/24/2001

11:26 AM

Page 163

Remote Data Access

163

End If End Sub

An RDA Engine object is created as usual, and the InternetURL property is assigned the URL of the SSCE Server agent DLL, sscesa10.dll. Next, the local connection string is assigned to the LocalConnectionString property. Both these two strings are the same as the previous Pull example. The server connection string uses integrated SQL Server security rather than specifying an SQL Server login and password. Because anonymous access is used for IIS, the IUSR_MALAHIDE login will be used to access SQL Server. The connection string will look like the following:
Provider=sqloledb;Data Source=(local); Initial Catalog=Pubs;Integrated Security=SSPI

The call to the Pull method species:


G G

The name of the table to create in the SSCE database, which is Stores. The TRACKINGON optionthis results in the two extra elds being added to the Stores table. The name tblError used for the errors table. This table will automatically be created when a Push is performed.
Note that you should specify a different errors table name (tblError) for each table being pulled. The errors table contains the same elds as the pulled table and is therefore specic to that table.

The Operations Show Stores menu command can be used to display the pulled table and the contents of the s_BinaryKey and s_Operation elds. When rst pulled, the contents of these two elds will always be NULL the values are set as records are changed. CREATING A CONFLICT To illustrate how conicts can be detected, the Operations Create Stores Conict menu in the \Examples\PocketPC\RDA\RDA.ebp project adds a record to the SSCE database table Stores and another record to the SQL Server database table Stores with the same primary key value for stor_id, but different data in the other elds. When the table is nally pushed, the conict will be detected. The code to create the conict is shown in Listing 4.6. Two INSERT statements are created in the strings sSQLLoc (for adding to the SSCE database) and sSQLRem (for adding to the SQL Server database). The local record is inserted using the ADOCEs Execute method through the Connection object. The remote record is inserted using the RemoteSQL method described earlier in this chapter.

04-P1914

8/24/2001

11:26 AM

Page 164

164
Listing 4.6

Chapter 4

SQL Server CE Remote Data Access and Replication

Creating a conict in the Stores table

Public Sub CreateStoresConflict() Dim sSQLLoc, sSQLRem, sLocalCon Dim oLocADO As ADOCE.Connection On Error Resume Next ' create the SQL INSERT statements sSQLLoc = "INSERT INTO Stores (stor_id, stor_name, " sSQLLoc = sSQLLoc & "stor_address, city, state, zip)" sSQLLoc = sSQLLoc & "VALUES ('9999', 'Store 1', " sSQLLoc = sSQLLoc & "'11 High Street', " sSQLLoc = sSQLLoc & "'Portland', 'OR', '89076')" sSQLRem sSQLRem sSQLRem sSQLRem sSQLRem = = = = = "INSERT sSQLRem sSQLRem sSQLRem sSQLRem INTO Stores (stor_id, stor_name, " & "stor_address, city, state, zip)" & "VALUES ('9999', 'Store 2', " & "'1021 Lost Creek', " & "'Fremont', 'CA', '90019')"

' add record locally Set oLocADO = CreateObject("ADOCE.Connection.3.1") If Err.Number <> 0 Then MsgBox "Error Creating ADOCE Object" & _ vbCrLf & Err.Description Exit Sub End If sLocalCon = "Provider=Microsoft.SQLSERVER.OLEDB.CE.1.0;" sLocalCon = sLocalCon & "Data source=\Pubs.SDF" oLocADO.Open sLocalCon If Err.Number <> 0 Then MsgBox "Error opening local database" & _ vbCrLf & Err.Description Exit Sub End If oLocADO.Execute sSQLLoc If Err.Number <> 0 Then MsgBox "Error adding local record" & _ vbCrLf & Err.Description Exit Sub End If oLocADO.Close Set oLocADO = Nothing ' add record remotely Call RemoteSQL(sMyServer, sSQLRem) MsgBox "Conflict Created" End Sub The easiest way to look at and edit records in an SQL Server database is through the Enterprise Manager. Click on Tables in the pubs database

04-P1914

8/24/2001

11:26 AM

Page 165

Remote Data Access

165

in the Tree pane, right-click the table name Stores, and select the Open Table Return All Rows menu command. This displays the records in a table and is editable.

PUSHING A TABLE Changes made locally in the Stores table can be pushed back to the SQL Server using the RDA Engine objects Push method. In Listing 4.7 the Inter netURL and LocalConnection strings are initialized as before. The Push method is passed
G G

The name of the table to push, which is Stores in this case. The connection string used to connect to the SQL Server database. Once again, this uses integrated security.

This code can be executed through the Operations Push Stores menu command in the sample application. Executing this menu command will result in a native error 28544 being generated. This is a clientagent error that the on-line documentation describes as One or more error rows returned from RDA_PUSH; see associated _err table. This results because of the conict created in the previous section.

Listing 4.7

Pushing a table

Public Sub PushStores() Dim ceRDA As SSCE.RemoteDataAccess Dim sLocalCon, sSvrCon On Error Resume Next Set ceRDA = CreateObject("SSCE.RemoteDataAccess.1.0") ' set RDA properties ceRDA.InternetURL = "http://" & sMyServer & _ "/sscePubs/sscesa10.dll" sLocalCon = "Provider=Microsoft.SQLSERVER.OLEDB.CE.1.0;" sLocalCon = sLocalCon & "Data source=\Pubs.SDF" ceRDA.LocalConnectionString = sLocalCon sSvrCon = "Provider=sqloledb;Data Source=(local);" sSvrCon = sSvrCon & "Initial Catalog=Pubs;" sSvrCon = sSvrCon & "Integrated Security=SSPI" ceRDA.Push "Stores", sSvrCon If Err.Number <> 0 Then ReportEngineErrors "Pushing Stores:", ceRDA Exit Sub Else MsgBox "Stores Pushed"

04-P1914

8/24/2001

11:26 AM

Page 166

166

Chapter 4

SQL Server CE Remote Data Access and Replication

End If End Sub

The following happens when a conict is detected:


G G

The offending record is removed from the SSCE Stores table The conicting record on the SQL Server database Stores table is not changedthe SQL Server changes take precedence A record is added to the tblError table describing the conict
Note that a Push does not result in records changed on the SQL Server table being downloaded to the SSCE table. You must perform a Pull again to get changes from the SQL Server table, and to do this you must rst drop the SSCE table. This can make RDA inefcient when pulling large tables.

The contents of the tblError table can be viewed in the sample application by selecting the Operations Show Conicts menu command. The table will contain a single record describing the conict with the following elds:
G G G G

s_errorDate: Date and time of the Push that detected the conict s_OLDEBErr: Database access error causing the conict s_OLDEBErrorString: A string describing the error Fields for each of the elds in the original table Stores containing the

record resulting in the conict The conict in this case results in an error 2627 Violation of PRIMARY KEY constraint UPK_storeid, since the conict created earlier used the same primary key for the local record and the record added to the SQL Server database.

SQL Server CE Relay


Generally, when you have a serial or USB connection to ActiveSync, you cannot connect to other servers on the network using TCP/IP. This means that while you can use RDA when a network or dial-up connection is present, you cannot use RDA with ActiveSync. Release 1.1 of SSCE introduced the SQL Server CE Relay applicationthis acts as a point-to-point proxy between the Pocket PC or HPC 2000 device and the IIS server (see Figure 4.16). By using relay, all connection methods between a Pocket PC and HPC 2000 devices can use RDA. You should note the following limitations in using relay:
G G

Relay must have a connection using ActiveSync 3.1 Relay does not support Secure Socket Layer (SSL) encryption or Integrated Windows authentication

04-P1914

8/24/2001

11:26 AM

Page 167

Remote Data Access

167

Figure 4.16

SQL Server CE relay architecture

CONFIGURING SQL SERVER CE RELAY Before starting to congure SSCE Relay ensure that you have your Pocket PC or HPC 2000 connected to a desktop PC using ActiveSync 3.1 using a serial or USB connection. It is best to start by manually conguring SSCE Relay as it is easy to change parameters without having to reconnect your device to ActiveSync. When you have Relay working, you can then congure Relay to start automatically when an ActiveSync connection is made. Relay acts as a proxy server, so you will need to change your RDA code to use a proxy server. You will need to add the line shown in bold to any code that makes a Push, Pull, or SubmitSQL call through the RDA Engine object:
ceRDA.InternetURL = "http://" & sServer & _ "/sscePubs/sscesa10.dll" ceRDA.LocalConnectionString = sLocalCon ' enable this line if SSCE Relay is used ceRDA.InternetProxyServer = "ppp_ peer:81" sSvrCon = "Provider=sqloledb;DataSource=(local)" sSvrCon = sSvrCon & ";Initial Catalog=Pubs;"

04-P1914

8/24/2001

11:26 AM

Page 168

168

Chapter 4

SQL Server CE Remote Data Access and Replication

sSvrCon = sSvrCon & "Integrated Security=SSPI" ceRDA.SubmitSQL sSQL, sSvrCon

This line species that Relay is being employed (the Relay is a point-topoint peer proxy) using port 81. You can now run the Relay server on your desktop PC. Run a command shell (cmd.exe) and change directory to \Program Files\Microsoft SQL Server CE\Relay and execute the following command:
sscerelay /clientport 81 /servername 190.100.100.120 /serverport 80

This command uses the following parameters:


G

Clientport: Species the port number (81) specied in the Inter netProxyServer property shown in the code above. Servername: Server name or IP address (190.100.100.120) of the IIS

server the RDA application connects to.


G

Serverport: The port number on the server used by IIS. Port 80 is the

default and is the most commonly used number. Sometimes port 8080 is used for security reasons. An icon is added to the tray area on the desktop PC, and the icon animates when transmission takes place. You should now be able to run the RDA application, and tables can be pulled and pushed as before. RDA errors are logged in a le called sscerelay.log in the same directory where sscerelay.exe is located. Once you have relay working you can close down the Relay application and then congure Relay to start automatically when an ActiveSync connection is made. To stop Relay issue the following command in the command shell:
sscerelay /stop

Now issue the following command. This is the same command as used before to start Relay, but with the additional parameter /register.
sscerelay /clientport 81 /servername 190.100.100.120 /serverport 80 /register Note that Relay will not be available until the next time an ActiveSync connection is made and not for the current session after issuing this command.

Relay is automatically started when an ActiveSync connection is made and closed down when the connection is closed. You can unregister Relay by issuing the command
sscerelay /unregister

04-P1914

8/24/2001

11:26 AM

Page 169

SQL Ser ver Replication

169

Security
In the examples shown above, anonymous authentication using the IUSR_ servername user has been used. In many situations you will want to implement NT authentication to secure access to your data. You can do this in IIS by
G

G G

Running the Internet Information Services administration program by selecting the Start Programs Administrative Tools Internet Services Manager or through the Control Panels Administrative Tools icon Expanding out Default Web Site and right-clicking the RDA virtual directory name (e.g., sscePubs) Selecting the Directory Security tab and clicking the Edit button Unchecking Anonymous access and checking Integrated Windows authentication Clicking OK to close the dialogs
Note that you can choose Basic authentication, but this can be insecure as the username and password are not sent in encrypted form.

When Integrated Windows authentication is enabled you will need to supply the Windows username and password through the RDA Engine object. You can use the InternetLogin and InternetPassword properties for this.
ceRDA.InternetLogin = "MyUserName" ceRDA.InternetPassword = "MyPassword"

SQL Server Replication


SSCE can replicate data with SQL Server 2000 using merge replication. SQL Server replication provides a much more sophisticated mechanism for downloading and uploading data than RDA. However, this comes at a cost.
G

G G

Careful planning is required and should involve network administration staff and database administrators. Installation and conguration are more difcult. Merge replication is a large, complex subject and involves a signicant learning curve to gain full advantage of the technology. Merge replication offers the following advantages over RDA:

Replication is two way changes made on the Pocket PC or HPC 2000 device are sent to the SQL Server, and changes made on the SQL Server are sent back to the Pocket PC or HPC 2000 device in a single operation.

04-P1914

8/24/2001

11:26 AM

Page 170

170

Chapter 4

SQL Server CE Remote Data Access and Replication

Conict resolution can be automatic using rules like rst modication wins, or you can write custom conict resolves that run on the server.

With RDA, changes made in the SQL Server are only downloaded when a Pull operation is made, and this involves copying down the entire contents of the table. With merge replication, only the changes are copied down, so this is much more efcient. Further, to perform a two-way transfer of data with RDA you must rst perform a Push, resolve conicts, and then perform a Pull. With merge replication these three tasks are performed by a single synchronization.
Note that SSCE replication only works with SQL Server 2000 using merge replication.

The examples and discussion in this chapter are designed to allow a programmer to setup and explore merge replication with SQL Server 2000. Before attempting to deploy an application that uses merge replication, you will need to carefully plan the topology and security of your solution. This will involve liaising with your network administration staff.
You should ensure that you have RDA working as described in the previous sections of this chapter before attempting to implement merge replication. The examples in the remainder of this chapter assume that IIS and the SSCE server and client agents have been correctly installed. The code examples assume that anonymous login is used to the IIS server.

There are two stages to getting merge replication up and running.


G G

Congure merge replication on the SQL Server. Write code using the Replication object to initialize merge replication on the Pocket PC or HPC 2000 device and then to periodically synchronize the data.

Synchronization of data with SSCE merge replication is not automatic. Your eVB application will need to decide when it is appropriate to synchronize data and then make a connection to SQL Server to perform synchronization. The following terms are used with merge replication:
G

Distributor: A process that manages the distribution of data from a publication to a subscriber. This runs through the SQL Server Agent service. Publication: The denition of data in a database that is available for replication. Subscriber: An application that consumes data from a publication and optionally returns data to the publication.

04-P1914

8/24/2001

11:26 AM

Page 171

SQL Ser ver Replication

171

Articles: The data elements being published in a publication. Although in SQL Server articles can be views, stored procedures, or tables, only tables are used for SSCE replication.

Installation and Conguration


The instructions here show how to setup merge replication for some tables in the pubs database on SQL Server 2000. UPDATING A STORED PROCEDURE Before attempting to use merge replication with SSCE, you will need to update the stored procedure sp_Msmakegeneration in the master database in SQL Server.
This should only be performed on SQL Server if no service packs have been installed. Service packs will automatically update this stored procedure.

To update this stored procedure,


G G G

G G

Run SQL Server Enterprise Manager Select the Tools SQL Query Analyzer menu command Ensure that the master database is selected from the list of databases in the toolbar Select the File Open menu command Select the le \Program files\Microsoft SQL Server CE\Inc
\sp_MSMakeGeneration.sql

Select the Query Execute menu command to execute the script and update the stored procedure

The le sp_MSMakeGeneration.sql is installed as part of a Developer SSCE installation and not part of a Server installation. You will therefore need to nd the le on your development PC. CREATING A SHARE FOR THE PUBLICATION You will need to create a folder and then create a share on the same server as SQL Server. This will be used by publication for storing les associated with replication. The default option is to use the share \\myserver\c$, but you cannot set permissions and security on this share. Therefore, you should create a folder and a share and then congure the correct security on that share.
G G G

Run the File Explorer, and create the folder \PubReplication. Right-click this new folder and select the Properties menu command. Select the Sharing tab.

04-P1914

8/24/2001

11:26 AM

Page 172

172

Chapter 4

SQL Server CE Remote Data Access and Replication

Click the Share this folder option button and ensure that PubRepli cation is entered for the Share Name. Click the Permissions button.

You will need to add the following users to have permissions on this share:
G

Administrator this is the default user for the SQL Agent service, and this user will require full access to the share. IUSR_servername The anonymous IIS user will need read-only access to this share. In this example, it is IUSR_Malahide.

If you are using Windows authentication you will need to add read-only access to the share for any users that participate in replication. You should now set the security for these two users, as follows:
G G

G G

Click the Add button in the Permissions for PubReplication dialog Double-click Administrator from the list of Users, Computers, or Groups and click OK Select Administrator in the list of users, and click the Full Control option button in the Allow column Click the Add button again Double-click IUSR_servername in this example the user is IUSR_ Malahide, from the list of Users, Computers, or Groups, and click OK Select IUSR_servername in the list of users, and click the Read option button in the Allow column Click OK to close the dialogs The Create Publication Wizard in the next section will use this share.

SET TING UP A PUBLICATION A publication denes the data that can be replicated. The easiest way of creating a publication is to use the Create Publication Wizard from the SQL Server Enterprise Manager.
G

Run the SQL Server Enterprise Manager by selecting the Start Programs Microsoft SQL Server Enterprise Manager menu command. Expand the Microsoft SQL Servers tree list in the left pane to show your server (Malahide in this case), and Databases to show the list of databases. Right-click the pubs database and select the New Publication menu command.

This starts the Create Publication Wizard. The steps in this wizard depend on whether a publication has been created already on this server. If a publication has not been created the wizard will take you through the details

04-P1914

8/24/2001

11:26 AM

Page 173

SQL Ser ver Replication

173

Figure 4.17

Create Publication WizardSelect Distributor

of the Distributor to use for the publication. The Distributor can be the SQL Server supporting the publication or another SQL Server. In this case, the steps assume that a Distributor is yet to be dened for the SQL Server and that the SQL Server itself will act as the Distributor.
G G

Click Next to skip the initial, opening sheet for the wizard. In the Select Distributor sheet select the rst option Make Malahide its own Distributor; SQL Server will create a distribution database and log (see Figure 4.17). Click Next.

Publication uses the SQL Server Agent to generate information relating to replication. By default, the agent is not started automatically. The Congure SQL Server Agent sheet allows you to congure the SQL Server Agent to run automatically when the computer is started.
G

Select Yes, Congure the SQL Server Agent service to start automatically and click Next.

04-P1914

8/24/2001

11:26 AM

Page 174

174

Chapter 4

SQL Server CE Remote Data Access and Replication

Figure 4.18

Create Publication WizardSpecify Snapshot Folder

The next page, Specify Snapshot Folder, is used to specify the name of the share that replication will use for holding snapshot and other information. In this example, you will use the share created in the previous section. Note that you should use a share and not a folder on a local drive.
G

Enter \\server\PubReplication for the Snapshot folder and click Next (see Figure 4.18). In this example, \\Malahide\PubReplica tion is used.

The next sheet, Choose Publication Database, lists all the databases on the SQL Server and allows you to select the database to publish. In this case you will be publishing the pubs database.
G

Select pubs from the list of databases and click Next.

There are three types of publication supported by SQL Server (Snapshot, Transactional, and Merge), but only Merge is supported by SSCE.
G

Select Merge Publication from the list of publication types in the Select Publication Type sheet, and click Next (see Figure 4.19).

04-P1914

8/24/2001

11:26 AM

Page 175

SQL Ser ver Replication

175

Figure 4.19

Create Publication WizardSelect Publication Type

The Specify Subscriber Types sheet allows you to select one or more types of subscriber. You must select at least Devices running SQL Server CE when using replication with SSCE.
G

Select Devices running SQL Server CE from the list of subscriber types, and any other subscriber types you want to test with. Click Next.

The next sheet, Specify Articles, allows you to specify the tables that will be published through the publication. While SQL Server supports tables, stored procedures, and views as articles, you should only use tables for SSCE replication. You need to carefully dene the set of tables to use, because you can end up limiting the ability to add new records to replicated tables. For example, if you set table A as an article, and table B has a foreign key relationship with the primary key in A but is not specied as an article, then you will not be able to add records to table A in the SSCE database. Of course, the more tables you specify as articles, the slower replication will be. You need to plan carefully the data that needs to be updated in the SSCE database and specify articles accordingly.

04-P1914

8/24/2001

11:26 AM

Page 176

176

Chapter 4

SQL Server CE Remote Data Access and Replication

Figure 4.20

Create Publication WizardSpecify Articles

Select the following tables in the object list: authors, publishers, roysched, sales, titles, titleauthor (see Figure 4.20) and click Next.

To enable merge replication, SQL Server needs to add a uniqueidentifier column with a unique index and the attribute ROWGUIDCOL to each table that does not already have such a column. The Article Issues sheet requests you to conrm this database change.
G

Select Next to conrm these database changes in the Article Issues sheet.

Each publication will need a name through which it is accessed. In this case you will set the name to pubs, that is, the same as the database name. You can also specify a description for the publication in this sheet. Note that you can have several different publications on the same databasethis can be useful when you have groups of users with different replication requirements.

04-P1914

8/24/2001

11:26 AM

Page 177

SQL Ser ver Replication

177

Leave the Publication Name with its default name pubs and click Next.

The last sheet, Customize the Properties of the Publication, allows you to change the default settings created by the wizard and to specify advanced features. In this case, the publication will be created with the default settings.
G

Click the Next button in the Customize the properties of the Publication sheet and then click Finish.

This completes the setting up of the Distributor and the Publication for the pubs database. CONFIGURING THE PUBLICATION ACCESS LIST Access to the publication is controlled separately from access control to the database being published. The Publication Access List species the users who can access the publication. You will need to add the IIS anonymous user to the Publication Access List for the pubs publication.
G

G G G

In the SQL Enterprise Manager, expand out the pubs database, and expand out the Publications entry under the pubs database. Right-click pubs in the Publications List and select the Properties menu command. Select the Publication Access List tab. Click the Add button to add a user to the Publication Access List. Select the servername\IUSR_servername user from the list (e.g., MALAHIDE\IUSR_MALAHIDE) and click OK.

This adds the anonymous user to the Publication Access List (see Figure 4.21).

Programming Replication
Replication is programmed through the SSCE.Replication objects methods and properties. This object is created using the progid SSCE.Replication.1.0. A reference to the library Microsoft SQL Server Control 1.0 should be added to the project using the eVB Project Add References menu command. All the code shown in this section can be found in the project \Examples\PocketPC\Replication\Replication.ebp or \Examples \HPC2000\Replication\Replication.ebp on the CDROM. The code to use replication is the same for Pocket PC and HPC 2000. All the code in this application is located in frmReplication.ebf.
You should ensure that the SQL Server Agent service is running before attempting to use merge replication.

04-P1914

8/24/2001

11:26 AM

Page 178

178

Chapter 4

SQL Server CE Remote Data Access and Replication

Figure 4.21

Conguring the publication access list

The following stages are used for programming replication:


G

Initialize: Used to create an SSCE database and initialize a subscription to a publication. Synchronize: Connects to the publication and downloads/uploads data changes. This is called periodically by an application to keep data changes up to date. Reinitialize: Used to reinitialize a subscription when changes are made to the articles on the SQL Server. Drop: Used to remove a subscription to a publication and optionally delete the database.

04-P1914

8/24/2001

11:26 AM

Page 179

SQL Ser ver Replication

179

INITIALIZING A SUBSCRIPTION Initializing a subscription involves setting replication properties to specify details on the publication and to create a local database to store the SSCE copies of the articles. Listing 4.8 shows the function ConfigureReplicationOb ject. This creates a Replication object and sets the necessary properties to specify the publication to subscribe to.
Listing 4.8 Setting Replication Properties

Private Sub ConfigureReplicationObject(oRep _ As SSCE.Replication, sServer) Set oRep = CreateObject("SSCE.Replication.1.0") oRep.InternetURL = "http://" & _ sServer & "/sscepubs/sscesa10.dll" ' TODO: Change this to the name of ' your Publication server ' This will probably be the same as your SQL ' Server you are connecting to oRep.Publisher = "MALAHIDE" oRep.PublisherDatabase = "pubs" oRep.Publication = "pubs" oRep.PublisherSecurityMode = NT_AUTHENTICATION ' Use these properties for non-NT Authentication ' access 'oRep.PublisherLogin = "sa" 'oRep.PublisherPassword = "" oRep.SubscriberConnectionString = _ "data source=\PubsRepl.sdf" oRep.Subscriber = "Pubs #1" End Sub

The properties used in Listing 4.8 are


G

InternetURL: The URL of the IIS server, virtual directory, and sscesa10.dll used for replication. Publisher: The Publisher SQL Server name. In many cases this will be the same name as the SQL Server containing the published database. This should be a server name and not an IP address. PublisherDatabase: The name of the SQL Server database being published. Publication: The name of the publication. In this case the Pub lisherDatabase and Publication are the same, but there could be

04-P1914

8/24/2001

11:26 AM

Page 180

180

Chapter 4

SQL Server CE Remote Data Access and Replication

G G G

several different publications (e.g., pubs1 or pubs2) on the same publisher database (e.g., pubs). PublisherSecurityMode: Species the type of login access to the SQL Server. The default is DB_AUTHENTICATION, which species that an SQL Server login/password will be supplied using the PublisherLogin and PublisherPassword properties. NT_AUTHENTICATION species trusted security, and a login and password do not need to be specied. PublisherLogin: An SQL Server login for DB_AUTHENTICATION. PublisherPassword: A password for DB_AUTHENTICATION. SubscriberConnectionString: The connection string specifying the local SSCE database used for the subscription. Note that you do not need to specify a provider because SSCE is assumed. Subscriber: The name by which the subscriber will be known by the publisher.

The function CreateSubscription (see Listing 4.9) checks if subscription database \PubsRepl.sdf exists, and if it does, deletes it. The function CreateSubscription then calls ConfigureReplicationObject to initialize the properties in the Replication object. Once this is done, the Replication methods Initialize, Run, and Terminate are called, and then the contents of the Authors table are displayed in a grid. This subscribes to the publication and then performs a merge replication resulting in the data in the articles being downloaded to the SSCE database. The function Create Subscription is called through the Subscription Create menu command.
Listing 4.9 Creating a subscription

Private Sub CreateSubscription(sServer) Dim oRep As SSCE.Replication Call ConfigureReplicationObject(oRep, sServer) On Error Resume Next If FileSystem1.Dir("\PubsRepl.sdf") <> "" Then FileSystem1.Kill "\PubsRepl.sdf" If Err.Number <> 0 Then DisplayError "Deleting database: " Exit Sub End If End If oRep.AddSubscription CREATE_DATABASE If Err.Number <> 0 Then Call ReportEngineErrors("AddSubscription:", oRep) Exit Sub End If oRep.Initialize

04-P1914

8/24/2001

11:26 AM

Page 181

SQL Ser ver Replication

181

If Err.Number <> 0 Then Call ReportEngineErrors("Initialize:", oRep) Exit Sub End If oRep.Run If Err.Number <> 0 Then Call ReportEngineErrors("Run:", oRep) Else oRep.Terminate Call ShowAuthors MsgBox "Initialized" End If End Sub

The following Replication object methods are used in Listing 4.9:


G

G G

AddSubscription: Adds a new anonymous subscription to an SQL Server publication. The CREATE_DATABASE option causes the method to create the SSCE database, while the option EXISTING_DATABASE assumes that the SSCE database already exists. Initialize: Prepares the Replication object for synchronization. Run: Invokes the merge replication, resulting in a two-way transfer of data. Terminate: Completes the merge replication process.

The function CreateSubscription uses the method ReportEngine Errorsthis is the same function used in the RDA examples for reporting errors. Creating the subscription adds three elds to the Authors table in the SSCE database: Rowguid, S_generation, and S_rowlineage. The code to display the Authors table species a list of elds to display in the SELECT statement rather than * to avoid displaying these eldsthey are binary and cannot be displayed in a grid. SYNCHRONIZING A SUBSCRIPTION The Pocket PC or HPC 2000 application is responsible for connecting to the SQL Server distributor and synchronizing the replication on a regular basis. This could be whenever the user dials into a network using RAS (Remote Access Server) or on a periodic basis for devices that are permanently connected to the network. The code in Listing 4.10 calls the Replication objects Ini tialize, Run, and Terminate methods to perform synchronizationthese are the same calls made in Listing 4.9.
Listing 4.10 Synchronizing replication

Private Sub Synchronize(sServer) Dim oRep As SSCE.Replication

04-P1914

8/24/2001

11:26 AM

Page 182

182

Chapter 4

SQL Server CE Remote Data Access and Replication

Call ConfigureReplicationObject(oRep, sServer) On Error Resume Next oRep.Initialize If Err.Number <> 0 Then Call ReportEngineErrors("Initialize:", oRep) Exit Sub End If oRep.Run If Err.Number <> 0 Then Call ReportEngineErrors("Run:", oRep) Else oRep.Terminate Call ShowAuthors MsgBox "Synchronized" End If End Sub

The Subscription Synchronize menu in the sample application synchronizes the subscription and redisplays the list of authors. Changes made in the SSCE copy of the Authors table will be copied up to the SQL Server copy, and changes made in the SQL Server copy of the Authors table will be copied down on the SSCE database. Note that this is two-way replication, whereas RDA only sends changes made on the SSCE table up to SQL Server. The entire contents of the table must be copied down from the SQL Server table using a Pull. The PublisherChanges property contains the count of the total number of publisher changes applied to the subscriber after synchronization takes place. Likewise, the SubscriberChanges property returns the number of changes made at the publisher by the subscriber. REINITIALIZING A SYNCHRONIZATION You can reinitialize a subscription through the Replication objects Reini tialization method. This marks the subscription as requiring a refresh, and the next time the Initialize, Run, and Terminate methods are called, the subscription information will be downloaded again from the SQL Server publication. This might need to be done if the articles in the publication have been changed and the changed articles need to be used in the SSCE database. DROPPING A SYNCHRONIZATION An SSCE application can remove itself from the list of anonymous subscribers to an SQL Server publication by calling the Replication objects DropSub scription method (see Listing 4.11). Note that the only Replication property that needs to be assigned a value is SubscriberConnectionString. The DropSubscription method can be passed the DROP_DATABASE constant to request that the SSCE database be deleted. The option LEAVE_DATA

04-P1914

8/24/2001

11:26 AM

Page 183

SQL Ser ver Replication

183

BASE will leave the database in place after the call is made. The Synchronize

Drop menu command will drop the subscription in the sample application.

Listing 4.11

Dropping a replication

Private Sub DropSubscription(gc_Server) Dim oRep As SSCE.Replication Set oRep = CreateObject("SSCE.Replication.1.0") On Error Resume Next oRep.SubscriberConnectionString = _ "data source=\PubsRepl.sdf" oRep.DropSubscription DROP_DATABASE If Err.Number <> 0 Then Call ReportEngineErrors("Drop:", oRep) Else MsgBox "Subscription dropped" End If End Sub

Dealing with Conicts


A conict resolver running on SQL Server always resolves replication conicts. Conicts are not resolved on the Pocket PC or HPC 2000 device. SSCE replication always uses row-level conict detection, regardless of how conict detection is congured in the publication. This means that if column A in a row is changed in the SSCE database and column B is changed in the SQL Server database on the same row, then this is considered a conict. The default resolution is to give precedence to the data rst saved in the SQL Server database. The Subscription Create Conict menu command in the sample application creates a conict by adding a record to the Authors table in the SSCE database and the SQL Server database with the same au_id primary key value. The record is added using the RDAs SubmitSQL method, showing that you can use replication and RDA in the same application. The code to create this conict uses two INSERT statements and is included in the subroutine CreateAuthorConflict. The conict will be detected and resolved the next time the Subscription Synchronize menu command is used. Since precedence is given to the rst data change made to the SQL Server, the record added to the SQL Server database through RDA will be kept, and the record added to the SSCE database will be discarded. Note that the record in the SSCE database is only considered added to the database when synchronization takes place, and not when the record was added to the SSCE database. At the end of synchronization, both the SSCE and SQL Server databases will

04-P1914

8/24/2001

11:26 AM

Page 184

184

Chapter 4

SQL Server CE Remote Data Access and Replication

contain the record originally added to the SQL Server database through RDA, and the record added to the SSCE database will have been deleted. You can determine the number of conicts detected using the Replica tion objects PublisherConflicts property. This property will contain the value 1 when synchronizing after the conict has been created. In the following code fragment, the MsgBox in the function Synchronize has been changed to display the number of conicts:
oRep.Terminate Call ShowAuthors MsgBox "Synchronized with " & oRep.PublisherConflicts _ & " conflict detected" Note that there is a SubscriberConflicts property, but this will always return the value 0 SSCE never resolves conicts.

You can customize conict resolution, perhaps to change the resolution rules, or to return information about the conict to the client. To do this, you need to write and install an SQL Server conict resolver, a topic that is outside the scope of this book.

Conclusion
This chapter has shown two techniques for keeping data synchronized between SSCE and SQL Server database. Remote Data Access (RDA) can be used when
G

G G

Data is infrequently sent from SQL Server to SSCE, or the amounts of data are small Where SQL Server 6.5 or 7.0 databases are used Where system administrators do not want to implement replication on an SQL Server 2000 installation SQL Server 2000 merge replication can be used when

G G

Frequent two-way synchronization of data is required Customized conict resolution is required

With either RDA or replication, it is important that you carefully plan and test your data transfer strategy. Most important, you should test the time taken to synchronize data using the connection technique (e.g., serial, USB, or wireless) employed by your usersthis may be a lot slower than your network connection.

Potrebbero piacerti anche