Windows phone application example

Calling Web API from a Windows Phone 8 Application (C#)

In this tutorial, you will learn how to create a complete end-to-end scenario consisting of an ASP.NET Web API application that provides a catalog of books to a Windows Phone 8 application.

Overview

RESTful services like ASP.NET Web API simplify the creation of HTTP-based applications for developers by abstracting the architecture for server-side and client-side applications. Instead of creating a proprietary socket-based protocol for communication, Web API developers simply need to publish the requisite HTTP methods for their application, (for example: GET, POST, PUT, DELETE), and client application developers only need to consume the HTTP methods that are necessary for their application.

In this end-to-end tutorial, you will learn how to use Web API to create the following projects:

  • In the first part of this tutorial, you will create an ASP.NET Web API application that supports all of the Create, Read, Update, and Delete (CRUD) operations to manage a book catalog. This application will use the Sample XML File (books.xml) from MSDN.
  • In the second part of this tutorial, you will create an interactive Windows Phone 8 application that retrieves the data from your Web API application.

Prerequisites

  • Visual Studio 2013 with the Windows Phone 8 SDK installed
  • Windows 8 or later on a 64-bit system with Hyper-V installed
  • For a list of additional requirements, see the System Requirements section on the Windows Phone SDK 8.0 download page.

If you are going to test the connectivity between Web API and Windows Phone 8 projects on your local system, you will need to follow the instructions in the Connecting the Windows Phone 8 Emulator to Web API Applications on a Local Computer article to set up your testing environment.

Step 1: Creating the Web API Bookstore Project

The first step of this end-to-end tutorial is to create a Web API project that supports all of the CRUD operations; note that you will add the Windows Phone application project to this solution in Step 2 of this tutorial.

Open Visual Studio 2013.

Click File, then New, and then Project.

When the New Project dialog box is displayed, expand Installed, then Templates, then Visual C#, and then Web.

Click image to expand

Highlight ASP.NET Web Application, enter BookStore for the project name, and then click OK.

When the New ASP.NET Project dialog box is displayed, select the Web API template, and then click OK.

Click image to expand

When the Web API project opens, remove the sample controller from the project:

  1. Expand the Controllers folder in the solution explorer.
  2. Right-click the ValuesController.cs file, and then click Delete.
  3. Click OK when prompted to confirm the deletion.

Add an XML data file to the Web API project; this file contains the contents of the bookstore catalog:

Right-click the App_Data folder in the solution explorer, then click Add, and then click New Item.

When the Add New Item dialog box is displayed, highlight the XML File template.

Name the file Books.xml, and then click Add.

When the Books.xml file is opened, replace the code in the file with the XML from the sample books.xml file on MSDN:

Save and close the XML file.

Add the bookstore model to the Web API project; this model contains the Create, Read, Update, and Delete (CRUD) logic for the bookstore application:

Right-click the Models folder in the solution explorer, then click Add, and then click Class.

When the Add New Item dialog box is displayed, name the class file BookDetails.cs, and then click Add.

When the BookDetails.cs file is opened, replace the code in the file with the following:

Save and close the BookDetails.cs file.

Add the bookstore controller to the Web API project:

Right-click the Controllers folder in the solution explorer, then click Add, and then click Controller.

When the Add Scaffold dialog box is displayed, highlight Web API 2 Controller — Empty, and then click Add.

When the Add Controller dialog box is displayed, name the controller BooksController, and then click Add.

When the BooksController.cs file is opened, replace the code in the file with the following:

Save and close the BooksController.cs file.

Build the Web API application to check for errors.

Step 2: Adding the Windows Phone 8 Bookstore Catalog Project

The next step of this end-to-end scenario is to create the catalog application for Windows Phone 8. This application will use the Windows Phone Databound App template for the default user interface, and it will use the Web API application that you created in Step 1 of this tutorial as the data source.

Right-click the BookStore solution in the in the solution explorer, then click Add, and then New Project.

When the New Project dialog box is displayed, expand Installed, then Visual C#, and then Windows Phone.

Highlight Windows Phone Databound App, enter BookCatalog for the name, and then click OK.

Add the Json.NET NuGet package to the BookCatalog project:

  1. Right-click References for the BookCatalog project in the solution explorer, and then click Manage NuGet Packages.
  2. When the Manage NuGet Packages dialog box is displayed, expand the Online section, and highlight nuget.org.
  3. Enter Json.NET in the search field and click the search icon.
  4. Highlight Json.NET in the search results, and then click Install.
  5. When the installation has completed, click Close.

Add the BookDetails model to the BookCatalog project; this contains a generic model of the bookstore class:

Right-click the BookCatalog project in the solution explorer, then click Add, and then click New Folder.

Name the new folder Models.

Right-click the Models folder in the solution explorer, then click Add, and then click Class.

When the Add New Item dialog box is displayed, name the class file BookDetails.cs, and then click Add.

When the BookDetails.cs file is opened, replace the code in the file with the following:

Save and close the BookDetails.cs file.

Update the MainViewModel.cs class to include the functionality to communicate with the BookStore Web API application:

Expand the ViewModels folder in the solution explorer, and then double-click the MainViewModel.cs file.

When the MainViewModel.cs file is opened, replace the code in the file with the following; note that you will need to update the value of the apiUrl constant with the actual URL of your Web API:

Save and close the MainViewModel.cs file.

Update the MainPage.xaml file to customize the application name:

Double-click the MainPage.xaml file in the solution explorer.

When the MainPage.xaml file is opened, locate the following lines of code:

Replace those lines with the following:

Save and close the MainPage.xaml file.

Update the DetailsPage.xaml file to customize the displayed items:

Double-click the DetailsPage.xaml file in the solution explorer.

When the DetailsPage.xaml file is opened, locate the following lines of code:

Replace those lines with the following:

Save and close the DetailsPage.xaml file.

Build the Windows Phone application to check for errors.

Step 3: Testing the End-to-End Solution

As mentioned in the Prerequisites section of this tutorial, when you are testing the connectivity between Web API and Windows Phone 8 projects on your local system, you will need to follow the instructions in the Connecting the Windows Phone 8 Emulator to Web API Applications on a Local Computer article to set up your testing environment.

Once you have the testing environment configured, you will need to set the Windows Phone application as the startup project. To do so, highlight the BookCatalog application in the solution explorer, and then click Set as StartUp Project:

Click image to expand

When you press F5, Visual Studio will start both the Windows Phone Emulator, which will display a «Please Wait» message while the application data is retrieved from your Web API:

Click image to expand

If everything is successful, you should see the catalog displayed:

Click image to expand

If you tap on any book title, the application will display the book description:

Click image to expand

If the application cannot communicate with your Web API, an error message will be displayed:

Click image to expand

If you tap on the error message, any additional details about the error will be displayed:

Примеры приложений для Windows Get Windows app samples

Многие официальные примеры кода Windows доступны в различных репозиториях GitHub, включая примеры приложений универсальной платформы Windows (UWP), примеры классических приложений для Windows и коллекцию примеров, рассматриваемых в документации для разработчиков Windows. Many official Windows code samples are available in various GitHub repositories, including Universal Windows Platform (UWP) app samples, Windows classic samples, along with a collection of Windows developer documentation samples. В этих примерах демонстрируется, как применяются большинство функций Windows и их API. These samples demonstrate most Windows features and their API use patterns.

Чтобы немного упростить поиск конкретных примеров, используйте упорядоченную коллекцию, доступную в обозревателе примеров кода. В ней вы сможете просмотреть и найти различные технологии и средства для разработчиков Майкрософт. To make finding specific samples a little bit easier, you can browse and search a categorized collection of code samples for various Microsoft developer tools and technologies through the sample browser.

Примеры, рассматриваемые в документации для разработчиков Windows Windows developer documentation samples

Ниже приведен список примеров мини-приложений, созданных специально для поддержки документации для разработчиков Windows. Here’s a list of mini-app samples created specifically to support Windows developer documentation. Если не указано иное, все следующие примеры представляют собой приложения UWP, которые обновлены для использования элементов управления последней версии WinUI 2.4. Unless noted, the following samples are all Universal Windows Platform (UWP) apps that have been updated to use the latest WinUI 2.4 controls.

  • RSS Reader — получение сведений о RSS-каналах и просмотр статей. Rss Reader — Retrieve RSS feeds and view articles
  • Family Notes — изучение различных модальностей ввода и сценариев узнавания пользователей. Family Notes — Explore different input modalities and scenarios of user awareness
  • Customer Orders — демонстрация функций, полезных для корпоративных разработчиков, например аутентификации Azure Active Directory (AAD), элементов управления пользовательского интерфейса (включая сетку данных), интеграция Sqlite и Базы данных SQL Azure, Entity Framework и облачные службы API. Customer Orders — Features useful to enterprise developers, like Azure Active Directory (AAD) authentication, UI controls (including a data grid), Sqlite and SQL Azure database integration, Entity Framework, and cloud API services
  • Lunch Scheduler — планирование обедов с друзьями и коллегами. Lunch Scheduler — Schedule lunches with your friends and coworkers
  • Coloring Book — демонстрация работы Windows Ink (в том числе панели инструментов Windows Ink) и функций радиального контроллера (для устройств Wheel, например Surface Dial). Coloring Book — Windows Ink (including the Windows Ink Toolbar) and radial controller (for Wheel devices such as the Surface Dial) features
  • Network Helper (Quiz Game) — обнаружение сетей и реализация обмена данными. Network Helper (Quiz Game) — Network discovery and communication
  • HUE Lights Controller — интеллектуальная система домашней автоматики с использованием Кортаны и технологии Bluetooth Low Energy (Bluetooth LE). HUE Lights Controller — Intelligent home automation with Cortana and Bluetooth Low Energy (Bluetooth LE)
  • Marble Maze — простая трехмерная игра с использованием DirectX. Marble Maze — Basic 3D game using DirectX
  • PhotoLab — просмотр и изменение файлов изображений. PhotoLab — View and edit image files

Скачать код Download the code

Чтобы скачать примеры, перейдите в один из репозиториев Майкрософт, например репозиторий с примерами приложений универсальной платформы Windows (UWP). To download the samples, go to one of the Microsoft repos such as Universal Windows Platform (UWP) app samples. Выберите Clone or download (Клонировать или скачать), а затем — Download ZIP (Скачать ZIP-файл). Select Clone or download, and then select Download ZIP.

В ZIP-файле для скачивания всегда содержатся последние версии примеров. The samples download .zip file always has the latest samples. Для скачивания файла не требуется учетная запись GitHub. You don’t need a GitHub account to download the file. Если выпущено обновление SDK или необходимо получить только последние изменения и добавления, просто скачайте актуальный ZIP-файл. When an SDK update is released or if you want to pick up any recent changes and additions, just download the latest zip file.

Для открытия, создания и запуска примеров Windows требуется Visual Studio и пакет Windows SDK. To open, build, and run Windows samples, you must have Visual Studio and the Windows SDK. Вы можете получить бесплатную копию Visual Studio Community. You can get a free copy of Visual Studio Community.

Для правильной работы примеров нужно распаковать весь архив, а не только отдельные примеры. For the samples to work correctly, be sure to unzip the entire archive and not individual samples. Большинство примеров зависят от общих файлов из папки SharedContent и используют связанные файлы, включая файлы шаблонов примеров и ресурсы изображений, чтобы уменьшить дублирование общих файлов. Many of the samples depend on common files in the SharedContent folder and use linked files, including sample template files and image assets, to reduce duplication.

Открытие примеров Open the samples

Скачайте ZIP-файл и откройте примеры в Visual Studio. After you download the .zip file, open the samples in Visual Studio.

Прежде чем распаковывать архив, щелкните файл правой кнопкой мыши и выберите Свойства > Разблокировать > Применить. Before you unzip the archive, right-click the file, select Properties > Unblock > Apply. Затем распакуйте архив в локальную папку на компьютере. Then, unzip the archive in a local folder on your computer.

Каждая папка в папке Samples содержит пример функции Windows. Each folder in the Samples folder contains a Windows feature sample.

Выберите пример. Select a sample. Поддерживаемые языки обозначаются вложенной папкой для конкретного языка. Supported languages are indicated by a language-specific sub-folder.

Выберите папку для языка, который нужно использовать. Select the folder for the language you want to use. В содержимом папки вы увидите файл решения Visual Studio (с расширением .sln), который можно открыть в Visual Studio. In the folder contents, you’ll see a Visual Studio solution (.sln) file that you can open in Visual Studio.

Обратная связь, вопросы и сообщения о проблемах Give feedback, ask questions, and report issues

Если у вас возникают проблемы или вопросы, перейдите на вкладку Issues (Проблемы) репозитория, чтобы создать запрос. If you have problems or questions, use the Issues tab in the repository to create a new issue.

Читайте также:  Hp laserjet p1505 windows 10 64 bit
Оцените статью