How to consume WCF REST Service with JSON in Windows Phone 7

In this post I will show you the way to consume JSON WCF REST Service in Windows Phone 7. This post is divided into four parts.

  1. Creating simple WCF REST Service for ADD
  2. Consuming JSON REST Service in Windows Phone 7 application.
  3. Creating complex WCF REST Service with custom classes and types.
  4. Consuming complex JSON REST Service in Windows Phone 7 application.

Creating simple Add Service

To start with let us create a WCF REST Service returning JSON as below. There is one operation contact named Add in the service and that is taking two strings as input parameters and returning integer.


[ServiceContract]
public interface IService2
{

[OperationContract]
[WebGet(UriTemplate="/Add/{Number1}/{Number2}",RequestFormat=WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json
)]
int Add(string  Number1, string Number2);

}

Service is implemented as below,


using System;

namespace MultipleBindingWCF
{

public class Service1 : IService2
{

public int Add(string Number1, string Number2)
{
int num1 = Convert.ToInt32(Number1);
int num2 = Convert.ToInt32(Number2);
return num1 + num2;
}

}
}

Next in this section we need to configure service. We need to configure service webHttpBinding to eanble it as REST Service. So in Web.Config we need to do the below changes.


<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name ="servicebehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restbehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<endpoint name ="RESTEndPoint"
contract ="MultipleBindingWCF.IService2"
binding ="webHttpBinding"
address ="rest"
behaviorConfiguration ="restbehavior"/>
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>

After configuring, Service ready for hosting. You are free to host it either on Azure, IIS, or Cassini. For local ASP.Net Server hosting press F5. Do a testing of service in browser and if you are getting expected output, you are good to consume it in the Windows Phone 7 application.

Consuming Service in Windows Phone 7

To consume REST Service in Windows Phone 7 and then parse JSON, you need to add below references in Windows Phone 7 project.

 

 

 

As the design of the page I have put two textbox and one button. User will input numbers to be added in the textbox and on click event of button result would get displayed in message box. Essentially on click event of the button we will make a call to the service. Design of the page is as below,


<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="calling JSON REST" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="JSON REST" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBox x:Name="txtNumber1" Height="100" Margin="-6,158,6,349" />
<TextBox x:Name="txtNumber2" Height="100" Margin="-6,28,6,479" />
<Button x:Name="btnAdd" Height="100" Content="Add" Click="btnAdd_Click"/>
</Grid>
</Grid>

On click event of the button we need to make a call to the service as below,

clip_image002

And ServiceURi is constructed as below,

clip_image004

There is nothing much fancy about above service call. We are just downloading JSON as string using WebClient. However parsing of JSON is main focus of this post. To parse we need to write below code in completed event.

clip_image006

In above code

  • Converting downloaded string as Stream
  • Creating instance of DataContractJsonSerializer. In that we are passing type as string since returned type of service is string.
  • Reading stream into instance of DataContractJsonSerializer
  • Displaying the result.

Putting all code together you should have below code to make a call and parse JSON in windows phone 7


using System;
using System.Net;
using System.Windows;
using Microsoft.Phone.Controls;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;

namespace ConsumingJSON
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}

private void btnAdd_Click(object sender, RoutedEventArgs e)
{

string Number1 = txtNumber1.Text;
string Number2 = txtNumber2.Text;
string ServiceUri = "http://localhost:30576/Service1.svc/Rest/add/"
+ Number1 + "/"
+ Number2;
WebClient proxy = new WebClient();
proxy.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
proxy.DownloadStringAsync(new Uri(ServiceUri));

}

void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Stream stream = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(string));
string result = obj.ReadObject(stream).ToString();
MessageBox.Show(result);
}
}
}

Creating complex Service with custom classes and types

Go back to service and add a custom class as below,

[DataContract]
public class Student
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string RollNumber { get; set; }
[DataMember]
public string Grade { get; set; }
}

And add one more function to service. This operation contract will return List of Students.


[OperationContract]
[WebGet(UriTemplate = "/GetStudents", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json
)]
List<Student> GetStudents();

Next you need to implement service as below,


public List<Student> GetStudents()
{
List<Student> lstStudent = new List<Student>
{
new Student { Name = "John " ,RollNumber = "1" , Grade = "A"},
new Student { Name = "Dan " ,RollNumber = "2" , Grade = "Q"},
new Student { Name = "Pinal " ,RollNumber = "3" , Grade = "M"},
new Student { Name = "Mahesh " ,RollNumber = "4" , Grade = "Z"},
new Student { Name = "Julie" ,RollNumber = "5" , Grade = "L"},
};
return lstStudent;
}

Configuration will be the same as of simple REST Service returning JSON. Press F5 to host and test the service.

Consuming complex JSON REST Service in Windows Phone 7 application

At the Windows Phone 7 application, you need to create entity class. This class will be representing Student class of service. Add Student class to project as below,


public class Student
{
public string Name { get; set; }
public string RollNumber { get; set; }
public string Grade { get; set; }

}

Design page as below. I have put a button and on click event of the button service will get called and returned data would be bind to the listbox.


<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="110" />
</Grid.RowDefinitions>
<ListBox x:Name="lstStudents" Height="auto" Width="auto" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Name}" Style="{StaticResource PhoneTextTitle2Style}"  />
<TextBlock Text="{Binding RollNumber}" Style="{StaticResource PhoneTextTitle3Style}" />
<TextBlock Text="{Binding Grade}" Style="{StaticResource PhoneTextAccentStyle}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

<Button Grid.Row="1" x:Name="btnAdd" Height="100" Content="Add" Click="btnAdd_Click"/>
</Grid>

In the code behind on click event of the button we need to make call using WebClient again


private void btnAdd_Click(object sender, RoutedEventArgs e)
{
WebClient proxy = new WebClient();
proxy.DownloadStringCompleted += new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
proxy.DownloadStringAsync(new Uri("http://localhost:30576/Service1.svc/rest/getstudents"));

}

And need to parse the returned JSON as below. In parameter to create instance of DataContractJsonSrrializer we are passing List of Student.


void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Stream stream = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(List<Student>));
List<Student> result = obj.ReadObject(stream) as List<Student>;
lstStudents.ItemsSource = result;
}

On running you should be getting output as below.

image

In this way you can work with WCF REST with JSON Data and Windows Phone 7. I hope this post is is useful. Thanks for reading

8 responses to “How to consume WCF REST Service with JSON in Windows Phone 7”

  1. […] Kumar (@debug_mode) described How to consume WCF REST Service with JSON in Windows Phone 7 in a 12/22/2011 post: In this post I will show you the way to consume JSON WCF REST Service in […]

  2. […] How to consume WCF REST Service with JSON in Windows Phone 7 […]

  3. I recreate your example.
    Everything works fine.
    Next step, I build that WCF Rest Service over HTTPS.
    I change the settings in IIS. Create a self-sign-Certificate. Change from port 80 to 443 and so on…
    In the Browser i have no Problmen to Consume it over HTTPS.
    But on Windows Phone over WebClient I can’t consume it.
    What settings on Windows Phone I must change to consume the new WCF Rest Service?
    Have you any idea?

  4. How to make a post service passing a List to be added in the wcf restful service? In Android I set the

    DefaultHttpClient gethttpClient;

    StringEntity sentity = new StringEntity(toJSONStringAr());
    getrequest.setEntity(sentity);

    How to Do It in your example?

  5. […] more about How to consume WCF REST Service with JSON in Windows Phone 7 @debug_mode Related Articles:How to check application returning from dormant state in Windows Phone 7 – […]

  6. Oleksandr Mykhaylyshyn

    to use ssl in windows phone you need to install certificate directly on device

  7. Hi There,

    I am given an endpoint where the webservice is hosted. Now I use the endpoint as service reference in my C# solution and access the request and response methods of the webservice.

    I am instantiating the classes and passing values to its methods directly like below:

    SendNotificationRequestType orequest = new SendNotificationRequestType();
    orequest.subject = tempSubject;
    orequest.payload = tempPayload;

    sendNotificationRequest oreq = new sendNotificationRequest(orequest);

    ” I assumed that calling the methods this way and passing the values will send the request to the endpoint directly.” But if it reached it would send a response over sendResponseType method with attributes as statusID and Statusmsg”

    I had a discussion and found the request needs to go via a channel and response fetched from the same channel.
    But how is my question. If you could help me in this.

    Thanks in advance.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com