Geeks With Blogs
Vishal Shukla

Introduction

This blog entry which is more like an article, will demonstrate how easily you can design occasionally connected applications using ADO .Net Sync services. It’s going to be a very basic example in VB .net showing how easily you can use Sync services within your application. I have taken the template from code project and will try to upload it there as well. I am also uploading my presentation in case anyone needs it.

Presentation and Source code

Background

At our organization we have designed an application for the Fire Rescue chiefs who are usually on unit and want the ability to access the application using their laptops and even PDAs. They use Verizon cards for broadband access and it works well for most part, but once in a while they lose the connection and the application dies. The ability to support mobile and remote workers is becoming more and more important for organizations. The Microsoft Sync framework has been designed to address these issues and gives a great framework to easily design your applications on occasionally connected architecture. For this article I will use the VB .net as sample as there are very few VB .net examples on the net.

Using the Code

I have uploaded the complete source code for the project, at the same time I will go through setting up on your front step by step. Hopefully in a process I’ll be able to explain the process in detail.

First you’ll have to download the Sync framework from Microsoft site. The V1 is available for download at

http://msdn.microsoft.com/en-us/sync/default.aspx

Once the framework has been installed, start visual studio 2008 and create new Windows Form application.

Now let’s add new item to the project “Local Data Cache”

NewLocalDataCache

What this is going to do is create 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 it’s support for studio 2008. It provides nice wizard for the whole set up making our life lot easier.

As soon as you click “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 form application you may already have 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 “Adventure Works” database. This is how the second screen looks ;

NewLocalDataCache2

Now that you have given your server connection information, the wizard creates client connection. This is nothing but the new SQL CE database that you just created. Also now that the wizard is aware of the server database it will allow you to add the tables to be cache. Click the “Add” button on the left bottom of the screen. Once you hit the “Add” button following screen appears.

SelectTables

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 laptops, tablets, PDA may not have enough storage. In the above scenario I have selected 3 of the tables. On the right side of screen you will get some more setting options. In most cases you would like to keep them to default settings.

The first option asks you what data you want to download; New and incremental changes only after first synchronization or Entire table each time. Also the sync framework is going to add 2 new columns to your tables to keep track of last update and new inserts. You can choose existing columns if you are already tracking it. Also it will create a history table named as 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 tombstone table.

Select “OK”, and “OK” on the first wizard screen this will create the local cached database with the tables you selected. On the first wizard screen you also have options to select the server and client project location. In this scenario both will be our current project. In my next article I will try to cover a 3 tier example using WCF services. And in N tier application you can select your server and client application to be different. You can optionally select to create synchronization components for client only or server only. By default it’s client and server.

After hitting ok on this screen it the wizard will create local database (.sdf) in our case it created AdventureWorks.sdf. It will then prompt you with following screen allowing you to select tables to be added to your dataset. This will allow easy creation of grid on the form with typed dataset.

ChooseDatabaseObjects

As you can notice I have selected all the 3 tables. After clicking Finish it will create dataset for the project. You can open the dataset and add some more tables from the server explorer, but those tables will not be cached on client machine. They will be available to use in the application but the application will go back to server each time those tables are accessed. For this demo we’ll keep it simple and not add any more tables, as the main purpose of demo is to see the sync framework in action. Now go back to your form and open your data sources (show data sources under data menu). Select Employee table and select Data grid view, and drag the table on form. This should add the gridview to the form with all the navigation controls. I really like this part of design, just drag and drop and you are ready to go.

Now comes the main part, in order to activate the sync process we will add the button to 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. Again for this demo will try to keep it simple and will call the sync process on click of a button.

CreateForm2

Double click the button and add the code to sync the databases. Now it’s just 3 lines of code and out of those 2 lines have been provided right in the wizard. Click the LocalDataCache1.sync and you will notice that on the right bottom corner is “Show Code Example”, click that copy the code and cut paste it in the event handler for button click.

Now just add code to merge the changes to client table using;

Me.AdventureWorksDataSet.Employee.Merge(EmployeeTableAdapter.GetData())

And that’s it, your first occasionally connected win form application is ready to run. Browse through the data on client side, now make some changes to the data on server. The data on client is still old as we have not initiated sync process, click the sync button and your client gets updated with new data. Now try changing data on client and see if it is reflected on 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 the LocalDataCache1.sync and say view code. You will see SyncAgent class, just add following code;

Partial Public Class LocalDataCache1SyncAgent Private Sub OnInitialized() Me.Employee.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 client side, click the “save” button on tool bar and then click the sync button. Data on server should reflect the changes done on client side, but wait have we got us in trouble by allowing bidirectional sync? What happens if both client and server update the same record, how will it work? Again the framework at your rescue, all such conflicts raise ApplyChangesFailed event for server sync provider which you can implement by implementing partial class for your server sync provider. Below is the sample on how to do it.

By default the changes from server are overwritten on client, you can change that logic to say that in case of ApplyChageFailed force changes from client to be over written to 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.

Partial Class LocalDataCache1ServerSyncProvider
    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
End Class

Here we are checking the date modified on server and date modified on client, and if the date modified on client is later we are forcefully updating server with client changes otherwise do nothing. You can apply any business logic here and in fact you can use ApplyingChanges event and modified the data before it is updated, this could be useful in cases where you want to update the values based on some calculation e. g. in case of inventory you may want to update both server and client with addition of values from server and client updates.

Points of Interest

This is a real simple example and in real world you may have lot more complex scenario’s to implement, but the purpose of the article is to show how easy it is to sync framework to design occasionally connected smart client applications.

Posted on Wednesday, September 17, 2008 4:14 AM vb .net | Back to top


Comments on this post: Introduction to ADO .Net Sync Services

# re: Introduction to ADO .Net Sync Services
Requesting Gravatar...
thanks for this clear & easy to understand article. very helpful.
Left by steve on Dec 29, 2009 12:36 PM

# re: Introduction to ADO .Net Sync Services
Requesting Gravatar...
thanks Casino. You can look at the follow up article at CodeProject
http://www.codeproject.com/script/Articles/MemberArticles.aspx?amid=2259395
Left by Vishal Shukla on Oct 07, 2010 12:21 AM

# re: Introduction to ADO .Net Sync Services
Requesting Gravatar...
This lecture is fine but what if in my case you have about a hundred forms and more than 50 tables
Left by tendai mare on Dec 15, 2010 9:04 AM

Your comment:
 (will show your gravatar)


Copyright © Vishal | Powered by: GeeksWithBlogs.net