Cluj München 1140km

Gânduri clujene din Bavaria

München - Munich - Monaco di Baviera

1. iulie 2009 14:08
by skorpionking
0 Comentarii

.NET 60 seconds code : using ADO.NET Synchronization Services 1.0

1. iulie 2009 14:08 by skorpionking | 0 Comentarii

The online/offline scenarios are a piece of cake right now thanks to the Microsoft ADO.NET Synchronization Services and SQL Server Compact Edition. Also SQL 2008 Server Express Edition can be used for these scenarios instead of SQL Server Compact Edition.

All you have to do is to download the framework (samples are available here) and open Visual Studio, create a windows application and now, let's add a new item to the project, "Local Data Cache".

What this is going to do is create a local SQL CE database that will be used by the client application, and we will eventually write the code to sync up this database with our master database, for selected tables. The best part of the Sync framework is its support for Visual Studio 2008. It provides a nice wizard for the whole set up, making our life a lot easier.

As soon as you click the "Add" button, the next screen pops up, which will be used to set up your local cached database. On the screen, select "Server Connection". Now, if you have previously used the Windows Forms application, you may already have a SQL connection setup, like in my case; otherwise, click the New button and create the connection string for your master SQL Server. For this example, I will use our favorite "Northwind"  database. Now that you have given your server connection information, the wizard creates a client connection. This is nothing but a new SQL CE database that you have just created. Also, now that the wizard is aware of the server database, it will allow you to add the tables to be cached. Click the "Add" button on the left bottom of the screen.

Select the tables that you would like to cache on the client side. Now, remember, you do not want to select all the tables as it's not practical to cache the whole master database on the client machine, as usually, the client machines in such cases as laptops, tablets, and PDAs may not have enough storage. In the above scenario, I have selected three tables. On the right side of the screen, you will get some more setting options. In most cases, you would like to keep them to the default settings.

The first option asks you what data you want to download. new and incremental changes are done only after the first synchronization. Also, the sync framework is going to add two new columns to your tables to keep track of the last update and new inserts. You can choose existing columns if you are already tracking it. Also, it will create a history table named TABLENAME_Tombstone. This is used to keep track of deleted rows. With SQL Server 2008, you would not need either of them, as SQL Server has standard change tracking. So, with SQL Server 2008, it will not add any additional columns or a tombstone table.

Select "OK", and "OK" on the first wizard screen. This will create a local cached database with the tables you selected. On the first wizard screen, you also have options to select the server and the client project location. In an N tier application, you can select your server and client application to be different. You can optionally select to create synchronization components for the client only or the server only. By default, it's the client and the server.

After hitting OK on this screen, the wizard will create a local database (.sdf); in our case, it created Northwind.sdf. It will then ask you to select tables to be added to your dataset. This will allow easy creation of the grid on the form with a typed dataset.

You can open the dataset and add some more tables from the Server Explorer, but those tables will not be cached on the client machine. They will be available to use in the application, but the application will go back to the server each time those tables are accessed. Now, go back to your form and open your data sources (show the data sources under the Data menu). Select the Customers table and select the DataGridView, and drag the table on the form. This should add the GridView to the form with all the navigation controls. I really like this part of the design, just drag and drop and you are ready to go.

In order to activate the sync process, we will add the button to the grid's tab strip. Usually, you will have a service running in the background that will check for network availability, and if its available, it will initiate the sync process. We will try to keep it simple, and will call the sync process on the click of a button.

Double click the button, and add the code to sync the databases. Now, it's just three lines of code, and out of those, two lines have been provided right in the wizard.

Me.NorthwindDataSet.Employee.Merge(CustomersTableAdapter.GetData())

And that's it, your first occasionally connected WinForms application is ready to run. Browse through the data on the client side. Now, make some changes to the data on the server. The data on the client is still old as we have not initiated the sync process. Click the Sync button and your client gets updated with new data. Now, try changing the data on the client and see if it is reflected on the server. It wont as, by default, the sync works unidirectional. But again, they have made it real easy to change it to bidirectional. All you have to do is right click LocalDataCache1.sync, and select View Code. You will see the SyncAgent class; just add the following code:

Partial Public Class LocalDataCache1SyncAgent
    Private Sub OnInitialized()
        Me.Customers.SyncDirection = _
           Microsoft.Synchronization.Data.SyncDirection.Bidirectional
    End Sub
End Class

And now, your application should sync up in both directions. Try changing some data on the client side, click the "Save" button on the tool bar, and then click the Sync button. Data on the server should reflect the changes done on the client side; but wait, have we got us in trouble by allowing bidirectional sync? What happens if both the client and the server update the same record, how will it work? Again, the framework at your rescue. All such conflicts raise an ApplyChangesFailed event for the server sync provider, which you can do by implementing a partial class for your server sync provider. Below is a sample of how to do it.

By default, the changes from the server are overwritten on the client. You can change that logic to say that in the case of ApplyChangesFailed, force changes from the client to be over written to the server.

Partial Class LocalDataCache1ServerSyncProvider

    Private Sub LocalDataCache1ServerSyncProvider_ApplyChangeFailed _
            (ByVal sender As Object, _
            ByVal e As Microsoft.Synchronization.Data.ApplyChangeFailedEventArgs) _
            Handles Me.ApplyChangeFailed
        e.Action = Microsoft.Synchronization.Data.ApplyAction.RetryWithForceWrite
    End Sub
End Class

In this case the changes from client are always written to the server. Again this may not be a practical solution as in most case you may want to do some kind of validations before accepting either client or server changes. And the best part is that even that's easy to implement. All you do is take the client changes and server changes and apply your business rule.

Private Sub LocalDataCache1ServerSyncProvider_ApplyChangeFailed _
        (ByVal sender As Object, _
        ByVal e As Microsoft.Synchronization.Data.ApplyChangeFailedEventArgs) _
        Handles Me.ApplyChangeFailed

    Dim clientChanges As DataTable = e.Conflict.ClientChange
    Dim serverChanges As DataTable = e.Conflict.ServerChange

    If (clientChanges.Rows(0)("ModifiedDate") > _
              serverChanges.Rows(0)("ModifiedDate") Then
        e.Action = _
          Microsoft.Synchronization.Data.ApplyAction.RetryWithForceWrite
    End If
End Sub

The complete code, in C#, a bit modified (with BackgroundWorker) can be downloaded from here: NorthwindSync.zip (92,70 kb)

Happy programming :-)

Adaugă comentariu

biuquote
Loading