Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » WCF » WCF 4.0 service consumed in Silverlight 4.0 with cross domain

WCF 4.0 service consumed in Silverlight 4.0 with cross domain

This article will explain how to call WCF 4.0 service hosted in IIS 7.5 in a Silverlight application.

Author Rank :
Page Views : 2837
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Objective 

This article will explain how to call WCF 4.0 service hosted in IIS 7.5 in a Silverlight application.  This article will explain the way to avoid cross domain problem also. 

Expected Output 

1.gif 

When user will click on + button a WCF service hosted on IIS will get called. As a input parameter to service value from two text box will be passed and result from the service will get display in result text box. 

2.gif
 
Create WCF Service 

Create WCF service. Open visual studio select new project and then from WCF tab select WCF Service application to create a new WCF service. 

3.gif
 
Delete the default code created by WCF from IService1 and Service1.svc.cs 
  • So delete the data contract 
  • Modify the service contract as below. Just make one operation contract to return a string. 
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 WcfService5
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string  GetMessage(string  number1 , string number2);
    }  
}

Now implement the service as below, 

Service1.svc.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 WcfService5
{
    public class Service1 : IService1
    {
        public string GetMessage(string number1, string number2)
        {
            return (Convert.ToInt32(number1) + Convert.ToInt32(number2)).ToString();
        }
    }
}

Since, we are creating WCF Service for SilverLight client, so we need to modify the endpoint of the service with basicHttpBinding. 

As we know SilverLight supports either basicHttpBinding or webHttpBinding.  webHttpBinding is essentially for REST based service .  We are going to use basicHttpBinding to enable SOAP based WCF service for SilverLight client. 

<services>
      <service name ="WcfService3.Service1" behaviorConfiguration ="svcbh" >
        <host>
          <baseAddresses>
            <add baseAddress = "http//localhost:9000/Service1/" />
          </baseAddresses>
        </host>
        <endpoint name ="duplexendpoint"
                  address =""
                  binding ="wsDualHttpBinding"
                  contract ="WcfService3.IService1"/>
        <endpoint name ="MetaDataTcpEndpoint"
                  address="mex"
                  binding="mexHttpBinding"
                  contract="IMetadataExchange"/>
      </service>
</services>
  1. Declare the end point with basicHttpBinding.

    <
    endpoint name ="SilverLightendpoint"
              address =""
              binding ="basicHttpBinding"
              contract ="WcfService5.IService1"/>

  2. Declare the Meta data exchange end point.

    <
    endpoint name ="MetaDataSilverlightEndpoint"
              address="mex"
              binding="mexHttpBinding"
              contract="IMetadataExchange"/>

  3. Define the service behavior 

    <
    serviceBehaviors>
      <behavior name ="svcbh">        
        <serviceMetadata httpGetEnabled="true"/>        
        <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
    </serviceBehaviors>
So the service will look like 

<services>
  <service name ="WcfService5.Service1" behaviorConfiguration ="svcbh">
    <endpoint name ="SilverLightendpoint"
              address =""
              binding ="basicHttpBinding"
              contract ="WcfService5.IService1"/>
    <endpoint name ="MetaDataSilverlightEndpoint"
              address="mex"
              binding="mexHttpBinding"
              contract="IMetadataExchange"/>
  </service>
</services>

Web.Config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name ="svcbh">        
          <serviceMetadata httpGetEnabled="true"/>        
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name ="WcfService5.Service1" behaviorConfiguration ="svcbh">
        <endpoint name ="SilverLightendpoint"
                  address =""
                  binding ="basicHttpBinding"
                  contract ="WcfService5.IService1"/>
        <endpoint name ="MetaDataSilverlightEndpoint"
                  address="mex"
                  binding="mexHttpBinding"
                  contract="IMetadataExchange"/>
      </service>
    </services>
    <!--<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />-->
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer> 
</configuration>

Hosting in IIS and solving the cross domain problem 


Solving cross domain problem
  1. Right click on WCF Service project and add new item. Select XML file from Data tab. 

    4.gif

  2. Give the name of the XML file clientaccesspolicy.xml

    5.gif

  3. Add the below markup in ClientAcccessPolicy.xml  file 

    <?
    xml version="1.0" encoding="utf-8" ?>
    <access-policy>
      <cross-domain-access>
        <policy>
          <allow-from http-request-headers="SOAPAction,Content-Type">
            <domain uri="*" />
          </allow-from>
          <grant-to>
            <resource path="/" include-subpaths="true"/>
          </grant-to>
        </policy>
      </cross-domain-access>
    </access-policy>

  4. Now open WCF Service project in windows explorer. To do this right clicks on the project and select open folder in Window explorer. 

    6.gif
Copy clientaccesspolicy.xml file and paste it in C:\inetpub\wwwroot. Make sure in wwwroot folder clientaccesspolicy.xml file exist. 

Consuming in SilverLight 4.0 
  1. Create  a Silverlight project  by  Project->new ->SilverLight -> SilverLight Application

    7.gif

    And create a web site to host Silver light application. 

    8.gif

  2. Now design the page in XAML. 

    9.gif

    MainPage.xaml


    <
    UserControl x:Class="SilverlightApplication3.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d">
        <Grid x:Name="LayoutRoot" Background="Gray" Height="200" Width="300">
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition Height="2*" />
            </Grid.RowDefinitions>
            <TextBox x:Name="txtResult" Height="40" Text="" Margin="12,14,22,14" />
            <StackPanel Orientation="Horizontal" Grid.Row="1" >
                <Canvas>
                <TextBox x:Name="txtNumber1" Height="40" Width="99"  Canvas.Left="20" Canvas.Top="30"/>
                    <Button x:Name="btnAdd" Height="40" Width="50" Content="+" Canvas.Left="120" Canvas.Top="30" />
                    <TextBox x:Name="txtNumber2" Height="40" Width="99"  Canvas.Left="170" Canvas.Top="30"/>
                </Canvas>          
            </StackPanel>
        </Grid>
    </UserControl>

    Explanation 

    a. Divided the main grid in two rows. 
    b. In first row put a textbox to display the result. 
    c. In second row put a stack panel with horizontal orientation.
    d. Put a canvas inside stack panel
    e. Put two text box and button in canvas.

  3. Right click on SilverLight project and add Service Reference. 

    10.gif

    Give the URL of the WCF service hosted in IIS in Address text box.  And then click GO. 

    11.gif

  4. Calling the Service 

    Add namespace 

    using SilverlightApplication3.ServiceReference1; 

    On click event of the button 

    Service1Client
    proxy = new Service1Client();
    proxy.GetMessageCompleted += delegate(object sender1, GetMessageCompletedEventArgs e1) { txtResult.Text = e1.Result;};
    proxy.GetMessageAsync(txtNumber1.Text ,txtNumber2.Text);           

    Explanation 

    a. Silverlight calls WCF service asynchronously 
    b. So first completed event is getting called. If operation contract name is GetMessage then event name will be GetMessageCompleted. 
    c. After event aysnc function is being called. 
MainPage.Xaml.cs

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;
using SilverlightApplication3.ServiceReference1;

namespace
SilverlightApplication3
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            btnAdd.Click += new RoutedEventHandler(btnAdd_Click);
        }
        void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            Service1Client proxy = new Service1Client();
            proxy.GetMessageCompleted += delegate(object sender1, GetMessageCompletedEventArgs e1) { txtResult.Text = e1.Result;};
            proxy.GetMessageAsync(txtNumber1.Text ,txtNumber2.Text);
        }
    }
}

Output 

1.gif 

Conclusion 

In this article we saw how we can consume WCF Service in Silverlight application with cross domain. I hope this article was useful. Thanks for reading. Happy Coding

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Dhananjay Kumar
I write few articles on Microsoft technologies. Read my blog at . | Mincracker MVP | Microsoft MVP
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.