Blue Theme Orange Theme Green Theme Red Theme
 
ANTS Performance Profiler 6.0
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
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.

Total page views :  9686
Total downloads :  206
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
SyncServices2Tier_src.zip
 
Become a Sponsor

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.


Login to add your contents and source code to 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.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.