Code to Share Status or Links on Social Media sites in Windows Phone

While creating application for Windows Phone you may come across requirement to share certain message from your application on social media sites configured on user device. You can do it using ShareStaus Task. ShareStausTask class is defined as below. It is inherited from ShareTaskBase class.

image

 

ShareStatus Task Launcher allows an application to launch a dialog that allows user to share status message on social network site.

A status message can be shared as below,


ShareStatusTask shareStatusTask = new ShareStatusTask();
shareStatusTask.Status = "Hey I am Shared By DebugMode";
shareStatusTask.Show();


You may come across other scenario where you may need to share HyperLink across Social Media sites from your application. You can do that using launcher ShareLinkTask.

ShareLinkTask class is defined as below,

image

ShareLink Task Launcher allows an application to launch a dialog that allows user to share links on social network site.

A link can be shared as below,



ShareLinkTask shareLinkTask = new ShareLinkTask();
shareLinkTask.Title = "DebugMode";
shareLinkTask.LinkUri = new Uri("http://debugmode.net", UriKind.Absolute);
shareLinkTask.Message = "Post of DebugMode.";
shareLinkTask.Show();

These launchers will be launched only if user has configured social media sites on their device. I hope this post is useful. Thanks for reading.

How to launch Call Task from Secondary Tile in Windows Phone 7

Recently I got a mail from one of the reader. She asked; How could be launch Call Task from Secondary Tile? In this post I am going to show the way to do that. Before you go ahead with this post, I strongly recommend reading below three posts for more on Live Tiles and Call Task.

Video on How to work with Live Tiles in Windows Phone 7

Live Tiles in Windows Phone 7.5 or Mango phone

Code to make call in Windows Phone 7

Delete Secondary Tiles in Windows Phone 7.5 or Mango Phone

Idea of launching Call Task from Secondary Tiles is very simple.

  1. On clicking of Secondary Tile user will get navigated to a blank page. Let us call that page as Page1.XAML
  2. On NavigatedTo method of the Page1.Xaml, we will instantiate Call Task and show call panel to user.

Let us create Secondary Tile on MainPage.Xaml. I have put a button on MainPage and on click event of the button Secondary Tile will get created.


private void btnCreateSecondaryTiles_Click(object sender, RoutedEventArgs e)
{

var newTile = new StandardTileData()
{
Title = "Blogs Update",
BackgroundImage = new Uri("background.png", UriKind.Relative),
Count = 42,
};
var uri = "/Page1.xaml?state=Live Tile";
ShellTile.Create(new Uri(uri, UriKind.Relative), newTile);



}

If you notice in above code, I have set navigation to Page1.Xaml. Now on onNavigatedTo() method we need to write code to launch Call Task.


protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
//base.OnNavigatedTo(e);
PhoneCallTask callTask = new PhoneCallTask();
callTask.PhoneNumber = "999999";
callTask.DisplayName = "debugMode";
callTask.Show();


}


 

On running you should be getting below output

image

I hope this post was useful. Thanks for reading.

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