ptg 1814 CHAPTER 45 SQL Server and the .NET Framework new AdventureWorks2008Entities(_svcUri); ProductReview P = NewContext.ProductReview.Where ( p => p.ProductReviewID == ProductReviewId ).FirstOrDefault(); if (P != null) { string OldComments = P.Comments; P.Comments = NewComments; NewContext.UpdateObject(P); NewContext.SaveChanges(); Debug.WriteLine(string.Format(“Success! Updated comments to {0}” , P.Comments)); //put old comments back: P.Comments = OldComments; NewContext.UpdateObject(P); NewContext.SaveChanges(); } return P; } Notice the use of the NewContext object. It is of type AdventureWorks2008Entities, a DataServiceContext derivative that was generated when you added your service reference. You must use this class, rather than the original _ctx object, to perform any CRUD query other than a retrieval. Walking through the code in Listing 45.9, you first select your desired ProductReview entity and then update its Comments property. Then you call UpdateObject and SaveChanges to commit your changes to the database through your service. Next up, Listing 45.10 illustrates how to perform an insert of a new ProductReview (related to an existing Product) using ADODS. Under the hood, it uses the HTTP POST verb to accomplish its goal. In this example, you first fetch your Product (to which you associ- ate your new ProductReview), then set the properties of your ProductReview, add that new object ( PR) to the current list (via NewContext.AddToProductReview), set the Product property on PR, and then call SetLink to tell your context that you have made this associ- ation. Finally, you call SaveChanges to commit your work. ptg 1815 Using ADO.NET Data Services 45 LISTING 45.10 An Insert Query Using the ADO.NET Data Services Client Library public ProductReview AddProductReview(int ToProductId, string Comments) { AdventureWorks2008Entities NewContext = new AdventureWorks2008Entities(_svcUri); Product P = ( from p in NewContext.Product where p.ProductID == ToProductId select p ).FirstOrDefault(); ProductReview PR = null; if (P != null) { PR = new ProductReview() { Comments = Comments, EmailAddress = “alex@unifieddigital.com”, Rating = 4, ReviewDate = DateTime.Now, ModifiedDate = DateTime.Now, ReviewerName = “Alex T. Silverstein” }; NewContext.AddToProductReview(PR); PR.Product = P; NewContext.SetLink(PR, “Product”, P); NewContext.SaveChanges(); Debug.WriteLine(string.Format(“Success! Added new review {0}”, PR.ProductReviewID)); } return PR; } To round things out, in this final example, Listing 45.11 illustrates how to perform a delete using ADODS. Its syntax is straightforward and simple. All that is needed is to fetch the object to be deleted and then call DeleteObject on your context and then ptg 1816 CHAPTER 45 SQL Server and the .NET Framework SaveChanges. Note that in this final example, the URI for your deletion is http://server:port/AW08Service.svc/ProductReview(11), no payload is sent to the server, and your HTTP verb is DELETE. LISTING 45.11 A Delete Query Using the ADO.NET Data Services Client Library public void DeleteProductReview(int ProductReviewId) { AdventureWorks2008Entities NewContext = new AdventureWorks2008Entities(_svcUri); ProductReview PR = ( from p in NewContext.ProductReview where p.ProductReviewID == ProductReviewId select p ).FirstOrDefault(); if (PR != null) { NewContext.DeleteObject(PR); NewContext.SaveChanges(); } } Although you’ve learned quite a bit about ADODS in this short space, we encourage you to continue exploring this exciting new framework on your own, using Fiddler to examine the HTTP traffic in detail. For now, it’s time to switch gears to a new topic. Leveraging the Microsoft Sync Framework Microsoft Sync Framework (MSF) is a complete platform enabling synchronization of data, files, feeds, or other critical information between clients, peers, and servers over common transport protocols and across networks. It provides the necessary interfaces, assemblies, code-generation tools, script wizards, and other components that make it easy for develop- ers to begin using it. The main use case for MSF we cover in this chapter is that of the Occasionally Connected Application (OCA). OCA is a descriptive term for a program that relies on data on a regular basis, yet which is not permanently connected to the Internet. If your target users are stuck with a slow, unreliable, or occasionally unavailable network provider, they are the perfect targets candidate for building an OCA. OCAs include phone, PDA, tablet, or other portable device applications, such as those needed by a mobile salesperson, floor manager, insurance adjuster, physician, or any other professional who is on the go. People in these positions cannot be expected to always ptg 1817 Leveraging the Microsoft Sync Framework 45 have access to a high-speed wireless network, and MSF enables you to build programs that accommodate them. Getting Started with MSF and Sync Services for ADO.NET As is the trend with many new Microsoft technologies, much of the work of configuring and preparing your application is done by wizards and other code-generation mecha- nisms. In the sections that follow, we examine how to use the MSF-related tools and templates provided with SQL Server 2008 and Visual Studio 2008 to accomplish our goal of building an OCA-style Windows Forms application. To begin, you must first have MSF installed on your local machine. To accomplish this, you have two options: install the feature using the SQL Server installer (illustrated in Figure 45.12) or download MSF using the links found at MSF’s home page at http://www. msdn.com/sync. You also need to install Sync Services for ADO.NET (SSADO) if your system does not have it already. SSADO provides assemblies in the Microsoft.Synchronization.Data* name- spaces that enable data synchronization for ADO.NET applications. To see whether you have these assemblies, open Windows Explorer and navigate to %PROGRAMFILES%\Microsoft Synchronization Services\ADO.NET. If they aren’t installed, visit the MSF home page and look for the Sync Services for ADO.NET links; then down- load and install. FIGURE 45.12 Installing MSF via the SQL Server 2008 installer. ptg 1818 CHAPTER 45 SQL Server and the .NET Framework The general architectural model for MSF with SSADO is made up of the following: . Synchronization providers, both client and server side, which abstract the details of and provide access to the data stores on each side of the synchronization . A synchronization agent, which acts as the runtime that communicates with each synchronization provider . Databases, which store the desired content as well as synchronization metadata and supporting T-SQL code The main idea behind these components is that they enable your application to read and write to a local database; then, when synchronization time comes, any changes that happened on the local side get pushed up to the server database. In turn, any changes that happened on the server since the last synchronization get pushed down to the local data- base. Any conflicts that occur are resolved by the conflict resolution logic built in to the synchronization components (which, of course, you can tweak as necessary). In this way, when synchronization completes, your local database always has the latest and greatest, and you can continue to work offline until the next synchronization. In the sample OCA, you build a simple WinForms application that synchronizes with the AdventureWorks2008 database on your local server. Building Our Example OCA To begin, start Visual Studio and create a new Windows Forms application (this example is in C#). Next, right-click your application name in Solution Explorer and click Add New Item. Click the Data node under the Categories heading on the left. Under Templates, click Local Database Cache, and name this new file AW08LocalCache.sync (as illustrated in Figure 45.13). Local database caches (LDCs) provide you with the code area in your project where you can control how data synchronization works. FIGURE 45.13 Adding a local database cache file to the sample application. ptg 1819 Leveraging the Microsoft Sync Framework 45 After your LDC has been added, the new Configure Data Synchronization (CDS) dialog opens (you can also view this dialog anytime by double-clicking your LDC). This is a criti- cal dialog to understand because it is responsible for generating all the C#, T-SQL, and configuration code needed for using synchronization in your program. When you use SSADO with SQL Server 2008 databases, two options exist for performing the change tracking at its core: . Using SQL Server Change Tracking, a new feature in SQL Server 2008 that natively tracks row changes and stores them as metadata, accessible via a new set of functions (covered in detail in Chapter 42, “What’s New for Transact-SQL in SQL Server 2008”) . Using the default tracking mechanism, which relies on T-SQL triggers to compare datetime values stored in columns added to the server tables Returning to the CDS dialog, under the Database Connections group box, select the connection to your local AdventureWorks2008 database under Server Connection. Under Client Connection, leave the default AdventureWorks2008.sdf (New) selection. This option creates a new SQL Server Compact (SQLCE) 3.5 database in your application that acts as your OCA’s local data store (illustrated in Figure 45.14). On the left side of the dialog, under Cached Tables, is a tree structure (the top of the tree represents the Application itself). Using the Add and Remove buttons below the tree, you can configure which tables you want to synchronize between the local SQLCE database and the remote database. Those you select are created and/or populated before your first synchronization with the server. FIGURE 45.14 Using the Configure Data Synchronization dialog to configure MSF with ADO.NET. ptg 1820 CHAPTER 45 SQL Server and the .NET Framework Click the Add button, and, using the ensuing Configure Tables for Offline Use dialog, scroll down under Tables and put a check mark next to ProductReview (Production) (illustrated in Figure 45.15). As you can see on the right side, there are a number of options for which data to download (all or incremental), which columns will be used to compare records (either by using existing columns or adding new ones to the server table), and where deleted records’ keys will be stored on the server ( TableName_Tombstone is the default naming convention). The wizard adds the CreationDate and ModifiedDate columns to ProductReview in both the local and server databases. The wizard creates the ProductReview_Tombstone table on the server. It also generates two handy T-SQL DDL scripts in your Visual Studio project to accomplish and undo these changes. When your Configure Tables for Offline Use dialog matches the one in Figure 45.15, click OK to return to the main CDS dialog. Next, uncheck the Use SQL Server Change Tracking check box, found under the Database Connections group box. Next, click the Advanced button. This group box contains options that allow you to generate the server and client provider code in either the same or two different Visual Studio projects. If you click the Show Code Example link button on the bottom of the CDS dialog, you are presented with a handy dialog that provides you with a block of prewritten synchroniza- tion code and a Copy button that puts that code on the Clipboard. Click the Copy button and then click Close. When your CDS dialog matches the one in Figure 45.14, click OK. To make things even easier for development, the next dialog that appears (Data Source Configuration Wizard) will generate a strongly typed dataset (called AdventureWorks2008DataSet) that encapsulates your selected tables (illustrated in Figure 45.16). Be sure to put a check mark in the root Tables node; then click Finish. (If you get a warning about MSF needing to upload or synchronize changes, accept the default state of the dialog and click OK.) Using Solution Explorer, examine all the files created throughout this process. Notice your new App.Config and corresponding Settings.Settings files, with their connection strings FIGURE 45.15 Using the Configure Tables for Offline Use dialog to select tables to be synchronized. ptg 1821 Leveraging the Microsoft Sync Framework 45 FIGURE 45.16 Using the Data Source Configuration Wizard to generate a strongly typed dataset. to the local and server databases. Then look at the T-SQL DLL script that creates the trig- gers, columns, and tombstone table which facilitate change tracking. Examine your new SQLCE database (using SSMS if you like), strongly typed dataset, LDC, and other code files. Believe it or not, the only things left to do to set up the OCA for synchronization are to add a DataGridView to the application’s main form, associate it with the strongly typed dataset, add the block of code that you copied to your Clipboard (earlier, from the CDS dialog) to an event handler, and change your agent to perform bidirectional synchroniza- tion (it does unidirectional download-only by default). Perform the following steps to complete your application: . To set the synchronization mode, open your LDC’s designer file ( AW08LocalCache.designer.cs), locate the synchronization agent class ( AW08LocalCacheSyncAgent), and replace its partial method declaration for OnInitialize to the following: private void OnInitialized() { Production_ProductReview.SyncDirection = Microsoft.Synchronization.Data.SyncDirection.Bidirectional; } . Next, open your project’s main form in the forms designer. Reveal the Data Source tool window by pressing Shift+Alt+D. Drag the Production_ProductReview node from the Data Source tool window onto your form. This provides your form with an instance of your strongly typed dataset ( AdventureWorks2008DataSet) as well as a DataGridView (production_ProductReviewDataGridView) with standard buttons, table adapter ( production_ProductReviewTableAdapter) and associated manager ptg 1822 CHAPTER 45 SQL Server and the .NET Framework ( tableAdapterManager), and data navigator ( production_ProductReviewBindingNavigator) for moving through the data using the toolbar. . Set the Dock property of your DataGridView to Fill. The final result should look something like the form shown in Figure 45.17. . Double-click the title area of your form. In the OnLoad event handler that opens in the text editor, replace the code in the body with the following synchronization code: private void Form_Load(object sender, EventArgs e) { //Sync the data when the application starts try { new AW08LocalCacheSyncAgent().Synchronize(); } catch (Exception) { MessageBox.Show(“Unable to synchronize at this time.”); } finally { production_ProductReviewTableAdapter.Fill( adventureWorks2008DataSet.Production_ProductReview); } } FIGURE 45.17 Windows Forms application UI showing synchronization data. ptg 1823 Summary 45 . Run your application in debug mode. Edit and save any record using your DataGridView; then, using SQL Server Management Studio, edit and save a different record in the Production.Product review table. Examine the results of bidirectional synchronization by restarting your application. Validate the changes by querying the server data by writing a new SELECT query and executing it in SSMS. If you are interested in learning all the implementation details of MSF, feel free to walk through your synchronization code in debug mode to familiarize yourself with all the components at work, including the providers, agent, adapters, and T-SQL triggers. Although this tutorial provided an MSF jump-start, you should be sure to visit the MSF Developer Center at http://www.msdn.com/sync for full coverage on all aspects of MSF and SSADO. Summary In this chapter, you saw how to develop data-driven applications using several new and updated frameworks including ADO.NET 3.5, LINQ to SQL, ADO.NET Data Services, and the Microsoft Sync Framework. Chapter 46, “SQLCLR: Developing SQL Server Objects in .NET," shows how to write stored procedures, functions, triggers, aggregates, and custom data types in C# or VB.NET. . “What’s New for Transact -SQL in SQL Server 2008 ) . Using the default tracking mechanism, which relies on T -SQL triggers to compare datetime values stored in columns added to the server tables Returning. AdventureWorks2008 database under Server Connection. Under Client Connection, leave the default AdventureWorks2008.sdf (New) selection. This option creates a new SQL Server Compact (SQLCE) 3.5 database. links; then down- load and install. FIGURE 45.12 Installing MSF via the SQL Server 2008 installer. ptg 1818 CHAPTER 45 SQL Server and the .NET Framework The general architectural model for MSF