Monday, January 30, 2012

How to call WCF services methods from Silverlight Application

How to call WCF services methods from Silverlight Application

Here I am giving very basic idea for beginner who wants to know how we can call WCF service from Silverlight application. Calling WCF service from Silverlight uses different types of binding (basicHttpBinding), if you use RIA service then you need not to think binding configuration, it will take care automatically.

<client>
   <endpoint address="http://localhost:13513/Service1.svc" binding="basicHttpBinding"
    bindingConfiguration="BasicHttpBinding_IService1" contract="WcfService1.IService1"
    name="BasicHttpBinding_IService1" />
</client>
  
Follow the steps to create first “HelloWorld” solution  

1.     Create Simple WCF service project “WcfService1” in solution “HelloWorld.sln”
2.     Add “clientaccesspolicy.xml” and “crossdomain.xml” xml file into WCF project “WcfService1”
3.     Add one Silverlight project “SilverlightApplication1” into same solution “HelloWorld.sln”
4.     “SilverlightApplication1.Web”will get added automatically
5.     Set “SilverlightApplication1” project as startup project
6.     Now right click on “SilverlightApplication1” project and “Add service Reference” to “WcfService1”
7.     Now right click on “WcfService1” reference and click on Update Proxy
8.     Run the application

After creating project it will looks like as below screen shot

  
Source Code

C# Code in “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;

namespace WcfService1
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);
    }

C# Code in “Service1.svc.cs” file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService1
{
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }
    }
 }

C# Code in “MainPage.XMAL”
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightApplication1
{
    public partial class MainPage : UserControl
    {
        //Declare WCF proxy ref variable
        WcfService1.Service1Client webClient;

        public MainPage()
        {
            InitializeComponent();
            //Initialise WCF proxy variables
            webClient = new WcfService1.Service1Client();
            //Registred WCF complatedevent
            webClient.GetDataCompleted += new EventHandler<WcfService1.GetDataCompletedEventArgs>(ServiceCloud_GetDataCompleted);
        }

        //On button click event will call WCF service Async method to get data
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //Call WCF method
            webClient.GetDataAsync(30);
        }

        //once WCF service call completed then "e.Result" will give you return data from WCF call
        //you need to wait until WCF call complated and return value
        void ServiceCloud_GetDataCompleted(object sender, WcfService1.GetDataCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                //if WCF return data successfully then data will return into e.Result
                label1.Content = e.Result.ToString();
            }
            else
            {
                //other wise error message will be returned
                label1.Content = e.Error.Message.ToString();
            }

        }
    }
} 
Troubleshoots
  1. You might get error related to “Crossdomain” policy, if you don’t place “clientaccesspolicy.xml” and “crossdomain.xml” into “WcfService1” project, after changing anything/adding these .xml files you have to update the proxySee here to create these files: http://riteshkk2000.blogspot.com/2011/01/attempting-to-access-service-in-cross.html
  2. Internet explorer may ask to install Silverlight runtime even this already installed into your machine. you need to register local URL on the “Restricted Site”See more here to solve:    http://riteshkk2000.blogspot.com/2011/01/asking-to-install-silverlight-4-when.html
  3. If you need more and more details with pictorial view then good site to go through http://blogs.msdn.com/b/avkashchauhan/archive/2011/11/29/silverlight-front-end-calling-to-wcf-service-all-in-one-windows-azure-web-role-sample.aspx

No comments: