Building Applications and Services Using Open Data Protocol

groanaberrantInternet and Web Development

Feb 2, 2013 (4 years and 4 months ago)

676 views





Hands
-
On Lab

Building Applications and Services Using
O
pen
Data

Protocol



Lab version:



1.0.0

Last updated:


3/18/2013










CONTENTS

OVERVIEW

................................
................................
................................
................................
...................

3

Starting Materials

6

EXERCISE 1
: INTRODUCTION TO OP
EN DATA PROTOCOL

................................
................................
.

6

Task 1


Exploring an OData Feed

................................
................................
................................
.........

7

EXERCISE 2: CREATING

AN ODATA FEED OVER S
QL SERVER
................................
..........................

8

Task 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

EXER
CISE 3: BUILDING A S
ILVERLIGHT CLIENT WI
TH ODATA FEEDS

................................
..........

19

Task 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



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

t
hird 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, y
ou 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

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



Use Open Data Prot
ocol 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


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 K
it 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
\
Dependency
Checker 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 Stu
dio 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,



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
1

Hit TAB to select the highlighted snippet.



Figure
2

Hit 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 La
b comprise
s

the following exercises:

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 exercise
s
.



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
a
s
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

server
s, 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 J
SON 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 Atom
Pub

that are

documented and
released under the
principle of
OSP (Open Specification Promise)
to allow everyone to freely
interoperate with OData implementations.


Currently
,

the
following Microsoft products

support
OData
:



Microsoft Visual Studio 2008 SP1



M
icrosoft 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 e
ach 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 b
rowse 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 D
epartment 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, wh
ich shows MEDIAN parks that have
seven or more wardens. The following is the resulting URL.


URL

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



Figure
3

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


Task 1


Creating the Data Service Web Application
Project

In this task
,

you will create a
n

ASP.NET Web application project t
hat 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
a
n empty
solution for
this exercise.

3.

In Solution Explorer, right
-
click the
OpenDataService
s

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
\
Ex
2
\
B
egin

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
4

Creating a new Website (C#)



Figure
5

Creating 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
Propert
y

page, open the
Web

tab.

c.

In the
Server
s

section
,

select
Specific Port
.

d.

Set the port number to
50000
.

e.

Press

Ctrl

+
S

to save changes.


Figure
6

Specifying a port number



Task 2


Creating the Entity Data Model

In th
is 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
AdventureWorks
Shopping
.edmx
, and then click
Add
.



Figure
7

Adding

the

ADO.NET Entity Data Model

(C#)



Figure
8

Adding

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.

C
lick
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)
. I
f not
,

ch
ange 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
9

Specify the database connection


5.

Back on the Entity Data
Model W
izard

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
10

Choose database objects to include in the model

Note:
For more information,
see

ADO.NET Entity Framework
.


7.

Click
Finish
.



Task 3


Creat
ing

the

WCF

Data Service

In this task, you will create the

WCF Data Service

that
expose
s

data by using the Entity Data Model as
specified by the ADO.NET Entity Fram
ework.

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
.


F
i
gure
11

Add the WCF Data
Service

item (C#)



F
i
gure
12

Add 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#

p
ublic class AdventureWorks : DataService<AdventureWorksShopping
Entities>


(Code Snippet


OData

Lab
-

Ex 2.3.3
-

AdventureWorks Data Service Definition

VB
)

Visual Basic

Public Class
AdventureWorks


Inherits

DataService(Of AdventureWorksShopping
Entities)


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:

(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.MaxProtocolVers
ion =
DataServiceProtocolVersion.V2
;

}


(Code Snippet


OData

Lab
-

Ex 2.3.4
-

AdventureWorks.svc InitializeService

VB
)

Visual Basic

Public Shared Sub Ini
tializeService(ByVal config As
DataServiceConfiguration)


config.SetEntitySetAccessRule("*",
EntitySetRights.
AllRead
)


config.DataServiceBehavior.MaxProtocolVersion =
DataServiceProtocolVersion.V2

End Sub


Note:

By default, a data
service,

does not expose any resources. Access to resources need to
be explicitly enabled before any resources or a
ssociations are accessible. For more
information, see
IDataServiceConfiguration.SetEntitySetAccessRule Method
(System.Data.Se
rvices)
.



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 sur
rounding 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

E
ntity
D
ata
M
odel

(EDM) style represent

the
database

tables that are exposed by the data service.

T
he output will be
similar to the following figure.

Note:

The XML document returned by default is an Atom service document
because

th
e

default serialization used by the

data service is Atom
.


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
13

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


Figure
14

Data 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
mo
re complex requests

using URIs check
Simple Addressing Scheme for Data with
Uniform URLs
.



Exercise 3
: Building a Silv
erlight 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 LIN
Q.

Task 1


Creating Silverlight App
lication

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 20
10
.

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
15

Solution Explorer showing the Op
en Data solution


W
ebSite

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


4.

In the Sol
ution 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.


Fi
gure
16

Creating a new Silverlight Application project (C#)



Figure
17

Creating a new Silv
erlight 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
18

New Silverlight
Application Dialog


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


Figure
19

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



Figure
20

Soluti
on Explorer Showing the Adventure Works Shopping project (VB)



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 va
riety 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 fr
om 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.


Figure
21

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

N
ote:

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.



Figure
22

ASP.N
ET 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
23

Solution Explorer showing the Service Reference into the

AdventureWorksShopping project



Task 3


Configuring the AdventureWorks Shopping
P
roject

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

1.

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

2.

Right
-
click the
AdventureWorksShopping

project, point to
Add
, and click
Existing Item
. Brows
e
to the
Source
\
Assets
\
Ex
3
\

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
24

Configuring the AdventureWorks service URL


3.

Add the f
ile 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
I
tem
. Browse to the
Source
\
Assets
\
Ex
3
\

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

6.

Select the MainPage.xaml file in
S
olution
E
xplorer
, 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


O
D
ata

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.Adventu
reWorks.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.


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,
Sele
ctionChangedEventArgs 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

Categor
iesListBox_SelectionChanged Method
-

VB)

Visual Basic

Private Sub CategoriesListbox_SelectionChanged(ByVal sender As Object, ByVal e
As SelectionChangedEventArgs)


Dim category = TryCast(Me.CategoriesListbox.SelectedItem, ProductCategory)


PopulateFi
lteredShoppingCenters(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
cre
ates 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
)

C#

private void PopulateFilteredShoppingCenters(ProductCategory category)

{


if (category != null


&& category.ProductCategoryShopping != null


&& category.ProductCategoryShopping.Count > 0)


{


var shoppingQuery = (from shoppingCenter

in
this.DistrictOfColumbia.Sho
pingCenters.AddQueryOption("$filter",
t
his.CreateShoppingsFilter(category))


select shopping
Center) 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 shoppingCente
r In
Me.DistrictOfColumbia.Shop
ingCenters.AddQueryOption("$filter",
Me.CreateShoppingsFilt
er(category)) _


Select shoppingCenter), DataSer
viceQuery(Of ShopingCenter
))



Me.AsyncQueryOnDataContext(shoppingQuery, Me.ShoppingsListbox)


Else


Me.ShoppingsListbox.DataContext = Nothing


End If

End Sub


11.

Press
C
TRL
+
SHIFT
+
B

to build the solution.



Task 4


Persisting Changes to a Database

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))


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,



.Ite
mQty = 1


}


shoppingCart.Add(newShoppingCart)


Me.AdventureWorks.AddToShoppingCart(newShoppingCart)


Else


item.ItemQty += 1


Me.AdventureWorks.UpdateObject(item)


End If


End If

End 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.Delet
eObject(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)


End If

End 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("Ch
anges 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 p
roject. 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 voi
d InitializeService(DataServiceConfiguration config)

{


config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);


config.SetEntitySetAccessRule("ShoppingCart", EntitySetRights.All);


config.DataServiceBehavior.MaxProtocolVersion =
DataServiceP
rotocolVersion.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.V2

End 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 Proj
ect
.

2.

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


Figure
25

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


Figure
26

The AdventureWorks Shopping application


5.

Click the
+

button to add some products to the shopp
ing 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.


Figure
27

Saving the Shopping Cart


8.

Close
Internet Explorer

to finish the applic
ation.



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 c
reate a proxy class
for an OData service and use it in a seamless way.