Consuming basic REST service in Windows Phone 7 Application

No.of Views921
Bookmarked0 times
Downloads 
Votes0
By  Dhananjay Kumar   On  23 Apr 2010 09:04:22
Tag : Windows Phone , Utilities
In this article I am going to explain how to consume a REST service in windows 7 phone application
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Objective

In this article I am going to explain how to consume a REST service in windows 7 phone app.
 We will achieve this is two steps
1.    Create and Host REST based WCF service
2.    Consume service in W7 phone application.
 

Create and host REST service

 What I am going to do is to create a very simple REST service.  Service will have one operation contract. This will take one string as input and return greeting message appending the string.
1.    Open visual studio and from File menu select new project.  Go to WCF tab and select WCF service application.
2.    Open Web.Config file and inside System.Servicemodel delete any existing endpoint settings.
3.    Right click on your .svc file and select view markup. 
 

Image Loading

Add as a Factory class to the markup of the service System.ServiceModel.Activation.WebServiceHostFactory. after adding markup should look like below 

Image Loading

4.    Define the contract. There is one operation contract. This will take a string as input parameter and return a string.   

Image Loading

In WebGet attribute all settings are default for XML return and response.  URI for the operation will be
http://hostserver:port/Service1.svc/GetData/[parameter] so if you want to pass your name as parameter then URL would be http://hostserver:port/Service1.svc/GetData/DhananjayKumar

5.    Run the WCF service or right click on .svc file and select view in browser. Once you will run , you will see the below output
 

Image Loading

In address bar of browser you can see the URL and XML output would be as below

 

Image Loading

6.    We are going to host the service for our sample in Cassini server.For reference complete code for Web.Config , Contract and Service definition is as below


Contract (IService1.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace RESTtoConsumeinWindwPhone
{
   
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet(UriTemplate="GetData/{a}",
            RequestFormat=WebMessageFormat.Xml  ,
            ResponseFormat=WebMessageFormat.Xml,
            BodyStyle=WebMessageBodyStyle.Bare)]
        String GetData(string a);
   
   }
   
}

Service Definition (Service1.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace RESTtoConsumeinWindwPhone
{   
    public class Service1 : IService1
    {
        public String GetData(string a)
        {
            return "Hello " + a + "From REST Service "; 
        }         
    }
}


Web.Config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
         <serviceMetadata httpGetEnabled="true"/>          
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>  
</configuration>

Consuming REST service in Window 7 Phone application

Very first create Windows Phone Application.  From Silverlight for Windows Phone tab select Windows Phone Application project type.
1.    In content grid place  a textbox and a button.
2.    User will eneter text and on clcik event we will pass this text to service and display retrun string into a message box.  I am not designing the page very much it’s a very simple page.
  

Image Loading

 

MainPage.Xaml.cs

<phoneNavigation:PhoneApplicationPage 
    x:Class="RESTServiceConsuming.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phoneNavigation="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Navigation"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="800"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}">
    <Grid x:Name="LayoutRoot" Background="{StaticResource PhoneBackgroundBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>       
        <Grid x:Name="TitleGrid" Grid.Row="0">
            <TextBlock Text="MY APPLICATION" x:Name="textBlockPageTitle" Style="{StaticResource PhoneTextPageTitle1Style}"/>
            <TextBlock Text="page title" x:Name="textBlockListTitle" Style="{StaticResource PhoneTextPageTitle2Style}"/>
        </Grid>       
        <Grid x:Name="ContentGrid" Grid.Row="1">
            <Button x:Name="myButton" Height="75" Content="Call REST service" Margin="99,197,124,381" />
            <TextBox x:Name="myTxtBox" Height="31" HorizontalAlignment="Left" Margin="20,96,0,0"  Text=" " VerticalAlignment="Top" Width="434" FontFamily="Verdana" Foreground="#FFCB4B4B" FontSize="32" />
            <TextBox x:Name="myTxtBoxDisplay" Height="31" HorizontalAlignment="Left" Text=" " VerticalAlignment="Top" Width="434" FontFamily="Verdana" Foreground="#FFCB4B4B" FontSize="20" Margin="20,319,0,0" />
        </Grid>
    </Grid>   
</phoneNavigation:PhoneApplicationPage>

 

 Now I will be consuming REST service on click event of button.
1.    Using WebClient class will make the asynchronous calls.
2.    On returning of the response as stream using DataContractSerliazer , I will de serialize  the returned stream.

Image Loading

3.    While constructing the URL to be called append input parameter. I am taking input parameter here from textbox. 

Image Loading

MainPage.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml;
using System.Runtime.Serialization; 


namespace RESTServiceConsuming
{
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();

            SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

            myButton.Click += new RoutedEventHandler(myButton_Click);
        }

        void myButton_Click(object sender, RoutedEventArgs e)
        {
            WebClient proxy = new WebClient();
            string strUri = "http://localhost:50841/Service1.svc/GetData/"+myTxtBox.Text;
            proxy.OpenReadCompleted+=new OpenReadCompletedEventHandler(proxy_OpenReadCompleted);
            proxy.OpenReadAsync(new Uri(strUri)); 
        }

        void proxy_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {          

            DataContractSerializer ser = new DataContractSerializer(typeof(string)); 
            String str = ser.ReadObject(e.Result).ToString();
            myTxtBoxDisplay.Text = str;       
        }      
    }
}

Press F5 to get the result

Image Loading

Conclusion

in this article I explained about how to consume a REST service in Win7 mobile app.  In later articles I shall explain image and streaming through REST service in Win7 mobile app. Thanks for reading. I hope it was useful. Happy Coding.

 
Sign Up to vote for this article
 
About Author
 
Dhananjay Kumar
Occupation-Software Engineer
Company-Infosys Technolgies,Pune
Member Type-Gold
Location-India
Joined date-20 Jul 2009
Home Page-http://dhananjaykumar.net/
Blog Page-http://dhananjaykumar.net/
Dhananjay Kumar is Microsoft MVP on connected system. He blogs at http://dhananjaykumar.net/ . You can follow him http://twitter.com/debugmode_/ and reach him at dhananjay.25july@gmail.com
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top