Article
    C#
    ADO.Net
    .NET
    ASP.Net & Web Forms
    Custom Controls
    Web Development
    Exception Handling
    XML
    Database
    Security in .Net
    Testing
    Web Services
    Windows Services
    Windows Controls
    WCF
    AJAX
    WPF
    XAML
    Reporting
    Setup
    VB.Net
    LINQ
    JQuery
    SilverLight
    JavaScript
    HTML5
    Crystal Report
    Cloud Computing
    Share Point
    Visual C++
    MVC
    Android
    PHP
    Java
    HTML
    WordPress
    Joomla
    Products
    Drupal
    Windows Phone
    JSON
    LightSwitch
    iPhone/iPad
    Ruby on Rails
    IIS 7
    Windows 8
    CSS/CSS3
    Excel
    MS Access
    Shortcut Keys
    Visual SourceSafe
    Team Foundation Server
    APIs
Follow Us
Follow _MindStick_ on Twitter View MindStick Software's LinkedIn profile View MindStick Software's Facebook profile
Top Contributor
Advertisement
Advertise with Us
Mindstick
Article Article  Forum Forum  Blog Blog  Quiz Quiz  Beginner Beginner  Careers Careers  Contact Contact  Login Login  
Home | Product | Services | About Us | Interview | DeveloperSection | Submit an Article | Submit Blog

Home >> Windows Phone >> Data binding in Windows Phone 7 using WCF Service
Data binding in Windows Phone 7 using WCF Service
Data binding in Windows Phone 7 using WCF Service


by Arun Singh on 4/18/2012 5:43:26 PM

Views: 2415       Comments: 0

Data binding in Windows Phone 7 using WCF Service

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(int value);

        /// <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(string eMail);

 

        [OperationContract]

        CompositeType GetDataUsingDataContract(CompositeType composite);

 

        // 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(int value)

        {

            return string.Format("You entered: {0}", value);

        }

 

        public string GetLoginInformation(string eMail)

        {

            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 = new DataSet();

            da.Fill(ds);

            DataTable dt = new DataTable();

            string xmlData = ds.GetXml();

            da.Dispose();

            con.Close();

            return xmlData;

        }

 

        public CompositeType GetDataUsingDataContract(CompositeType composite)

        {

            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.Service1Client proxy = new ServiceReference1.Service1Client();

            proxy.GetLoginInformationAsync("amitsingh@xyz.com");

            proxy.GetLoginInformationCompleted += new EventHandler<ServiceReference1.GetLoginInformationCompletedEventArgs>(proxy_GetLoginInformationCompleted);

 

        }

 

        void proxy_GetLoginInformationCompleted(object sender, ServiceReference1.GetLoginInformationCompletedEventArgs e)

        {

            // Bind Data from WCF Service

            txtBlockContent.Text = e.Result;

          

        }

 

        private void button1_Click(object sender, RoutedEventArgs e)

        {

          

            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.

Report Abuse Form
Reason:    
 

Title :
Comment :
Text ColorBackground Color
BoldItalicUnderline
LeftCenterRightJustify
Ordered ListBulleted List
IndentOutdent
Horizontal Rule
SubscriptSuperscript
HyperlinkImage
Design ModeDesign
View HtmlHtml
     
 
Latest Article by Arun SinghRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Latest BlogsRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Top Viewed ArticlesRSS Feed
    
    
    
    
    
    
    
    
    
    
Top Viewed BlogsRSS Feed
    
    
    
    
    
    
    
    
    
    
Latest Interview QuestionsRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Total Online Users: 6001
Advertisement
MindStick Cleaner
Advertise with Us
  
Copyright © 2013MindStick. All Rights Reserved.