Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » ADO.NET & Database » Introduction to ADO .Net Sync Services

Introduction to ADO .Net Sync Services

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. The 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 you can use Sync services within your application.

Page Views : 13135
Downloads : 275
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
SyncServices2Tier_src.zip
 
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Introduction

The 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.

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.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Vishal Shukla
Vishal has over 11 years of IT experience with over 10 years on Microsoft technologies from vb 3.0 to .net 3.5. Vishal works as a System Architect for the Palm Beach County. He has been actively involved with local user group community. He has given various presentaions at code camps, Teched Tweener and various user group events.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Mindcracker MVP Summit 2012
Become a Sponsor
 Comments
Mindcracker MVP Summit 2012
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.