41
Hands-On Lab Building Applications and Services Using Open Data Protocol Lab version: 1.0.0 Last updated: 4/11/2022

Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Hands-On LabBuilding Applications and Services Using Open Data Protocol

Lab version: 1.0.0

Last updated: 5/15/2023

Page 2: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

CONTENTS

OVERVIEW................................................................................................................................................. 3Starting Materials 6

EXERCISE 1: INTRODUCTION TO OPEN DATA PROTOCOL.................................................................6Task 1 – Exploring an OData Feed........................................................................................................7

EXERCISE 2: CREATING AN ODATA FEED OVER SQL SERVER.........................................................8Task 1 – Creating the Data Service Web Application Project...............................................................9

Task 2 – Creating the Entity Data Model............................................................................................11

Task 3 – Creating the WCF Data Service............................................................................................14

Exercise 2 Verification.......................................................................................................................17

EXERCISE 3: BUILDING A SILVERLIGHT CLIENT WITH ODATA FEEDS ..........................................19Task 1 – Creating Silverlight Application............................................................................................19

Task 2 – Adding Service References...................................................................................................24

Task 3 – Configuring the AdventureWorks Shopping Project............................................................26

Task 4 – Persisting Changes to a Database........................................................................................30

Exercise 3 Verification.......................................................................................................................34

SUMMARY................................................................................................................................................ 36

Page 3: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Overview

The Open Data Protocol (OData) is a web protocol for querying and updating data. Its specification is available under Microsoft's Open Specification Promise (OSP), therefore third parties, including open source projects, can build Open Data Protocol clients and services.

OData is defined as a set of open extensions/conventions to AtomPub. It adds the following features to AtomPub.

A convention for representing structured data

A resource addressing scheme and URL syntax

A set of common query options (filter, sort, etc.)

Schema describing resource structure, links and metadata

Payload formats and semantics for batch and “unit of work” requests

Alternate representations of resource content (JSON)

In this lab, you will learn about the Open Data Protocol, the ecosystem where it works, and why developers should write applications and services using the Open Data Protocol as their Data Access protocol. You will also learn how to create simple applications in various technologies that manage the OData feeds.

Objectives

In this Hands-On Lab, you will learn how to:

Use Open Data Protocol in different environments

Create an OData feed over SQL Server 2008

Prerequisites

The following is required to complete this hands-on lab:

Microsoft Visual Studio 2010

Microsoft .NET Framework 4

SQL Server 2008 Express Edition (or above)

Silverlight 4 Tools for Microsoft Visual Studio 2010

Page 4: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Setup

All the requisites for this lab are verified using the Configuration Wizard. To make sure that everything is correctly configured, follow these steps:

Note: To perform the setup steps you need to run the scripts in a command window with administrator privileges.

1. Run the Configuration Wizard for the Training Kit if you have not done it previously. To do this, browse to Source\Setup folder of this lab, and double-click the Dependencies.dep file. Install any pre-requisites that are missing (rescanning if necessary) and complete the wizard.

Note: The Configuration Wizard is used for checking dependencies and setting up the environment. If the Configuration Wizard is not installed on your machine, you must install it running the DependencyChecker.msi file located on the %VS2010TKInstallationFolder%\Assets\DependencyChecker folder (e.g. by default the Training Kit is installed under C:\VS2010TrainingKit).

For convenience, much of the code you will be managing along this lab is available as Visual Studio code snippets. The Dependencies.dep file launches the Visual Studio installer file that installs the code snippets.

Using the Code Snippets

With code snippets, you have all the code you need at your fingertips. The lab document will tell you exactly when you can use them. For example,

Page 5: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

To add this code snippet in Visual Studio, you simply place the cursor where you would like the code to be inserted, start typing the snippet name (without spaces or hyphens), in this case LabNameEx01RunmethodCS, watch as Intellisense picks up the snippet name, and then hit the TAB key twice once the snippet you want is selected. The code will be inserted at the cursor location.

Figure 1Hit TAB to select the highlighted snippet.

Figure 2Hit TAB again and the snippet will expand

To insert a code snippet using the mouse rather than the keyboard, right-click where you want the code snippet to be inserted, select Insert Snippet followed by My Code Snippets and then pick the relevant snippet from the list.

To learn more about Visual Studio IntelliSense Code Snippets, including how to create your own, please see Creating and Using IntelliSense Code Snippets.

Exercises

This Hands-On Lab comprises the following exercises:

Page 6: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

1. Introduction to Open Data Protocol

2. Creating an OData Feed over SQL Server

3. Building a Silverlight Client with OData Feeds

Estimated time to complete this lab: 60 minutes.

Starting Materials

This Hands-On Lab includes the following starting materials.

Visual Studio solutions. The lab provides the following Visual Studio solutions that you can use as starting point for the exercises.

◦ Source\Ex2\Begin\[C#|VB]\OpenDataServices.sln

◦ Source\Ex3\Begin\[C#|VB]\OpenDataServices.sln

Note: Inside each exercise folder, you will find an end folder containing a solution with the completed lab exercise.

Exercise 1: Introduction to Open Data Protocol

In this exercise, you will learn the advantages provided by Open Data Protocol, the ecosystem; where it works, and why developers should write applications and services using the Open Data Protocol as their Data Access protocol.

Today, one important value in a connected world is the ability to reuse and share data, by creating a system that can support multiples data sources.

The Open Data Protocol, referred to as OData, is a web protocol for querying and updating data and it was born of the need to break down data silos and increase their shared value. This allows data silos to interoperate between producers such as SQL Server, SharePoint servers, Cloud Storage Services, and consumers, for example Java, PHP, Silverlight, IIS, ASP.NET, AJAX.

OData uses web technologies, such as HTTP, Atom Publishing (AtomPub), and JSON to provide access to information from a range of applications, services, and stores like relational databases, file systems, content management systems, and traditional web sites.

OData is also defined as a set of open extensions / conventions to AtomPub that are documented and released under the principle of OSP (Open Specification Promise) to allow everyone to freely interoperate with OData implementations.

Page 7: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Currently, the following Microsoft products support OData:

Microsoft Visual Studio 2008 SP1

Microsoft Visual Studio 2010

Microsoft Office Excel 2010 (Through PowerPivot)

SharePoint 2010

SQL Server 2008 R2

Windows Azure Table Storage

Using OData as the default data access protocol, allows your application to work and interact with other systems; without any implementation restriction because it supports HTTP, XML and JSON.

Note: The data in OData is represented as rows using Atom feeds, where each entry has the usual metadata and is structured as name/value pairs inside content.

Task 1 – Exploring an OData Feed

In this task, you will browse an OData feed and perform a simple query to filter out the data.

1. Open an Internet Explorer windows and browse to the following URL.

◦ http://ogdi.cloudapp.net/v1/dc/RecreationParks/

The data shown contains general locations and amenity information about recreation parks of the Department of Columbia and it is formatted as an OData feed.

2. Add a filter to return only the data about MEDIAN parks. To do this, add the following query string to the URL and press the ENTER key to see the filtered results.

◦ ?$filter=use_type eq 'MEDIAN'

The resulting URL is the following.

URL

http://ogdi.cloudapp.net/v1/dc/RecreationParks/?$filter=use_type eq 'MEDIAN'

3. You can perform a more complex query on the data, for example adding an additional filter.

Replace, the previous query string with the following one, which shows MEDIAN parks that have seven or more wardens. The following is the resulting URL.

Page 8: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

URL

http://ogdi.cloudapp.net/v1/dc/RecreationParks/?$filter=(use_type eq 'MEDIAN') and (ward ge '7')

Figure 3Results feed of the OData query

Note: This data used in this exercise, is real data taken from the Open Government Data Initiative (OGDI). The OGDI project contains data gathered from government agencies. For more information about OData, see www.odata.org.

Exercise 2: Creating an OData Feed over SQL Server

In this exercise, you will learn how to create a data service that exposes a SQL Server database, and consume it using a web browser.

Page 9: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Task 1 – Creating the Data Service Web Application Project

In this task, you will create an ASP.NET Web application project that will host and expose the data service.

1. Open Microsoft Visual Studio 2010 from Start | All Programs | Microsoft Visual Studio 2010 | Microsoft Visual Studio 2010.

2. Open the OpenDataServices.sln solution file, located under the Source\Ex2\Begin folder of this lab (choosing the folder that matches the language of your preference). This is an empty solution for this exercise.

3. In Solution Explorer, right-click the OpenDataServices solution, point to Add and select New Project.

4. In the Add New Project dialog, select the language of your preference (Visual C# or Visual Basic), and then click the Web project type. Make sure that .NET Framework 4.0 is selected, and then select the ASP.NET Empty Web Application template.

5. You may set the location to the Source\Ex2\Begin folder of this lab (and choosing the folder that matches the language of your preference).

6. Set the Name to WebSite, and click OK.

Figure 4Creating a new Website (C#)

Page 10: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Figure 5Creating a new Website (Visual Basic)

7. Configure the web site to use port 50000.

a. To do this, in Solution Explorer, right-click the WebSite project and in the context menu select Properties.

b. In the Property page, open the Web tab.

c. In the Servers section, select Specific Port.

d. Set the port number to 50000.

e. Press Ctrl + S to save changes.

Page 11: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Figure 6Specifying a port number

Task 2 – Creating the Entity Data Model

In this task, you will create the mapping specification that connects programmable classes to storage structures.

The Entity Data Model (EDM) is a specification for defining the data used by applications built on the Entity Framework. Applications using the EDM define a design schema, which includes entities and relationships in the domain of the application.

1. Create the AdventureWorks Entity Data Model. To do this, in Solution Explorer, right-click the WebSite project, point to Add, and click New Item.

2. In the Add New Item dialog box, select ADO.NET Entity Data Model. Specify a Name value of AdventureWorksShopping.edmx, and then click Add.

Page 12: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Figure 7Adding the ADO.NET Entity Data Model (C#)

Page 13: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Figure 8Adding the ADO.NET Entity Data Model (Visual Basic)

3. In the Entity Data Model Wizard, select Generate from Database and click Next.

4. Specify the Database connection. To do this, follow the following steps:

a. Click New Connection.

b. If the Choose Data Source dialog is prompted, select Microsoft SQL Server Database File (SqlClient) as Data Source and click Continue. If the Connection Properties dialog is displayed directly, make sure the Data source is set to Microsoft SQL Server Database File (SqlClient). If not, change it to this value.

c. In the Connection Properties dialog, browse to Source\Assets\AdventureWorksShopping.mdf in the Database file name field, and then click OK.

Figure 9Specify the database connection

Page 14: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

5. Back on the Entity Data Model Wizard click Next, and then Yes when the Wizard asks to copy the database file to the application data folder.

6. Include only the Tables objects from all the proposed database objects and leave the Model Namespace. Make sure that Pluralize or singularize generated object names option is unchecked.

Figure 10Choose database objects to include in the model

Note: For more information, see ADO.NET Entity Framework.

7. Click Finish.

Task 3 – Creating the WCF Data Service

In this task, you will create the WCF Data Service that exposes data by using the Entity Data Model as specified by the ADO.NET Entity Framework.

Page 15: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

1. Add the Data Service. To do this, in Solution Explorer, right-click the WebSite project, point to Add, and click New Item.

2. In the Add New Item dialog box, select the WCF Data Service template. Specify a Name value of AdventureWorks.svc, and then click Add.

Figure 11Add the WCF Data Service item (C#)

Page 16: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Figure 12Add the WCF Data Service item (Visual Basic)

3. Locate the class definition and replace it with the following code. This indicates that the service uses the Entity Framework Data Model as data source.

Note: Visual Studio will open the code file for the new service by default. You can also find the file in the Solution Explorer by right-clicking the AdventureWorks.svc file.

(Code Snippet – OData Lab - Ex 2.3.3 - AdventureWorks Data Service Definition CSharp)

C#

public class AdventureWorks : DataService<AdventureWorksShoppingEntities>

(Code Snippet – OData Lab - Ex 2.3.3 - AdventureWorks Data Service Definition VB)

Visual Basic

Public Class AdventureWorks Inherits DataService(Of AdventureWorksShoppingEntities)

4. Grant read and write access to all resources of the Entity Data Model associated with the service, by replacing the InitializeService method with the following code:

Page 17: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

(Code Snippet – OData Lab - Ex 2.3.4 - AdventureWorks.svc InitializeService CSharp)

C#

public static void InitializeService(DataServiceConfiguration config){ config.SetEntitySetAccessRule("*", EntitySetRights.AllRead); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;}

(Code Snippet – OData Lab - Ex 2.3.4 - AdventureWorks.svc InitializeService VB)

Visual Basic

Public Shared Sub InitializeService(ByVal config As DataServiceConfiguration) config.SetEntitySetAccessRule("*", EntitySetRights.AllRead) config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2End Sub

Note: By default, a data service, does not expose any resources. Access to resources need to be explicitly enabled before any resources or associations are accessible. For more information, see IDataServiceConfiguration.SetEntitySetAccessRule Method (System.Data.Services).

Exercise 2 Verification

In this verification, you will use a web browser to consume the Data Service and to check its XML response.

Note: The easiest way to try a data service is to simply access it through a web browser. While this is probably not the way you will ultimately use the data service (it is more likely that a program will interact with it), it is an easy way to understand how requests work, how results look like, and other details surrounding the implementation of the service.

1. Navigate to the AdventureWorks data service. To do this, right-click the AdventureWorks.svc file and select View in Browser. You will notice that the XML response of the data service is a list of entity-sets. The entity-sets in the Entity Data Model (EDM) style represent the database tables that are exposed by the data service. The output will be similar to the following figure.

Note: The XML document returned by default is an Atom service document because the default serialization used by the data service is Atom.

Page 18: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Note: If the browser displays a message saying it cannot display the feed, turn off the feed reading view. In Internet Explorer, clear the Turn on feed reading view check box, located under Tools | Internet Options | Content Tab | Feeds Section | Settings,.

Figure 13Data Service XML response

2. To browse a specific entity, add its name to the address in the web browser. For instance, if the web server port is 50000 you should browse http://localhost:50000/AdventureWorks.svc/Product/. The following output should appear.

Page 19: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Figure 14Data Service XML response for the product entity set

Note: The WCF Data Services framework implements a data addressing scheme that uses URIs. It is based on the Entity Data Model (EDM) specification for data types and data sets. For building more complex requests using URIs check Simple Addressing Scheme for Data with Uniform URLs.

Exercise 3: Building a Silverlight Client with OData Feeds

In this exercise, you will create a Silverlight Application that consumes a local OData service and an OData service on the clouds. Additionally, this exercise demonstrates how to perform simple CRUD operations using LINQ.

Task 1 – Creating Silverlight Application

Page 20: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

In this task, you will create the Silverlight client application, which exposes products for the categories available in each shopping center.

1. Open Microsoft Visual Studio 2010, from Start | All Programs | Microsoft Visual Studio 2010. If the User Account Control dialog appears, click Continue.

2. In the File menu, choose Open and then Project/Solution. In the Open Project dialog, browse to Ex3\Begin in the Source folder of the lab, select OpenDataService.sln in the folder of the language of your preference (Visual C# or Visual Basic), and click Open.

Note: If you performed the previous exercise, you can use the same ending solution.

3. The solution contains the following project:

Figure 15Solution Explorer showing the Open Data solution

WebSite

A standard web site project that hosts the AdventureWorks service and expose its entities.

4. In the Solution Explorer, right-click the solution, select Add | New Project. In the New Project dialog, expand the language of your preference (Visual C# or Visual Basic) in the Project types list select Silverlight. In the Templates list, select Silverlight Application. Enter the name AdventureWorksShopping, and click OK to create the project.

Page 21: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Figure 16Creating a new Silverlight Application project (C#)

Page 22: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Figure 17Creating a new Silverlight Application project (VB)

5. In the New Silverlight Application dialog, make sure that the WebSite project is selected to host the Silverlight application, and that the Silverlight 4 version of the framework is targeted. Make sure that the Add a test page references the application checkbox, and click OK.

Figure 18New Silverlight Application Dialog

The following figure shows the newly Silverlight Application in the Solution Explorer.

Page 23: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Figure 19Solution Explorer Showing the Adventure Works Shopping project (C#)

Figure 20Solution Explorer Showing the Adventure Works Shopping project (VB)

Page 24: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Task 2 – Adding Service References

This exercise uses the Open Government Data Initiative (OGDI) databases. OGDI uses the Windows Azure Platform to make it easier to publish and use a wide variety of public data from government agencies. OGDI is also a free, open source starter kit, which includes code that can be used to publish data on the Internet in a Web-friendly format with easy-to-use, open API's. OGDI-based web API’s can be accessed from a variety of client technologies such as Silverlight, Flash, JavaScript, PHP, Python, Ruby, mapping web sites, etc.

In this task, you will create a reference to the Open Government Data Initiative (OGDI) and a reference to the Adventure Works service.

1. Add the OGDI reference to the AdventureWorksShopping project. To do this, in Solution Explorer, right-click the AdventureWorksShopping project, and select Add Service Reference.

2. Enter http://ogdi.cloudapp.net/v1/dc as the Address, and click Go to search for services. Visual Studio will find and show the available services.

3. Set the Namespace to DistrictOfColumbia, and click OK to add the service reference.

Page 25: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Figure 21Adding the Service Reference

4. To add the Adventure Work reference into the project, run the ASP.NET applications locally in the ASP.NET Development Server. To do this, in the Solution Explorer, right-click the AdventureWorks.svc file of the WebSite project and click View in Browser.

Note: Notice that the Adventure Work service is configured to use the port number 50000. Make sure there is no other application that uses this port. If you wish, you can change the Web properties of the project.

Page 26: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Figure 22ASP.NET Development Server Showing the Adventure Work host service

5. Add the AdventureWorks reference to the project. To do this, in the Solution Explorer, right-click the AdventureWorksShopping project, and click Add Service Reference.

6. Enter http://localhost:50000/AdventureWorks.svc as the Address, and click Go to search for services. Visual Studio will find and show the available services.

7. Set the Namespace to AdventureWorks, and click OK to add the service reference.

Figure 23Solution Explorer showing the Service Reference into the AdventureWorksShopping project

Task 3 – Configuring the AdventureWorks Shopping Project

In this task, you will complete the methods that query the database to retrieve the application data. All the queries use LINQ.

1. Delete the MainPage.xaml file from the AdventureWorks. To do this, in the Solution Explorer, right-click the file and click Delete.

Page 27: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

2. Right-click the AdventureWorksShopping project, point to Add, and click Existing Item. Browse to the Source\Assets\Ex3\ folder, go to the subfolder that corresponds to the language of your preference, select the MainPage.xaml file, and click Add.

If the AdventureWorks.svc service is running on a different port than 50000, you need to change the service URL in the AdventureWorks property of the MainPage class.

Figure 24Configuring the AdventureWorks service URL

3. Add the file that contains the styles of the application’s UI. To do this, right-click the AdventureWorksShopping project, point to Add, click New Folder and name it Styles. Right-click this folder, point to Add and click Existing Item. Browse to the Source\Assets\Ex3\ folder, select the Styles.xaml file, and click Add.

4. Add a reference to the styles file in App.xaml. To do this, open App.xaml and add the following code, between the Application.Resources tags.

XAML

<Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Styles/styles.xaml"></ResourceDictionary> </ResourceDictionary.MergedDictionaries> </ResourceDictionary></Application.Resources>

5. Add the following references to the AdventureWorksShopping by right-clicking the References folder in Solution Explorer, and clicking Add Reference.

◦ System.Windows.Controls.Data

◦ System.Windows.Controls.Data.Input

Page 28: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

6. Select the MainPage.xaml file in Solution Explorer, and press F7 to open its code file.

7. Check the AdventureWorks and DistrictOfColumbia properties; both initialize their respective data services in their getters.

8. Locate the UserControl_Loaded method and add the following code.

(Code Snippet – OData Lab - Ex 3.3.8 UserControl_Loaded Method - CS)

C#

private void UserControl_Loaded(object sender, RoutedEventArgs e){ var categoryQuery = (from category in this.AdventureWorks.ProductCategory.Expand("ProductCategoryShopping") where category.ParentProductCategoryID != null select category) as DataServiceQuery<ProductCategory>; this.AsyncQueryOnDataContext(categoryQuery, this.CategoriesListbox);

var shoppingCartQuery = this.AdventureWorks.ShoppingCart.Expand("Product"); this.AsyncQueryOnDataContext(shoppingCartQuery, this.ShoppingCartListbox);}

(Code Snippet – OData Lab - Ex 3.3.8 UserControl_Loaded Method - VB)

Visual Basic

Private Sub UserControl_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs) Dim categoryQuery = TryCast((From category In Me.AdventureWorks.ProductCategory.Expand("ProductCategoryShopping") _ Where category.ParentProductCategoryID IsNot Nothing _ Select category), DataServiceQuery(Of ProductCategory)) Me.AsyncQueryOnDataContext(categoryQuery, Me.CategoriesListbox)

Dim shoppingCartQuery = Me.AdventureWorks.ShoppingCart.Expand("Product") Me.AsyncQueryOnDataContext(shoppingCartQuery, Me.ShoppingCartListbox)End Sub

The preceding method queries the AdventureWorks service and retrieves the data necessary to populate the list boxes of the application when it is loaded.

Page 29: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

9. Locate the CategoriesListBox_SelectionChanged method, which updates the list of products when a category is selected, and add the following code.

(Code Snippet – OData Lab - Ex 3.3.9 CategoriesListBox_SelectionChanged Method - CS)

C#

private void CategoriesListbox_SelectionChanged(object sender, SelectionChangedEventArgs e){ var category = this.CategoriesListbox.SelectedItem as ProductCategory; PopulateFilteredShoppingCenters(category);

this.AdventureWorks.BeginLoadProperty( category, "Product", result => this.Dispatcher.BeginInvoke(() => { this.AdventureWorks.EndLoadProperty(result); this.ProductsListbox.DataContext = category.Product; }), null);}

(Code Snippet – OData Lab - Ex 3.3.9 CategoriesListBox_SelectionChanged Method - VB)

Visual Basic

Private Sub CategoriesListbox_SelectionChanged(ByVal sender As Object, ByVal e As SelectionChangedEventArgs) Dim category = TryCast(Me.CategoriesListbox.SelectedItem, ProductCategory) PopulateFilteredShoppingCenters(category)

Me.AdventureWorks.BeginLoadProperty(category, "Product", Sub(result) Me.Dispatcher.BeginInvoke(Sub() Me.AdventureWorks.EndLoadProperty(result) Me.ProductsListbox.DataContext = category.Product End Sub) End Sub, Nothing)End Sub

10. Locate the PopulateFilteredShoppingCenters method and add the following code. This method creates a filter to return only the shopping centers that sell the specified product category.

(Code Snippet – OData Lab - Ex 3.3.10 PopulateFilteredShoppingCenters Method - CS)

Page 30: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

C#

private void PopulateFilteredShoppingCenters(ProductCategory category){ if (category != null && category.ProductCategoryShopping != null && category.ProductCategoryShopping.Count > 0) { var shoppingQuery = (from shoppingCenter in this.DistrictOfColumbia.ShopingCenters.AddQueryOption("$filter", this.CreateShoppingsFilter(category)) select shoppingCenter) as DataServiceQuery<ShopingCenter>;

this.AsyncQueryOnDataContext(shoppingQuery, this.ShoppingsListbox); } else { this.ShoppingsListbox.DataContext = null; }}

(Code Snippet – OData Lab - Ex 3.3.10 PopulateFilteredShoppingCenters Method - VB)

Visual Basic

Private Sub PopulateFilteredShoppingCenters(ByVal category As ProductCategory) If category IsNot Nothing AndAlso category.ProductCategoryShopping IsNot Nothing AndAlso category.ProductCategoryShopping.Count > 0 Then Dim shoppingQuery = TryCast((From shoppingCenter In Me.DistrictOfColumbia.ShopingCenters.AddQueryOption("$filter", Me.CreateShoppingsFilter(category)) _ Select shoppingCenter), DataServiceQuery(Of ShopingCenter))

Me.AsyncQueryOnDataContext(shoppingQuery, Me.ShoppingsListbox) Else Me.ShoppingsListbox.DataContext = Nothing End IfEnd Sub

11. Press CTRL+SHIFT+B to build the solution.

Task 4 – Persisting Changes to a Database

Page 31: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

In this task, you will complete the methods that manage the shopping cart and save its content to the database.

1. In the MainPage.xaml.cs file, locate the AddItemButton_Click method and add the following code. This method adds one unit of the corresponding product to the shopping cart.

(Code Snippet – OData Lab - Ex 3.4.1 AddItemButton_Click Method - CS)

C#

private void AddItemButton_Click(object sender, RoutedEventArgs e){ var product = ((Button)sender).DataContext as Product; if (product != null) { var shoppingCart = this.ShoppingCartListbox.DataContext as ObservableCollection<ShoppingCart>; var item = shoppingCart.SingleOrDefault(i => i.ProductID == product.ProductID); if (item == null) { var newShoppingCart = new ShoppingCart { ProductID = product.ProductID, Product = product, ItemQty = 1 }; shoppingCart.Add(newShoppingCart); this.AdventureWorks.AddToShoppingCart(newShoppingCart); } else { item.ItemQty++; this.AdventureWorks.UpdateObject(item); } }}

(Code Snippet – OData Lab - Ex 3.4.1 AddItemButton_Click Method - VB)

Visual Basic

Private Sub AddItemButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Dim product = TryCast(DirectCast(sender, Button).DataContext, Product) If product IsNot Nothing Then Dim shoppingCart = TryCast(Me.ShoppingCartListbox.DataContext, ObservableCollection(Of ShoppingCart))

Page 32: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Dim item = shoppingCart.SingleOrDefault(Function(i) i.ProductID = product.ProductID) If item Is Nothing Then Dim newShoppingCart = New ShoppingCart() With { .ProductID = product.ProductID, .Product = product, .ItemQty = 1 } shoppingCart.Add(newShoppingCart) Me.AdventureWorks.AddToShoppingCart(newShoppingCart) Else item.ItemQty += 1 Me.AdventureWorks.UpdateObject(item) End If End IfEnd Sub

2. Locate the DeleteItemButton_Click method and add the following code.

(Code Snippet – OData Lab - Ex 3.4.2 DeleteItemButton_Click Method - CS)

C#

private void DeleteItemButton_Click(object sender, RoutedEventArgs e){ var item = ((Button)sender).DataContext as ShoppingCart; if (item != null) { var shoppingCart = this.ShoppingCartListbox.DataContext as ObservableCollection<ShoppingCart>; shoppingCart.Remove(item); this.AdventureWorks.DeleteObject(item); }}

(Code Snippet – OData Lab - Ex 3.4.2 DeleteItemButton_Click Method - VB)

Visual Basic

Private Sub DeleteItemButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Dim item = TryCast(DirectCast(sender, Button).DataContext, ShoppingCart) If item IsNot Nothing Then Dim shoppingCart = TryCast(Me.ShoppingCartListbox.DataContext, ObservableCollection(Of ShoppingCart)) shoppingCart.Remove(item) Me.AdventureWorks.DeleteObject(item)

Page 33: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

End IfEnd Sub

In the preceding code, the selected item is removed from the Shopping cart.

3. Locate the CheckoutButton_Click method and add the following code to save the shopping cart in the database.

(Code Snippet – OData Lab - Ex 3.4.3 CheckoutButton_Click Method - CS)

C#

private void CheckoutButton_Click(object sender, RoutedEventArgs e){ this.AdventureWorks.BeginSaveChanges(result => { var response = this.AdventureWorks.EndSaveChanges(result); MessageBox.Show("Changes saved successfully!"); }, null);}

(Code Snippet – OData Lab - Ex 3.4.3 CheckoutButton_Click Method - VB)

Visual Basic

Private Sub CheckoutButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Me.AdventureWorks.BeginSaveChanges(Sub(result) Dim response = Me.AdventureWorks.EndSaveChanges(result) MessageBox.Show("Changes saved successfully!") End Sub, Nothing)End Sub

Note: This exercise uses Entity Framework to manage the data access of the application.

4. You must grant write access to the ShoppingCart resource in the AdventureWorks data service in the WebSite project. To do this, open the AdventureWorks.svc data service code under the WebSite project and add the following code to the InitializeService method:

(Code Snippet – OData Lab – Ex 3.4.4 - AdventureWorks.svc InitializeService CSharp)

C#

public static void InitializeService(DataServiceConfiguration config){

Page 34: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

config.SetEntitySetAccessRule("*", EntitySetRights.AllRead); config.SetEntitySetAccessRule("ShoppingCart", EntitySetRights.All); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;}

(Code Snippet – OData Lab – Ex 3.4.4 - AdventureWorks.svc InitializeService VB)

Visual Basic

Public Shared Sub InitializeService(ByVal config As DataServiceConfiguration) config.SetEntitySetAccessRule("*", EntitySetRights.AllRead) config.SetEntitySetAccessRule("ShoppingCart", EntitySetRights.All) config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2End Sub

5. Press CTRL+SHIFT+B to build the solution.

Exercise 3 Verification

In this verification, you will explore the Silverlight application; add some products to your shopping cart, and save it to the database.

1. Set the Website project as the startup project. To do this, right-click the Website project in Solution Explorer, and click Set as StartUp Project.

2. Set the AdventureWorksShoppingTestPage.html as the startup page, by right-clicking it in Solution Explorer, and then clicking Set As Start Page.

Page 35: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Figure 25Setting the Start Page

3. Press F5 to run the solution.

4. In the application, select the Mountain Bike category to display the shopping centers that sell products from this category.

Page 36: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Figure 26The AdventureWorks Shopping application

5. Click the + button to add some products to the shopping cart. You can also add products from other categories.

6. Try deleting some products from the shopping cart by clicking in the X button next to the desired product.

Note: The shopping cart is implemented using an Observable Collection instance, therefore when you add or remove products from it, the Datagrid is notified, so it is refreshed to reflect the changes.

7. When you are ready, click the Checkout button to save the changes to the database. Notice that this is the point where the changes are impacted in the database, when items are added or removed; these operations are kept in-memory.

Page 37: Building Applications and Services Using Open Data Protocolaz12722.vo.msecnd.net/.../Lab.docx  · Web viewBuilding Applications and Services Using Open Data Protocol Description

Figure 27Saving the Shopping Cart

8. Close Internet Explorer to finish the application.

Summary

In this Lab, you have learnt what Open Data is and how to consume it from .NET applications. You also learnt what the Open Data Government Initiative is. It was demonstrated how to build applications that consume Open Data from different sources, for example a local database and a database on the clouds. Then, you have seen how to use the PowerPivot add-in for Microsoft Excel 2010 that reads and organize the OData data to perform analysis on it. And finally, you used the PHP Toolkit to create a proxy class for an OData service and use it in a seamless way.