Click here to Skip to main content
Click here to Skip to main content

A beginner’s guide to WCF in XBAP

By , 9 Feb 2009
Rate this:
Please Sign up or sign in to vote.

Contents

Development platform

  1. Visual Studio 2008
  2. .NET framework 3.5
  3. IIS 5.1~7
  4. IE7/Firefox 2.x
  5. ASP.NET 2.0
  6. Windows Vista/XP

Introduction

Windows Presentation Foundation, in short, WPF, is Microsoft’s new user interface technology. WPF was introduced with the release of >NET framework 3.0. WPF comes with a lot of promises; for example, it can be used to show very rich graphics centric 2D and 3D models. WPF uses the client machine's graphics capability to the full extent. For more information about WPF, please visit www.windowclient.net. In this article, we will discuss about using WPF in the web! It sounds like a very strange wish to accomplish. But it’s true; WPF can be used in the browser. This special browser centric package is called a WPF Browser Application. XBAP stands for XAML Browser Application, which is the eventual output of the WPF Browser Application. The main purpose of XBAP is to introduce a fat client application which runs on the client side and provide the user the ease of desktop applications in the web. XBAP uses the resources of the client machine, that’s why the .NET framework must be installed in the client machine to run the WPF Browser Application. Even though XBAP uses the client machine's resources and memory, it runs in a sandbox environment. This mode of sandbox is called the partial trust mode. XBAP in .NET 3.5 has a few improvements over 3.0. Using WCF in partial trust mode is one of them. In this article, we will see the implementation of a WCF service in XBAP partial trust mode.

Preparing the stage

Learning by example is always a very good way of learning new things, that’s why we are going to develop a simple XAML browser application in which we will display a to-do list and notes of a user, and of course, use WCF to communicate with our data layer. A few things must be clear before jumping in to the stage. In partial trust mode, XBAP can consume a WCF Service from the site of origin only. So, we cannot use a cross domain WCF Service from XBAP. Another restriction we have is in the case of WCF binding configuration. We can only use BasicHttpBinding and WSHttpBinding in partial trust mode. For retrieving, creating, deleting, and updating tasks, we will use BasicHttpBinding. On the other hand, for retrieving, creating, deleting, and updating notes, we will use WsHttpBinding. Let’s go through the project templates first. We will, of course, create a WPF Browser Application project. Next, we will create a WCF Service Application project, and finally, we will develop a simple website (Web Application project of VS2008) where our browser application will be hosted. We will use a SQL Server Express edition database in the data service layer, a “tododata.mdf”. We will construct our own user base and user validation. The WPF browser application will forward all requests to a WCF Web Service. The WCF Service will do the business logic validation and retrieve data from the data access layer. Shown below is a simple diagram to present how the application architecture will be:

XBAP-WCF.JPG

Creating the projects and the necessary files

By now, we already know that we are going to create three different projects. So, let’s get started. We will start by creating a blank solution for our convenience. Go ahead and create a blank solution in VS2008 and save the solution to a convenient place with a convenient name. Now, add a new WPF Browser Application project to the solution. Then, add a new WCF Service Application to the solution, and lastly add a new Web Application project. That concludes the projects creation process. To save the data, we will use a SQL Server Express database. So, let's go ahead and add a SQL Server database file and name it to your convenience. Then, create the necessary tables for tasks, notes, and users. Next, we need a simple mechanism to retrieve, save, and modify data from the database; for this, we are going to use LINQ. Add a DBML file to the WCF Service project, and drag and drop the data tables from the Database Explorer to the DBML. Next, we have to define our service interfaces. We will have two services in the same WCF project: one for notes (INoteService) and the other for tasks (ITaskService).

Projects.jpg

Configuring WCF for XBAP

If you are new to WCF, I would like to suggest you spend some time on the MSDN library learning WCF. Now, we have our WCF Service application “WcfService”. We will configure our WCF Service so that our XBAP can consume this service. By default, when users add a WCF Service, Visual Studio automatically configures two end points for the Service. We are going to modify the binding configuration for our Service so that XBAP can communicate with it. Visual Studio 2008 provides a nice tool to edit WCF Service configurations, and the tool is called “WCF Service Configuration Editor”. We will edit the Service configurations with this tool. You can also modify the web.config manually to setup the appropriate markup under the Service Model section. By default, when you right click on the web.config of the Service, no edit configuration tool is shown. To make it show, first, we have to run it from the Tools menu of Visual Studio 2008. Click on the Tools menu of Visual Studio 2008, and click on the WCF Configuration menu. Now, you can close the tool. Once you have opened the tool, it will be available for the current session. Now, right click on the web.config file of the WCF Service project and select “Edit WCF configuration”. The configuration editor will pop up with the entire configuration that is defined in the web.config. In the configuration editor, on the left side, you will find a tree with service information populated. Expand the Services node, and you will see a node named “Endpoints”. By default, under the Endpoints node, there are two pre-added endpoints, one configured with WsHttpBinding and another configured with MaxHttpBinding. Now, select the endpoint that is configured with WsHttpBinding. After selecting the endpoint, the properties of that endpoint will be shown in the property editor on the right side. Change the binding property from WsHttpBinding to BasicHttpBinding. Click on File, and save and close the tool.

ServiceConfigurationEditor.jpg

Now, it’s time to host the service to a location so that our application can consume it from a fixed location. When we add the WCF Service application, by default, Visual Studio 2005/2008 configures the service to run on the Visual Studio Development Server. We are going to modify this to run from IIS. For this, right click on the WCF Service project and select Properties. After the project properties window pops up, navigate to the Web tab and change the server configuration under the Servers section from “Use Visual Studio Development Server” to “Use IIS Web Server”. After that, you need to click on the Create Virtual Directory button to finish the process. Now, save the project. And, you are all done configuring the Service for your XBAP. If you are in Windows Vista, you might encounter a few errors; to overcome the problems, you must run Visual Studio with the “Run as Administrator” mode.

Consuming a WCF Service from XBAP

The hard part is now over. Just add a service reference; right click on the project, select “Add Service Reference“. After the service reference window pops up, click on the Discover button. You can select the service and the URL will be added to the address textbox. Click OK, and you are all done. Because of the previous actions that were performed, the appropriate mark up will be added in the app.config under the serviceModel configuration section. The markup that is added looks like this:

<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="BasicHttpBinding_IService1" closeTimeout="00:01:00"
                openTimeout="00:01:00" receiveTimeout="00:10:00" 
                sendTimeout="00:01:00"
                allowCookies="false" bypassProxyOnLocal="false" 
                hostNameComparisonMode="StrongWildcard"
                maxBufferSize="65536" maxBufferPoolSize="524288" 
                maxReceivedMessageSize="65536"
                messageEncoding="Text" textEncoding="utf-8" 
                transferMode="Buffered"
                useDefaultWebProxy="true">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" 
                    maxArrayLength="16384"
                    maxBytesPerRead="4096" 
                    maxNameTableCharCount="16384" />
                <security mode="None">
                    <transport clientCredentialType="None" 
                          proxyCredentialType="None" realm="" />
                    <message clientCredentialType="UserName" 
                             algorithmSuite="Default" />
                </security>
            </binding>
        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://munna.kaz.com.bd/TODO.SERVICE/Service1.svc"
            binding="basicHttpBinding" 
            bindingConfiguration="BasicHttpBinding_IService1"
            contract="TodoServiceReference1.IService1" 
            name="BasicHttpBinding_IService1" />
    </client>
</system.serviceModel>

Debugging a WCF Service

While developing XBAP, sometimes, developers need to debug the application. The developer may need to investigate what data is received by the Service and what data is transmitted from the Service. Well, since WCF works in XBAP only in partial trust mode, it’s become a little bit difficult, but not much. While debugging from Visual Studio 2008, we can set the “trust mode” to full trust. You can set the trust mode to full trust from the Security tab of the project properties. This will enable your WPF project to debug the application in the development environment. But, during deployment, you must change the trust mode back to partial trust; otherwise, you might get a trust not granted error.

Deploying your solution

First of all, the developer needs to set XBAP’s security mode to partial trust. In the Publish Wizard, the first step is to specify where you want to publish the binary. Browse and select a folder of your convenience. Click Next, and the next option is the selection of how the user will install the application. In this screen, the developer needs to select the “from a web site” option and specify the location of the website. Browse or put down the location of the website. While deploying your solution, you must be careful about the deployment URL and the URL of the WCF Service that is defined in the app.confiq of the XBAP. In the app.config, let’s say you have an end point with http://localhost/wcfservice. You should also put your XBAP deployment URL as http://localhost/xbaphost. If you have localhost in app.config, but you browse http://{pcname}/xbaphost, things won’t work, and you will end up with a code access security violation exception. So, you must remain consistent about the URL of the WCF Service and the XBAP Host.

PublishWizard.jpg

Using the WsHttpBinding configuration

You can also use WsHttpBinding to communicate with WCF, but a few things need to be configured to ensure that you don’t suffer from code access security exceptions. If you want to use WsHttpBinding, you don’t have to create any new binding. Visual Studio 2008, by default, creates two end points for a WCF Service application: WsHttpBinding and MaxHttpBinding. What the developer needs to do is to configure a new binding configuration. To accomplish this, edit the web.config of the WCF Service application. In the default window, you will see the first endpoint is configured with WsHttpBinding, and under the endpoint, a default binding is configured. It should say “(Default) Click to Create”. Just click to create a new binding configuration, and configure it not to use reliable session, and set the security mode to None. Shown below is the service mode configuration provided for better understanding; eventually, the WCF Configuration Editor will generate this sort of a markup.

<system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="NewBinding0" messageEncoding="Text">
          <reliableSession enabled="false"/>
          <security mode="None">
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <services>
      <service behaviorConfiguration="TESTWCF.Service1Behavior" name="TESTWCF.Service1">
        <endpoint address="" binding="wsHttpBinding" bindingConfiguration="NewBinding0"
          contract="TESTWCF.IService1">
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="TESTWCF.Service1Behavior">
          <serviceMetadata httpGetEnabled="true"/>
                    <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
</system.serviceModel>

Make sure that you disable reliable session and set security mode to “None” in both the client endpoint and the service’s endpoint binding configuration. Otherwise, XBAP can suffer from code access security exceptions.

A quick discussion on the data transfer limit

XBAP to WCF communication data transfer has a few limitations in the data transfer size. If you are transferring huge lists of objects that exceed the size specified in maxBufferSize and maxReceivedMessageSize in the web.config, the application will cause a receive limit exceeded exception. You can increase the size of maxBufferSize and maxReceivedMessageSize from web.config in the binding configuration section of the Service, but increasing the size will cause the application to suffer from code access permission exceptions. So, a very straightforward way to escape from this issue is to make your Service in such a way that you don’t return data that exceed the size limit. And, if you have huge data to transfer, change the service contract in such a way that you can transfer data in multiple requests, and in every request, the size limit should remain under maxBufferSize.

Conclusion

In a few cases, you will see that the Service is taking a little bit time to respond to your request, and that can cause your application to become irresponsive for a few seconds. To escape from this problem, you can use a background process to call the WCF Service, and display a wait screen to the user and hide the wait screen after the process finishes execution. That concludes a beginner introduction to XBAP to WCF communication.

License

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

About the Author

Rahman Masudur
Software Developer (Senior) Satori Tech Solutions, Inc.
Australia Australia
About Md. Masudur Rahman
 
Masudur currently works at Satori Tech Solutions, Inc. as a software developer. Masudur Lives in Sydney, Australia.
 
Awards
 
26 May 2009: Monthly competition: Best ASP.NET article of April 2009
 
24 Mar 2009: Monthly competition: Best ASP.NET article of February 2009
 
Masudur Blog
 
Masudur put down his interesting learning experiences in his blog at http://munnaondotnet.blogspot.com/.

Comments and Discussions

 
GeneralExcellent Article Pinmembermitchtaylorh9-Oct-10 4:50 
QuestionTaskDatabase.mdf.hidden-marked-as-virus?? Why was it renamed? PinmemberGerrit Horeis24-Sep-10 4:00 
GeneralAny problem regarding source code or running the source code PinmemberMasudur5-Feb-09 21:56 
Generalds PinmemberMember 29273064-Feb-09 22:05 
GeneralRe: ds PinmemberMember 29273064-Feb-09 22:06 
GeneralRe: ds PinmemberMember 29273064-Feb-09 22:07 
Questionthis is a good article, but it never work for me, I think maybe most of you have the same problem. Pinmembermalcolmxu6-Nov-08 4:08 
QuestionI am getting a error in my service . pls help me out!!! PinmemberDiya Mia14-Sep-08 22:52 
Generalnice article PinmemberMohammad Ashraful Alam31-Jul-08 2:06 
QuestionI keep getting the following error after logging in... HELP Pinmemberpatuww22-Jul-08 10:45 
AnswerRe: I keep getting the following error after logging in... HELP Pinmemberpatuww22-Jul-08 12:39 
GeneralRe: I keep getting the following error after logging in... HELP PinmemberMasudur22-Jul-08 19:37 
QuestionCan you put some light on xbap host Integration PinmemberMd. Asif Atick14-Jul-08 0:12 
GeneralAn excelent introduction to WPF Pinmemberbinidrarat13-Jul-08 7:10 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140421.2 | Last Updated 9 Feb 2009
Article Copyright 2008 by Rahman Masudur
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid