Odata on Mobile Devices

Exclusive offer: get 50% off this eBook here
OData Programming Cookbook for .NET Developers

OData Programming Cookbook for .NET Developers — Save 50%

70 fast-track, example-driven recipes with clear instructions and details for OData programming with .NET Framework with this book and ebook.

$29.99    $15.00
by Steven Cheng | August 2012 | Cookbooks

OData (Open Data Protocol) is a web protocol for querying and updating data, which can be freely incorporated in various kind of data access applications. OData makes it quite simple and flexible to use by applying and building upon existing well-defined technologies such as HTTP, XML, AtomPub, and JSON. WCF Data Services (formerly known as ADO.NET Data Services) is a well-encapsulated component for creating OData services based on the Microsoft .NET Framework platform. It also provides a client library with which you can easily build client applications that consume OData services. In addition to WCF Data Services, there are many other components or libraries, which make OData completely available to the non-.NET or even non-Microsoft world.

In this article by Steven Cheng, author of OData Programming Cookbook for .NET Developers, we will cover:

  • Accessing OData service with OData WP7 client library
  • Creating Panorama-style, data-driven Windows Phone applications with OData
  • Using HTML5 and OData to build native Windows Phone applications

With the continuous evolution of mobile operating systems, smart mobile devices (such as smartphones or tablets) play increasingly important roles in everyone's daily work and life. The iOS (from Apple Inc., for iPhone, iPad, and iPod Touch devices), Android (from Google) and Windows Phone 7 (from Microsoft) operating systems have shown us the great power and potential of modern mobile systems.

In the early days of the Internet, web access was mostly limited to fixed-line devices. However, with the rapid development of wireless network technology (such as 3G), Internet access has become a common feature for mobile or portable devices. Modern mobile OSes, such as iOS, Android, and Windows Phone have all provided rich APIs for network access (especially Internet-based web access). For example, it is quite convenient for mobile developers to create a native iPhone program that uses a network API to access remote RSS feeds from the Internet and present the retrieved data items on the phone screen. And to make Internet-based data access and communication more convenient and standardized, we often leverage some existing protocols, such as XML or JSON, to help us. Thus, it is also a good idea if we can incorporate OData services in mobile application development so as to concentrate our effort on the main application logic instead of the details about underlying data exchange and manipulation.
In this article, we will discuss several cases of building OData client applications for various kinds of mobile device platforms. The first four recipes will focus on how to deal with OData in applications running on Microsoft Windows Phone 7. And they will be followed by two recipes that discuss consuming an OData service in mobile applications running on the iOS and Android platforms. Although this book is .NET developer-oriented, since iOS and Android are the most popular and dominating mobile OSes in the market, I think the last two recipes here would still be helpful (especially when the OData service is built upon WCF Data Service on the server side).

Accessing OData service with OData WP7 client library

What is the best way to consume an OData service in a Windows Phone 7 application? The answer is, by using the OData client library for Windows Phone 7 (OData WP7 client library). Just like the WCF Data Service client library for standard .NET Framework based applications, the OData WP7 client library allows developers to communicate with OData services via strong-typed proxy and entity classes in Windows Phone 7 applications. Also, the latest Windows Phone SDK 7.1 has included the OData WP7 client library and the associated developer tools in it.
In this recipe, we will demonstrate how to use the OData WP7 client library in a standard Windows Phone 7 application.

Getting ready

The sample WP7 application we will build here provides a simple UI for users to view and edit the Categories data by using the Northwind OData service. The application consists of two phone screens, shown in the following screenshot:

Make sure you have installed Windows Phone SDK 7.1 (which contains the OData WP7 client library and tools) on the development machine. You can get the SDK from the following website:

http://create.msdn.com/en-us/home/getting_started

The source code for this recipe can be found in the \ch05\ODataWP7ClientLibrarySln directory.

How to do it...

  1. Create a new ASP.NET web application that contains the Northwind OData service.
    Add a new Windows Phone Application project in the same solution (see the following screenshot).

  2. Select Windows Phone OS 7.1 as the Target Windows Phone OS Version in the New Windows Phone Application dialog box (see the following screenshot).

  3. Click on the OK button, to finish the WP7 project creation.

    The following screenshot shows the default WP7 project structure created by Visual Studio:

  4. Create a new Windows Phone Portrait Page (see the following screenshot) and name it EditCategory.xaml.

  5. Create the OData client proxy (against the Northwind OData service) by using the Visual Studio Add Service Reference wizard.
  6. Add the XAML content for the MainPage.xaml page (see the following XAML fragment).

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <ListBox x:Name="lstCategories" ItemsSource="{Binding}"> <ListBox.ItemTemplate>> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="60" /> <ColumnDefinition Width="260" /> <ColumnDefinition Width="140" /> </Grid.ColumnDefinitions> <TextBlock Grid.Column="0" Text="{Binding Path=CategoryID}" FontSize="36" Margin="5"/> <TextBlock Grid.Column="1" Text="{Binding Path=CategoryName}" FontSize="36" Margin="5" TextWrapping="Wrap"/> <HyperlinkButton Grid.Column="2" Content="Edit" HorizontalAlignment="Right" NavigateUri="{Binding Path=CategoryID, StringFormat='/EditCategory.xaml? ID={0}'}" FontSize="36" Margin="5"/> <Grid> <DataTemplate> <ListBox.ItemTemplate> <ListBox> <Grid>

  7. Add the code for loading the Category list in the code-behind file of the MainPage. xaml page (see the following code snippet).

    public partial class MainPage : PhoneApplicationPage { ODataSvc.NorthwindEntities _ctx = null; DataServiceCollection _categories = null; ...... private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { Uri svcUri = new Uri("http://localhost:9188/NorthwindOData.svc"); _ctx = new ODataSvc.NorthwindEntities(svcUri); _categories = new DataServiceCollection(_ctx); _categories.LoadCompleted += (o, args) => { if (_categories.Continuation != null) _categories.LoadNextPartialSetAsync(); else { this.Dispatcher.BeginInvoke( () => { ContentPanel.DataContext = _categories; ContentPanel.UpdateLayout(); } ); } }; var query = from c in _ctx.Categories select c; _categories.LoadAsync(query); } }

  8. Add the XAML content for the EditCategory.xamlpage (see the following XAML fragment).

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <StackPanel> <TextBlock Text="{Binding Path=CategoryID, StringFormat='Fields of Categories({0})'}" FontSize="40" Margin="5" /> <Border> <StackPanel> <TextBlock Text="Category Name:" FontSize="24" Margin="10" /> <TextBox x:Name="txtCategoryName" Text="{Binding Path=CategoryName, Mode=TwoWay}" /> <TextBlock Text="Description:" FontSize="24" Margin="10" /> <TextBox x:Name="txtDescription" Text="{Binding Path=Description, Mode=TwoWay}" /> </StackPanel> </Border> <StackPanel Orientation="Horizontal" HorizontalAlignment="Center"> <Button x:Name="btnUpdate" Content="Update" HorizontalAlignment="Center" Click="btnUpdate_Click" /> <Button x:Name="btnCancel" Content="Cancel" HorizontalAlignment="Center" Click="btnCancel_Click" /> </StackPanel> </StackPanel> </Grid>

  9. Add the code for editing the selected Category item in the code-behind file of the EditCategory.xaml page.
    In the PhoneApplicationPage_Loaded event, we will load the properties of the selected Category item and display them on the screen (see the following code snippet).

    private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { EnableControls(false); Uri svcUri = new Uri("http://localhost:9188/NorthwindOData. svc"); _ctx = new ODataSvc.NorthwindEntities(svcUri); var id = int.Parse(NavigationContext.QueryString["ID"]); var query = _ctx.Categories.Where(c => c.CategoryID == id); _categories = new DataServiceCollection(_ctx); _categories.LoadCompleted += (o, args) => { if (_categories.Count <= 0) { MessageBox.Show("Failed to retrieve Category item."); NavigationService.GoBack(); } else { EnableControls(true); ContentPanel.DataContext = _categories[0]; ContentPanel.UpdateLayout(); } }; _categories.LoadAsync(query); }

    The code for updating changes (against the Category item) is put in the Click event of the Update button (see the following code snippet).

    private void btnUpdate_Click(object sender, RoutedEventArgs e) { EnableControls(false); _ctx.UpdateObject(_categories[0]); _ctx.BeginSaveChanges( (ar) => { this.Dispatcher.BeginInvoke( () => { try { var response = _ctx.EndSaveChanges(ar); NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative)); } catch (Exception ex) { MessageBox.Show("Failed to save changes."); EnableControls(true); } } ); }, null ); }

  10. Select the WP7 project and launch it in Windows Phone Emulator (see the following screenshot).

  11. Depending on the performance of the development machine, it might take a while to start the emulator.

Running a WP7 application in Windows Phone Emulator is very helpful especially when the phone application needs to access some web services (such as WCF Data Service) hosted on the local machine (via the Visual Studio test web server).

How it works...

Since the OData WP7 client library (and tools) has been installed together with Windows Phone SDK 7.1, we can directly use the Visual Studio Add Service Reference wizard to generate the OData client proxy in Windows Phone applications. And the generated OData proxy is the same as what we used in standard .NET applications. Similarly, all network access code (such as the OData service consumption code in this recipe) has to follow the asynchronous programming pattern in Windows Phone applications.

There's more...

In this recipe, we use the Windows Phone Emulator for testing. If you want to deploy and test your Windows Phone application on a real device, you need to obtain a Windows Phone developer account so as to unlock your Windows Phone device. Refer to the walkthrough:

App Hub - windows phone developer registration walkthrough,available at http://go.microsoft.com/fwlink/?LinkID=202697

OData Programming Cookbook for .NET Developers 70 fast-track, example-driven recipes with clear instructions and details for OData programming with .NET Framework with this book and ebook.
Published: July 2012
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

Consuming JSON-format OData service without OData WP7 client library

By using the OData WP7 client library, it is quite simple and straightforward to consume an OData service in Windows Phone applications. But, what if we do not want to use the OData WP7 client library and still want to query data entities from OData services? This might be the case if we want to avoid involving additional components/libraries (such as the OData client library) in our WP7 application. Well, we can use the WebClient class to issue raw OData query requests and manually parse the Atom XML format responses via LINQ to XML APIs. Then, what about JSON-format responses?

In this recipe, we will demonstrate how to build a WP7 OData client which consumes JSON format query responses without using the OData WP7 client library.

Getting ready

In this recipe, we will build a simple WP7 application that retrieves the Category list (in JSON format) from the Northwind OData service and displays it on the phone screen.

Make sure you have installed the Windows Phone SDK 7.1 (which contains the OData WP7 client library and tools) on the development machine. You can get the SDK from
http://create.msdn.com/en-us/home/getting_started.

The source code for this recipe can be found in the \ch05\SimpleODataWP7Sln directory.

How to do it...

  1. Create a new ASP.NET web application that contains the Northwind OData service.
  2. Create a new Windows Phone application (use Windows Phone OS 7.1).

    You can refer to the Accessing OData service with OData WP7 client library recipe in this article for detailed information.

  3. Add the following assembly references in the Windows Phone application:
    • System.Runtime.Serialization.dll
    • System.Servicemodel.Web.dll
  4. Create some helper classes for deserializing the JSON-format OData response (see the following code snippet).

    // For deserialize the response body public class CategoriesResponse { public List d { get; set; } } // For deserialize each Category entity public class CategoryObj { public string __metadata { get; set; } public int CategoryID { get; set; } public string CategoryName { get; set; } public string Description { get; set; } }

  5. Add the XAML content for the MainPage.xaml page (auto-generated in the project). The following is the main XAML fragment of the MainPage.xaml page in the sample application:

    <StackPanel x:Name="TitlePanel" Grid.Row="0" <Margin="12,17,0,28"> <TextBlock x:Name="ApplicationTitle" Text="Northwind Data Client" Style="{StaticResource PhoneTextNormalStyle}"/> <TextBlock x:Name="PageTitle" Text="Categories" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> </StackPanel> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <ListBox x:Name="lstCategories" ItemsSource="{Binding }"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" Margin="5"> <TextBlock Text="{Binding Path=CategoryID}" FontSize="54" Width="80" Height="80" /> <StackPanel Orientation="Vertical"> <TextBlock Text="{Binding Path=CategoryName}" FontSize="36" Margin="3" /> <TextBlock Text="{Binding Path=Description}" FontSize="14" /> </StackPanel> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Grid>

  6. Add the code for loading the Category list (from the Northwind OData service) in the code-behind file of the MainPage.xaml page.
    All the OData query and response processing code will be put in the PhoneApplicationPage_Loaded event (see the following code snippet).

    private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { WebClient wc = new WebClient(); wc.Headers[HttpRequestHeader.Accept] = "application/json"; Uri queryUri = new Uri("http://localhost:12040/NWDataService.svc/Categories? $select=CategoryID,CategoryName,Description"); wc.OpenReadCompleted += (src, args) => { using (var responseStream = args.Result) { DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof(CategoriesResponse)); var responseObj = ser.ReadObject(responseStream) as CategoriesResponse; if (responseObj != null) { LayoutRoot.DataContext = responseObj.d; lstCategories.UpdateLayout(); } else { MessageBox.Show("Failed to retrieve Category list."); } } }; wc.OpenReadAsync(queryUri); }

  7. Launch Windows Phone Application in Windows Phone Emulator (use the Ctrl + F5 or F5 shortcuts). The following screenshot shows the main screen of the sample phone application:

How it works...

The previous sample page uses the OpenReadAsync method of the WebClient class to send the raw OData query (which ensures the asynchronous network access). Also, we have specified the Accept HTTP header, so that the service will return a JSON-format response. After the response data arrives, we use the DataContractJsonSerializer class to deserialize the JSON-format response into strong-typed objects (based on the CategoriesResponse and CategoryObj helper classes we have defined).

By using Fiddler to capture the underlying HTTP response content (see the following screenshot), we find that the JSON object graph of the OData response exactly matches the helper classes we defined here.

And it is recommended that we use Fiddler to inspect the JSON response data of an OData service before we define the helper classes for data serialization/deserialization between OData response and .NET objects
Although we can use the WebClient + DataContractJsonSerializer approach to access an OData service, it is still quite cumbersome. In most cases, the OData WP7 client library is the preferred choice for consuming an OData service in Windows Phone applications.

See also

  • Accessing OData service with OData WP7 client library recipe
OData Programming Cookbook for .NET Developers 70 fast-track, example-driven recipes with clear instructions and details for OData programming with .NET Framework with this book and ebook.
Published: July 2012
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

Creating Panorama style data-driven Windows Phone application with OData

Windows Phone 7 brings out the new Panorama UI style to improve the user navigation experience on the phone screen. Unlike standard applications that are designed to fit within the confines of the phone screen, WP7 applications with Panorama UI style offer a unique way to view data and resources by using a long horizontal canvas that extends beyond the confines of the screen. For WP7 data-driven applications, Panorama-style UI is extremely useful for presenting data that can be divided into multiple groups or partitions. In this recipe, we will show you how to use an OData service as the data source for building a WP7 Panorama-style, data-driven application.

 

Getting ready

Here, we will build a Panorama-style WP7 application to present the Northwind Categories and Products data (by using the Northwind OData service). In the application, each Category and its associated Product list will be displayed in a separate Panorama page, so that the user can swipe the phone screen, to navigate between them (see the following screenshot).

Make sure you have installed Windows Phone SDK 7.1 (which contains the OData WP7 client library and tools) on the development machine. You can get the SDK from the website o http://create.msdn.com/en-us/home/getting_started.

The source code for this recipe can be found in the \ch05\ ODataWP7PanoramaSln directory.

How to do it...

  1. Create a new ASP.NET web application that contains the Northwind OData service.
  2. Create a new Windows Phone application (use Windows Phone OS 7.1).
  3. You can refer to the Accessing OData service with OData WP7 client library recipe in this article for detailed information.

  4. Add the assembly reference, Microsoft.Phone.Controls.dll, in the Windows Phone Application.
  5. Create the OData client proxy (against the Northwind OData service) by using the Visual Studio Add Service Reference wizard.
  6. Add the XML namespaces for the Panorama Control in the XAML file of the MainPage.xaml page (see the following XAML fragment).

    <phone:PhoneApplicationPage x:Class="ODataWP7PanoramaApp.MainPage" ... xmlns:controls="clr-namespace:Microsoft.Phone. Controls;assembly=Microsoft.Phone.Controls" xmlns:shell="clr-namespace:Microsoft.Phone. Shell;assembly=Microsoft.Phone" ... >

  7. Add the Panorama Control under the default Grid container Control in the XAML file of the MainPage.xml page (see the following XAML fragment).

    <Grid x:Name="LayoutRoot" Background="Transparent"> <controls:Panorama x:Name="MainPanel" Background="Purple" Title="OData Panorama Demo" ItemsSource="{Binding}" > <controls:Panorama.HeaderTemplate> <DataTemplate> <TextBlock Text="{Binding Path=CategoryName}" FontSize="54" FontWeight="Bold" /> </DataTemplate> </controls:Panorama.HeaderTemplate> <controls:Panorama.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Path=CategoryName, StringFormat='Products under {0}:'}" FontSize="32" Margin="10" /> <ListBox ItemsSource="{Binding Path=Products}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Path=ProductID}" Margin="10,5,15,5" Width="50" /> <TextBlock Text="{Binding Path=ProductName}" Margin="5" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </StackPanel> </DataTemplate> </controls:Panorama.ItemTemplate> <controls:PanoramaItem> <ProgressBar IsIndeterminate="True" /> </controls:PanoramaItem> </controls:Panorama> </Grid> ;

  8. Add the code for loading the Category and Product entities in the code-behind file of the MainPage.xaml page (see the following code snippet).

    public partial class MainPage : PhoneApplicationPage { ...... private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { var svcUri = new Uri("http://localhost:11904/NWDataService.svc"); var ctx = new NorthwindEntities(svcUri); var Categories = new DataServiceCollection(ctx); Categories.LoadCompleted += (o, args) => { if (args.Error != null) { MessageBox.Show("Failed to retrieve data."); return; } if (Categories.Continuation != null) Categories.LoadNextPartialSetAsync(); else { this.Dispatcher.BeginInvoke(() => { MainPanel.Items.Clear(); MainPanel.DataContext = Categories; }); } }; var query = ctx.Categories.Expand("Products"); Categories.LoadAsync( query ); }

    ......

How it works...

There is only one page (MainPage.xaml) in the same WP7 project. This page uses the Panorama Control (in the Microsoft.Phone.Controls assembly) provided by Windows Phone SDK to present the OData entities. When the application starts and displays the MainPage.xaml page, the PhoneApplicationPage_Loaded event is fired so as to retrieve the Category and Product lists from the Northwind OData service. After the data entities get loaded, we directly assign the data container (of the DataServiceCollection class) to the Panorama Control's DataContext property (so as to trigger data binding). According to the data binding template in the XAML file, each Category entity (and its associated Product entities) will be bound to a separate PanoramaItem Control (inside the Panorama Control). Thus, users can flick the phone screen to explore each Category (and Products under the Category), one by one.

If you prefer using code instead of data binding, you can also programmatically create the PanoramaItem Controls based on the Category entity collection (see the following code snippet).

void PopulatePanoramaItemsWithCode (DataServiceCollection categories) { foreach (var category in categories) { var panelItem = new PanoramaItem(); panelItem.Content = new CustomUserControl(); panelItem.DataContext = category; MainPanel.Items.Add(panelItem); } }

For more information about the WP7 Panorama Control, you can refer to the following MSDN reference:

Panorama Control Overview for Windows Phone available at http://msdn.microsoft.com/en-us/library/ff941104(v=vs.92).

See also

  • Accessing OData service with OData WP7 client library recipe

Summary

OData on Mobile Devices, demonstrates how to use OData services in mobile application development.In the first recipe, we learned how to use the OData WP7 client library in a standard Windows Phone 7 application.In the second recipe, we learned how to build a WP7 OData client which consumes JSON format query responses without using the OData WP7 client library.We also saw the main screen of the sample phone application.In the third recipe, we learned the use of an OData service as the data source for building a WP7 Panorama-style, data-driven application. We saw how user can navigate each Category and its associated Product list in a separate page.


Further resources on this subject:


 

 

About the Author :


Steven Cheng

Steven Cheng is a senior support engineer at Microsoft Global Technical Support Center where he has been supporting Microsoft software development technologies for more than 5 years. Currently, as a community leader, he is working actively in the MSDN newsgroup and forum communities.

Steven Cheng's technical specialties cover many popular areas of Microsoft development technologies including .NET framework, ASP.NET, XML WebService, Windows Communication Foundation, SharePoint development, and so on. His blog can be found at http://blogs.msdn.com/stcheng.

Books From Packt


Android Database Programming
Android Database Programming

Flash iOS Apps Cookbook
Flash iOS Apps Cookbook

Microsoft Silverlight 4 Data and Services Cookbook
Microsoft Silverlight 4 Data and Services Cookbook

Windows Phone 7 Silverlight Cookbook
Windows Phone 7 Silverlight Cookbook

OCA Oracle Database 11g: SQL Fundamentals I: A Real World Certification Guide ( 1ZO-051 )
OCA Oracle Database 11g: SQL Fundamentals I:A Real World Certification Guide ( 1ZO-051 )

Microsoft Silverlight 4 and SharePoint 2010 Integration
Microsoft Silverlight 4 and SharePoint 2010 Integration

Microsoft Silverlight 5 Data and Services Cookbook
Microsoft Silverlight 5 Data and Services Cookbook

Getting Started with Oracle Data Integrator 11g: A Hands-On Tutorial
Getting Started with Oracle Data Integrator 11g: A Hands-On Tutorial


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
5
H
F
g
4
Q
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software