articles

Home / DeveloperSection / Articles / Data Binding in Windows Phone 7 Using WCF Service

Data Binding in Windows Phone 7 Using WCF Service

Anonymous User 14262 18-Apr-2012

This article is going to explain how to bind data in Windows Phone 7 using WCF Service. Let’s see a brief demonstration on it.

Getting Started:

1.       Open Visual Studio

2.       Create new Silverlight Windows 7 Phone Development Project

3.       Enter your project Name

4.       Click on button ‘Ok’

Data Binding in Windows Phone 7 Using WCF Service

Now drag and drop TextBlock and Button control in MainPage.xaml user interface design and made following layout by setting some property too.

Data Binding in Windows Phone 7 Using WCF Service

Now make WCF service which returns data from database. Here I’m just retrieving user information from the database on the basis of user email id.

To create WCF service, follow up some following step.

Step:  Open Visual Studio and go to File-> New-> Project.

Data Binding in Windows Phone 7 Using WCF Service

Now click on button ‘Ok’ and write down following code.

Code of 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;
using System.Data;
 
namespace WcfService2
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {
 
        [OperationContract]
        string GetData(intvalue);
        /// <summary>
        /// Method to retrieve information from database for particular email id.
        /// </summary>
        /// <param name="eMail">EmailId of that person for which you would take information</param>
        /// <returns> string type xml data</returns>
        [OperationContract]
        [WebGet(UriTemplate="data/{value}")]
       string GetLoginInformation(stringeMail);
 
        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeTypecomposite);
 
        // TODO: Add your service operations here
    }
 
 
    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    [DataContract]
    public class CompositeType
    {
        bool boolValue=true;
        string stringValue="Hello ";
 
        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue= value; }
        }
 
        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue= value; }
        }
    }
}
Code of Service1.svc.cs:
using System;

using System.Data;
using System.Data.SqlClient;
 
namespace WcfService2
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class Service1 : IService1
    {
        public string GetData(intvalue)
        {
            return string.Format("You entered: {0}", value);
        }
 
        public string GetLoginInformation(stringeMail)
        {
            SqlConnection con=new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["myConnection"].ConnectionString);
            con.Open();
            string queryString= string.Format("select * from tblLogin where EmailId = '{0}'", eMail);
            SqlCommand cmd= new SqlCommand(queryString, con);
            // SqlDataReader dr = cmd.ExecuteReader();
            SqlDataAdapter da=new SqlDataAdapter(cmd);
            DataSet ds= newDataSet();
            da.Fill(ds);
            DataTable dt= newDataTable();
            string xmlData=ds.GetXml();
            da.Dispose();
            con.Close();
            return xmlData;
        }
 
        public CompositeType GetDataUsingDataContract(CompositeTypecomposite)
        {
            if (composite== null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue+="Suffix";
            }
            return composite;
        }
    }
}

Now start recently created WCF Service.

Data Binding in Windows Phone 7 Using WCF Service

Now click on ‘Service1.svc’ link.

Data Binding in Windows Phone 7 Using WCF Service

Now add this WCF Service in your DataBindDemo project. To add WCF service in windows phone 7 applications follows the following step.

Step:  Right click on project name; select ‘Add Service Reference’ options and following wizard’s instruction.

Data Binding in Windows Phone 7 Using WCF Service

Now following window will be appearing; fill appropriate information in text fields and click on button ‘Ok’.

Data Binding in Windows Phone 7 Using WCF Service

Data Binding in Windows Phone 7 Using WCF Service

Now WCF service added successfully in windows phone 7 applications. Write down following code;

Code of MainPage.xaml:
<!--LayoutRoot is the root grid where all page content is placed-->

    <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="My Application" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="DataBindingDemo" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}" FontSize="36" />
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0" DataContext="{Binding}">
            <Button Content="Invoke WCF Service" Height="72" HorizontalAlignment="Left" Margin="124,583,0,0" Name="button1" VerticalAlignment="Top" Width="302" Click="button1_Click" />
            <TextBlock Height="571" HorizontalAlignment="Left" Margin="12,6,0,0" Name="txtBlockContent" Text="" VerticalAlignment="Top" Width="438" />
        </Grid>
    </Grid>

Code of MainPage.xaml.cs:
using System;

using System.Windows;
using Microsoft.Phone.Controls;
using DataBindDemo.ServiceReference1;


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

            // GetInfo();

        }
        public void GetInfo()
        {

            ServiceReference1.Service1Clientproxy=newServiceReference1.Service1Client();
            proxy.GetLoginInformationAsync("amitsingh@xyz.com");
            proxy.GetLoginInformationCompleted+=newEventHandler<ServiceReference1.GetLoginInformationCompletedEventArgs>(proxy_GetLoginInformationCompleted);

        }

        void proxy_GetLoginInformationCompleted(objectsender, ServiceReference1.GetLoginInformationCompletedEventArgse)
        {
            // Bind Data from WCF Service
            txtBlockContent.Text=e.Result;

        }

        private void button1_Click(objectsender, RoutedEventArgse)
        {

            Service1Client proxyClient=new Service1Client();
            proxyClient.GetLoginInformationAsync("amitsingh@xyz.com");
            proxyClient.GetLoginInformationCompleted+= new EventHandler<ServiceReference1.GetLoginInformationCompletedEventArgs>(proxy_GetLoginInformationCompleted);
        }
    }
}

Code of ServiceReferences.ClientConfig:
<configuration>


    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IService1"maxBufferSize="2147483647"
                    maxReceivedMessageSize="2147483647">
                    <security mode="None" />
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:51641/Service1.svc"binding="basicHttpBinding"
                bindingConfiguration="BasicHttpBinding_IService1"contract="ServiceReference1.IService1"
                name="BasicHttpBinding_IService1" />
        </client>
    </system.serviceModel>
</configuration>

Now execute DataBindDemo application; following output will be appearing after executing program.

Data Binding in Windows Phone 7 Using WCF Service

To retrieve data from database call WCF Service, to perform it click on button ‘Invoke WCF Service’.

Data Binding in Windows Phone 7 Using WCF Service

Returned data will be displayed on screen with the help of TextBlock control. This is the complete description of Data Binding concept in Windows Phone 7 development using WCF service. I hope you will enjoy it and I’m very thankful to you for reading this article.


Updated 07-Sep-2019
I am a content writter !

Leave Comment

Comments

Liked By