Consuming WCF SOAP Service in Windows 8 Metro Application

In this post we will consume WCF SOAP Service in C#/XAML based Metro Application. This is level 100 post showing basic steps to create simple WCF Service and consume that in Metro Application.

Very first let us create a WCF Service using VS2012. Form File menu create a new project by choosing WCF Service Application project template from WCF tab.

image

Remove all the default code from IService1.cs and replace it with following code. In below service contract we are going to return a simple greeting message. From client a name as string will be input to the service and service will return a greeting message as string.

IService1.cs


using System.ServiceModel;
namespace ServiceToConsumeinMetro
{
 [ServiceContract]
 public interface IService1
 {

[OperationContract]
 string GreetingMessage(string name);

 }

}

Service is implemented as following. It is concatenating two string and returning it .

Service1.svc.cs


namespace ServiceToConsumeinMetro
{

 public class Service1 : IService1
 {
 public string GreetingMessage(string name)
 {
 return "Welcome to Metro Word " + name;
 }
 }
}

We will go with the default binding and will not configure anything in Web.Config. Leave Web.config as it is and press F5 to run and host created WCF service in local server. On successful running in your browser you should have below output.

image

Now let us create a Metro Application to consume this service. From File menu in VS 2012 choose Blank App project template from Windows Metro Style tab.

image

Next let us design the page. On the page we are going to put one TextBox, One Button and one TextBlock. User will enter Name in textbox and on the click event of the button service will be called. Returned output from service will be displayed in the textblock. Xaml is as following

MainPage.xaml


<Page
 x:Class="App1.MainPage"
 IsTabStop="false"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:local="using:App1"
 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 mc:Ignorable="d">

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
 <Grid.RowDefinitions>
 <RowDefinition Height="200" />
 <RowDefinition Height="200" />
 <RowDefinition Height="200" />
 </Grid.RowDefinitions>
 <TextBox x:Name="txtName" Margin="286,25,583,113" />
 <Button x:Name="btnCallService" Content="Enter Name above and touch to call service" Height="100" Width="364" Grid.Row="1" Margin="367,10,0,90" Click="btnCallService_Click_1"/>
 <TextBlock x:Name="textResult" Grid.Row="2" FontSize="30" FontWeight="Bold" />
 </Grid>
</Page>

Next we need to add Service Reference in the Metro project. For that right click on Metro Application project Reference tab and select Add Service Reference

image

Add the reference as following. My metro application name is App1. If your Metro application name is XYZ then you will be adding XYZ.ServiceReference1 provided you have not changed reference name while adding it.

image

In Metro word everything is asynchronous. So we need to make async call to service. When you add reference automatically visual studio creates async function for you.

image

We can call this function from service as following

image

If you notice we have put await keyword before making a call to service. Since service is called in await manner so the function inside which we are calling service must be async. On click event of the button service can be called as following

image

Combining all discussion together code behind will look like as following

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using App1.ServiceReference1;

namespace App1
{

 public sealed partial class MainPage : Page
 {
 public MainPage()
 {
 this.InitializeComponent();
 }

protected override void OnNavigatedTo(NavigationEventArgs e)
 {
 }

private async void btnCallService_Click_1(object sender, RoutedEventArgs e)
 {
 Service1Client proxy = new Service1Client();
 string result = await proxy.GreetingMessageAsync(txtName.Text);
 textResult.Text = result;
 }
 }
}

On running you should be getting output as following

image

I am sorry for poor UI experience but any way making UI immersive was not purpose of this post. I hope now you know basic steps to consume WCF SOAP service in metro application.

Migrate HTML5 WinJS Metro Application project to VS2012

In this post we will migrate a Metro Project created in HTML5 and WinJS from VS11 to VS2012 RC.

Recently I upgraded my system to Windows 8 Release Preview. After upgrading Windows, I migrated VS to VS2012 RC. After successful installation of VS2012, I tried opening a HTML5 + WinJS project created in VS11. When I tried to build that project, I got below exception.

image

Exception was in file C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets

To remove this error what all you need to do is go to solution and remove old reference of Microsoft.WinJS

image

And then again try to rebuild the solution. You should not be getting any build error. Though after than if you run the project you will be getting errors like

image

This error implies that reference has been missing. To solve this we need to add new reference in the project. Add Windows Library for JavaScript 1.0 RC reference in the project. image

After adding reference you need to change the references on HTML. Currently your reference may look like as following

clip_image002

You need to change Microsoft.WinJS.0.6 to Microsoft.WinJS.1.0.RC. After changing references should look like as following

clip_image004

No go ahead and run the project. You should be not getting any error. In this way you can migrate HTML5 WinJS Metro project to VS2012.

I hope this post is useful. Thanks for reading.

Windows Phone Application Life Cycle and Fast Application Switching

What we will learn in this Article ?

  • Windows Phone terminology
  • Application Life Cycle
  • Fast Application Switching
  • Managing Page State

Windows Phone Terminologies

Application State

Application sate is application level Data. This Data may be returned by the service and being displayed in different view. For example a list of students being retuned by a service and on Page1 only students names are being displayed whereas on Page2 student names and age are being displayed. So Application State is a data returned by service and being displayed differently on different pages of the application.

Page State

It is common scenario that user fill some value on page and navigate from that page. On returning to the same page user expects persisted value on the page. Page state is visual persisted state of the page. For example on a page there is one text box and one check box. User has entered some value in text box and checked the check box. Value entered in the textbox and checked checkbox creates Page state of the page.

Tombstoning

It is process to persist data after application is terminated. Data can be persisted of an individual page or data can be persisted of state of whole application. When again user navigates back then application gets recreated and all the data persisted gets restored.

State Dictionary

Dictionary objects are used to store key/value pair. Dictionary in Windows phone is used to restore the Application state. At time of Tombstoning Dictionary gets preserved.

Application Life Cycle

Application life cycle of Windows Phone application says about different state of the application from launching to closing. User launches an application and application goes to running state. Due to launching of other application or on pressing of hardware start or search button application goes to dormant or tombstone state. Again on the launching of application, app gets activated from either dormant or tombstone state. Application can be closed by pressing of hardware back button.

Block diagram on Application Life Cycle events

image

Different events are as below. All events are written in App.Xaml.CS

Application Launching

clip_image002

Application Activated

clip_image004

Application Deactivated

clip_image006

Application Closing

clip_image008

As a developer it is must to have understanding of sequence of events get executed in Windows Phone application life cycle

Fast Application Switching

Windows Phone 7.5 operating system provides improved fast application switching over Windows Phone 7 operating system. Before we go into details of how FAS is better in Mango, let us first understand what is FAS?

Imagine application “A” is running and user launches a new application “B”. On pressing hardware back button user can return back to application “A”. If application “A” gets activated without “resuming “ screen then it can be termed as “ Fast Application Switching

In Windows Phone 7.5 version FAS is improved over Windows Phone 7 with introduction of new state in application life cycle called “Dormant state”. Whereas in Windows Phone 7.0 version there was no Dormant state and on deactivation application directly goes to Tombstone state.

In Windows Phone 7 flow of application was as below,

  • User deactivates application by pressing hardware start or search button
  • Application goes to tombstone state
  • Windows Phone 7 operating system saves information about application Navigation state and State Dictionary
  • Operating system terminates application thread and processes.
  • User again activates application by pressing hardware back button.
  • Operating system creates application thread and process.
  • Operating system restores memory state by retrieving saved value of Navigation state and state dictionary.

Due to above steps in Windows Phone 7 operating system user gets feeling that application was running in background and got resumed from there. However this is not true and operating system again creates application process and restores memory state. Creation of application process and restoration of application memory states take time and cause to slower application switching.

image

In Windows Phone 7.5 flow of application is as below,

  • User deactivates application by pressing hardware start or search button
  • Application goes to dormant state
  • Windows Phone 7.5 operating system preserve instance of the application
  • User again activates application by pressing hardware back button.
  • Operating system restores preserve instance and re activate application
  • If operating system runs low on the memory, it pushes application from dormant state to tombstone state.
  • If application is reactivating from tombstone state then it follows the same cycle as of Windows Phone 7 operation system.

image

Now you understand significant of dormant state for Fast Application switch. With introduction of dormant state in application life cycle, operating system preserve instance of the application in memory unless it is forced to release due to low memory. So at the time of application reactivation as a developer you need to check whether to restore the application or not? If application is reactivating from dormant state then there should not be restoration.

On Application Activated event you can check whether application is reactivating from dormant or tombstone state as below,


private void Application_Activated(object sender, ActivatedEventArgs e)
 {

if (e.IsApplicationInstancePreserved)
 {

// No need to restore the application.
 // Application is reactivating from dormant state
 }

else
 {
 // Need to restore the application.
 // Application is reactivating from tombstone state
 // Read state dictionary and Navigation state to restore memory state

}
 }

An Application gets closed by pressing hardware back button. And in that case application neither goes to dormant state or tombstone state. If there are multiple pages in application then user navigates between pages using hardware back button. However if on start page of application user press hardware back button then operating system will close the application. While closing application Application_Closing() events gets executed.

Maintaining Page State

Page state deals with transient data whereas Application State deals with Persistent Data.

Page state deals with preserving data binding of the user interface of the page. If application is reactivating from dormant state then there is no need of preserving the state of the page or in simple words data of the controls on page explicitly. However if application is reactivating from tombstone state then page data need to be preserved and restore explicitly.

To demonstrate how Page State works? I have designed page as below,

Let us put some control on the phone application page.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

 <TextBox x:Name="txtValue" Height="100" Margin="12,37,58,470" />
 <CheckBox x:Name="chkValue" Height="100" Margin="251,144,0,364"
 HorizontalAlignment="Left" Width="134" />
 <Slider x:Name="sldValue" Value="30"
 Height="100" Margin="28,383,58,124" />

 </Grid>

There are three controls on the page. After tombstone, we need to preserve and restore value of these controls. Now we need to create properties for each control. We need to call NotifyPropertyChanged event in the setter of property to notify when value changed at the control. Control value would be bind with two ways binding with these properties. Eventually Data class will be as below,


&nbsp;

using System.Runtime.Serialization;
using System.ComponentModel;

namespace RestorePageState
{
 [DataContract]
 public class Data : INotifyPropertyChanged
 {

private string textValue;
 private bool chckValue;
 private double sliderValue;

public string TextValue
 {
 get
 {
 return textValue;

}
 set
 {
 textValue = value;
 NotifyPropertyChanged("TextValue");

}
 }

public bool ChckValue
 {
 get
 {
 return chckValue;

}
 set
 {
 chckValue = value;
 NotifyPropertyChanged("ChckValue");

}
 }
 public double SliderValue
 {
 get
 {
 return sliderValue;

}
 set
 {
 sliderValue = value;
 NotifyPropertyChanged("SliderValue");

}
 }
 public event PropertyChangedEventHandler PropertyChanged;
 private void NotifyPropertyChanged(string propertyName)
 {
 if (null != PropertyChanged)
 PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
 }

}
}

With Data Class in place we need to preserve state of the page. There are two checks to perform before preserving page state. First check to be done, whether application is reactivating from dormant state. If so then there is no need of restoring the state. To save the state of the page OnNavigatedFrom method instance of the Data need to be saved in the State dictionary as below,


protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
 {
 if (e.NavigationMode != System.Windows.Navigation.NavigationMode.Back)
 {
 State["Data"] = dataToBindControls;
 }
 }

In above code dataToBindControls is object of Data bind to the controls on the page. To restore the page OnNavigatedTo method state count need to checked as below.


protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
 {
 if (isNewInstanceofPage)
 {
 if (dataToBindControls == null)
 {
 if (State.Count > 0)
 {
 dataToBindControls = (Data)State["Data"];
 }
 else
 {
 dataToBindControls = new Data();
 }
 }
 DataContext = dataToBindControls;
 }
 isNewInstanceofPage = false;
 }

}

Essentially there are three tasks we are performing in above function

  • Checking if it is new instance of the page.
  • If yes then checking if value of data control [object of data class ] is null
  • If null then reading from the state else creating new instance of that.

Full source code behind to preserve page is as below,

using Microsoft.Phone.Controls;

namespace RestorePageState
{
 public partial class MainPage : PhoneApplicationPage
 {

 Data dataToBindControls;
 bool isNewInstanceofPage;

public MainPage()
 {
 InitializeComponent();
 isNewInstanceofPage = true;
 }

protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
 {
 if (e.NavigationMode != System.Windows.Navigation.NavigationMode.Back)
 {
 State["Data"] = dataToBindControls;
 }
 }

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
 {
 if (isNewInstanceofPage)
 {
 if (dataToBindControls == null)
 {
 if (State.Count > 0)
 {
 dataToBindControls = (Data)State["Data"];
 }
 else
 {
 dataToBindControls = new Data();
 }
 }
 DataContext = dataToBindControls;
 }
 isNewInstanceofPage = false;
 }

}
}

Last but not least data need to be bind to controls as below,


<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

 <TextBox x:Name="txtValue" Height="100" Margin="12,37,58,470"
 Text="{Binding TextValue,Mode=TwoWay}"/>
 <CheckBox x:Name="chkValue" Height="100" Margin="251,144,0,364"
 HorizontalAlignment="Left" Width="134"
 IsChecked="{Binding ChckValue,Mode=TwoWay}"/>
 <Slider x:Name="sldValue"
 Height="100" Margin="28,383,58,124"
 Value="{Binding SliderValue,Mode=TwoWay}"/>

 </Grid>

In this way a page state can be preserved. Before debugging last step we need to perform is enable Tombstone upon deactivation while debugging in the properties page. There may be other approach to preserve state as below,

  • Creating extension method for page class
  • Create helper class and call method of the class to save control’s data.

I will conclude with supporting above approach of Page State restore and retrieve for better encapsulation. Since each page is handling their own state so it is easy to separate the concern for pages individually.

First look of New Windows Azure Portal

I must say, I liked this new HTML5 based Windows Azure Portal. Once you login in Windows Azure Portal at the bottom you can find View the Preview Portal

image

You will be prompted to take a tour of new portal.

image

You will be getting dashboard as following,

image

You can see details of all the Hosted Service and Storage Account and SQL Azure database there. Details like

  • Type
  • Status
  • Subscription
  • Location

Is shown on the home page as following

image

There are four tabs in left side. By default All Items tab is selected. Other tabs are as following

image

If you want to get more details about Hosted Service then select Cloud Services tab and you will be getting much deeper details as following

image

In same way if you want finer lever details on SQL Azure database then select SQL DATABASES tab from left . You will be getting SQL Azure database details as following

image

If you want finer level details on Storage you can get by selecting Storage tab. You will be getting details as following

image

You can create following items by clicking new button in bottom

image

Items can be created as following

  • New Hosted Service
  • New Storage
  • New SQL Database
  • New Web Site
  • New Virtual Machine
  • New Network

image

There are some features might be disabled in your subscription. You will get following message when you select that feature. In my subscription Web Site, Virtual Machine and Network is not available and I get below message when I select them. Any time we can sign up for Preview Program.

image

While creating you will be having two options of QUICK CREATE or CUSTOM CREATE. Quick Create will create a cloud service by just specifying URL. Content deployment and configuration can be done later.

image

Custom Create will create cloud service by providing URL and optionally providing content employment and configuration.

image

You can manage keys and delete a service from the option given in bottom of the page.

clip_image001

In bottom you have option to get Help as well.

clip_image003

On clicking of HELP you will be getting various details and various operations.

clip_image005

In further blog post I will give more details of other features. Till then enjoy the new Azure Portal.