Click here to Skip to main content
15,881,139 members
Articles / Programming Languages / C# 4.0

Making WCF Service reference configurable from web.config in Silverlight application

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
22 Apr 2012CPOL2 min read 392.4K   762   15   3
How to make WCF service reference configurabe for Silverlight project(makes easy for deploying on severs like Dev, QA, UAT etc.)

Introduction

Here I am going to demonstrate solution for common problem which most of the developers face while developing Silverlight application with WCF Service. I have search lot of forums and could not found any good solution. So I am sharing my solution to make WCF service reference configurable. It makes easy for deploying on severs like Dev, QA, UAT etc. without code modification and republish.

Background

To implement this application, I am going to use the following technologies:

  • Silverlight5 for the client tier
  • WCF services -HTTP Binding
  • WCF RIA Service V1.0 SP2

Creating Silverlight Business Application

Create new Silverlight business application. Name it to ‘BusinessAppMVVM’.

Image 1

WCF Service

Add WCF service to the solution. Name it ‘BusinessAppMVVM.AppWCFService’.

Image 2

Write one test method in ‘Service1.svc.cs’ .

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

Add contract for this method.

[OperationContract] 
string GetUserAddress(string value); 

To enable a Silverlight control to access a service in another domain, the service must explicitly opt-in to allow cross-domain access. I am also going to deploy WCF service and Silverlight application on different servers.

Add ‘CrossDomainService’ service and add following code to it.

C#
public class CrossDomainService : ICrossDomainService 
{ 
    Message ICrossDomainService.ProvidePolicyFile() 
    { 
        FileStream filestream = File.Open(@"ClientAccessPolicy.xml", FileMode.Open); 
        // Either specify ClientAccessPolicy.xml file path properly 
        // or put that in \Bin folder of the console application 
        XmlReader reader = XmlReader.Create(filestream); 
        System.ServiceModel.Channels.Message result = Message.CreateMessage(MessageVersion.None, "", reader); 
        return result; 
    } 
}

Create contract for this service.

C#
[ServiceContract] 
public interface ICrossDomainService 
{ 
    [OperationContract] 
    [WebGet(UriTemplate = "ClientAccessPolicy.xml")] 
    Message ProvidePolicyFile(); 
} 

Add ‘ClientAccessPolicy.xml’ file for policy description.

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

Web Project

Add following ‘appsettings’ section to 'web.comfig’ file.

XML
<appSettings>
<!--QA Server WCF Service URL-->
<!--<add key="WCFServiceURL" value="<a href="http://test-iis-qa:1111/Service1.svc">http://Test-iis-QA:1111/Service1.svc</a />" />-->
<!--Local development WCF Service URL-->
<add key="WCFServiceURL" value="<a href="http://localhost:59761/Service1.svc">http://localhost:59761/Service1.svc</a />" />
</appSettings> 

In this section you can have all the URL of servers where WCF service is being deployed like Dev, QA, UAT etc. Just uncomment URL which service you want to use in your Silverlight project without modifying any code. You don’t need to redeploy.

I am going to add RIA service to communicate this URL value to Silverlight project.

Add RIA service BusinessAppRIAService’ in Web project.

Image 3

Add following method in your new RIA service.

C#
[Invoke]
public string GetWCFServiceAddress()
{
    string url = ConfigurationManager.AppSettings.Get("WCFServiceURL");
    return url;
}

Silverlight Client

Add service reference to Silverlight project.

Image 4

Declare property in ‘app.xaml.cs’.

C#
public string WCFServiceURL { get; set; }

Write following lines to call RIA service to get ‘WCFServiceURL’ value inside ‘Application_UserLoaded’.

C#
//Call RIA Service to get WCF Service URL
var context = new BusinessAppMVVM.Web.Services.BusinessAppRIAContext();
context.GetWCFServiceAddress(GetWCFServiceURLCompleted, null);

Define ‘GetWCFServiceURLCompleted’ as follows.

C#
private void GetWCFServiceURLCompleted(InvokeOperation<string> args)
{
try
{
    WCFServiceURL = args.Value;
}
catch (Exception ex)
{
    //log
}
}


Now you are all set to write testing code to call WCF service. Add button control to ‘Home.xaml’. On button click event write following line of code.

C#
private void button1_Click(object sender, System.Windows.RoutedEventArgs e)
{
    //Create Instance.
    BusinessAppServiceModel.Service1Client _serviceClient = null;
    if (_serviceClient == null)
    {
        var myBinding = new BasicHttpBinding();
        string url = ((App)Application.Current).WCFServiceURL;
        if (url != null)
        {
        var address = new EndpointAddress(url);
        _serviceClient = new BusinessAppServiceModel.Service1Client(myBinding, address);
        }
        else
        {
        MessageBox.Show("WCF Service URL is not found.");
        }
    }
    //Call Service
    _serviceClient.GetUserAddressCompleted -=
    new EventHandler<GetUserAddressCompletedEventArgs>(OnGetUserAddressCompleted);
    _serviceClient.GetUserAddressCompleted +=
    new EventHandler<GetUserAddressCompletedEventArgs>(OnGetUserAddressCompleted);
    _serviceClient.GetUserAddressAsync("Called from UI");
}
private void OnGetUserAddressCompleted(object sender, GetUserAddressCompletedEventArgs e)
{
    MessageBox.Show(e.Result);
}


Deploy Silverlight and WCF service. Go to Web.config to change service url. You can see your project is working without redeploy.

Image 5

At the End

You can download source code attached with this article. Hope this article will help you in deploying solution on different servers.

I would appreciate Vote for the Article and any comments or concerns or how things could be done better. Coming soon with my new findings.

Thanks for reading.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
United States United States
Manoj Kumar

AWS Certified Solutions Architect (Web development, Serverless, DevOps, Data)
MSSE - Cloud and Mobile Computing, San Jose State University

A wide range of experience in resolving complex business problems.

* Cloud Technologies: EC2, S3, DynamoDB & RDS databases, Lambda serverless architecture, Microservices architecture, API Gateway, Cloud Front CDN, Linux/Windows systems administration, CloudFormation, DevOps, Docker, CICD, Node.js, Python, Java and other open source technologies. Familiarity with OpenStack.
* Web Technologies: HTML5, Node.Js, MEAN Stack, AngularJS, ASP.Net Core, MVC5, CSS3, jQuery, Bootstrap, MongoDB, JavaScript, JSON, AJAX.
* Data: Experience in database architecture, Big Data, Machine Learning, BI, Data Analytics, No-SQL databases, ETL.
* Mobile: IOS/Android app development

He lives with his wife Supriya and daughter Tisya in Bay Area.

Comments and Discussions

 
QuestionIs it going to work via HTTPS? Pin
yuriiv22-Apr-12 2:05
yuriiv22-Apr-12 2:05 
AnswerRe: Is it going to work via HTTPS? Pin
ManojKumar1923-Apr-12 11:18
ManojKumar1923-Apr-12 11:18 
GeneralGreat Pin
ghulam.e.mustafa22-Apr-12 0:50
ghulam.e.mustafa22-Apr-12 0:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.