Going Mobile with WCF
A Crash Course in Windows Mobile and WCF
October 30, 2009
I have received many questions about mobile devicescommunicating with WCF services. There are not a lot of resources available onthis subject, so I decided to brush up on the details myself to provide someguidance here. For more information on mobile development, see "Mobile Development Options for .NET Developers"and "Better Mobile Website Development Using the jQuery Mobile Library."
The goal of this article is to provide you with acrash course in WCF for the Windows Mobile device. If you are new to mobiledevelopment, I hope to provide you with the steps necessary to dip your toes inthat pool of knowledge. If you also are new to WCF, you may find this articleat least brings you up to speed in the context of mobile communications butdiscussions will also focus on how mobile communications with WCF compare towhat the seasoned WCF developer would expect. I ll provide you with systemset-up requirements to get started with mobile WCF clients; I ll explain how todesign a WCF service for mobile consumption; I ll walk you through proxygeneration for mobile applications, and; I ll summarize several relevantfeature differences you ll encounter with WCF for mobile applications.
Windows Mobile and the .NET Compact Framework for Newbies
Windows Mobile is Microsoft s operating platformfor running mobile applications the latest version being Windows Mobile 6.1. Tobuild managed applications for Windows Mobile devices, developers use the .NETCompact Framework, which provides a subset of .NET Framework functionality witha much smaller footprint. Windows Mobile 6 devices include the latest versionof the .NET Compact Framework 3.5.
Windows Mobile devices are either Pocket PCs orSmartphones. A Pocket PC is a Personal Digital Assistant (PDA), which isbasically a hand-held computer that receives input from a stylus or keyboard,depending on the device. Pocket PCs that double as phones usually have akeyboard for input. For development purposes, standard Pocket PC devices arereferred to as Windows Mobile 6 Classic devices, while Pocket PC phone devicesare referred to as Windows Mobile 6 Professional devices. Smartphones are likePocket PCs with a smaller form factor and typically rely only on keyed input ofsome sort, not a stylus or touch screen. For development purposes, thesedevices are referred to as Windows Mobile 6 Standard devices.
The Windows Mobile 6 device label Professional,Classic, or Standard becomes relevant when it is time to select an emulator ordevice as you develop mobile applications with Visual Studio 2008.
Ready, Set, Mobile!
Assuming you ve installed Visual Studio 2008 SP1,you ll need to install a few other platform tools to develop applications forWindows Mobile 6 devices:
Microsoft Windows Mobile Device Center 6.1 forWindows Vista
Windows Mobile 6 Professional and StandardSoftware Development Kits Refresh
Windows Mobile 6.1 Emulator Images
Power Toys for .NET Compact Framework 3.5
Note: Linksto these resources are provided in the readme file in the accompanying code file;see end of article for download details.
The Windows Mobile Device Center (WMDC) isaccessible as a Control Panel feature (see Figure 1). WMDC lets you interactwith your cradled devices or emulators including file copying andsynchronization activities.
Figure 1: Windows Mobile Device Center fromControl Panel
The Windows Mobile 6 SDKs provide necessary VisualStudio tools, templates, and emulator images for Windows Mobile 6, as well ascode samples. There are two SDKs:
Windows Mobile 6 Standard (provides tools forSmartphone development).
Windows Mobile 6 Professional (provides toolsfor Pocket PC development).
You should install both SDKs, as they are notcumulative. In addition, install the Windows Mobile 6.1 Emulator Images if youwant to work with the latest emulators. Later in this article I ll walk throughusing a device template and setting up Visual Studio for emulator testing.
Power Toys for the .NET Compact Framework 3.5provides several tools for Windows Mobile development. The most relevant to thisdiscussion is the ServiceModel Metadata Tool for the .NET Compact Framework(NetCF). We ll use this to generate proxies in a later section.
Creating a WCF Service for Mobile Clients
Before we explore how you will create a mobileapplication to consume a WCF service, let s create a simple WCF service anddiscuss some of the design constraints you should consider for mobilescenarios. The steps for designing, implementing, and hosting a WCF service areas follows:
Design the service contract
Implement the service contract on a service type
Initialize the ServiceHost for that service type
Supply service endpoints, custom bindingconfigurations if applicable, and configure runtime behaviors
As we walk through these steps I will comment onany special considerations for mobile clients.
Consider the simple example of a service contractand service type implementation shown in Figure 2. The service contract is aCLR interface (IGreetingService) decorated with the ServiceContractAttribute,each method decorated with the OperationContractAttribute to include it in theservice metadata. You typically supply a Namespace to theServiceContractAttribute to disambiguate messages on the wire. So far, this istypical for any WCF service.
[ServiceContract(Namespace = "urn:mobilewcf/samples/2009/04")]public interface IGreetingService{[OperationContract]string Greet(string firstname);}[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]public class GreetingService : IGreetingService{public string Greet(string firstname){if (string.IsNullOrEmpty(firstname)){Console.WriteLine("ERROR: You must provide a valid name to receive a greeting.");throw new InvalidOperationException("You must provide a valid name to receive a greeting.");}string s = string.Format("Greetings {0}.", firstname);Console.WriteLine(s);return s;}}
Figure 2: A simple service contract andimplementation for mobile clients
The service type (GreetingService) implements theservice contract and coordinates calls to the business and data tier. In thiscase, it is a simple service and the implementation is in the service type. TheServiceBehaviorAttribute is used to apply service behaviors that are tightlycoupled to the implementation. Although irrelevant to the mobile application,InstanceContextMode is typically set to PerCall (as illustrated in Figure 2).
Fundamentally, you can design a service contractthat will work for both non-mobile and mobile clients although there are manydifferences in how the mobile client code is generated. Figure 3 describes keyfeatures of a service contract, whether or not they can be implemented at theservice and still support mobile clients, and how that feature is supported inthe mobile client proxy.
Figure 3: Mobile support for service contractfeatures
What this should tell you is that requiringsessions or transactions, employing stream parameters, and the use of callbackcontracts are all deal breakers for calling a service from a mobile device. Inlater sections I ll elaborate on some of the other points in Figure 3. For now,let s move on to hosting the service and exposing mobile-compatible endpoints.
Exposing Mobile-compatible Service Endpoints
Once you ve designed the service contractrespecting the limitations in Figure 3, and implemented your service type, youcan host the service and expose endpoints that can be called by your mobileapplication. Assuming you are hosting on Windows Server 2003 or Windows Server2008 machines you ll typically host services in Internet Information Services(IIS), Windows Process Activation Service (WAS), or self host in a WindowsService the only requirement is that you expose one or more HTTP-based endpointsconfigured to be compatible with mobile client requirements.
For testing purposes I always create a consolehost. Here is a very simple example of the ServiceHost initialization code:
ServiceHost host = new ServiceHost(typeof(GreetingService));try{host.Open();Console.ReadLine();}finally{if (host.State == CommunicationState.Faulted)host.Abort();elsehost.Close();}
Instead of hard-coding endpoints, this code assumesthat endpoints will be configured in the app.config (or web.config for IIS andWAS hosting). Figure 4 shows the section for theGreetingService described in Figure 2. A single endpoint is exposed overBasicHttpBinding which means it is a simple SOAP 1.1 endpoint without securityfeatures. This is a good way to test that your mobile application can reach theservice before you begin adding necessary security features (which I ll discusslater). In addition, you ll want to expose a metadata exchange endpoint, usingMexHttpBinding (a variation of WSHttpBinding without security) so that you cangenerate a proxy for the mobile application.
Figure 4: A simple example of amobile-compatible service model configuration
The associated service behavior (see the section) enables metadata exchange behavior to supportthe endpoint, and HTTP browsing (so you can view the WSDL document in thebrowser). The debug setting to includeExceptionDetailsInFaults should be set tofalse on production (frankly, this setting is not very useful for debuggingmobile applications, as NetCF leaves much to be desired in the way of handlingfaults thrown by the service channel).
With this you now have a mobile-compatible serviceconfiguration and can begin to look at creating your first mobile applicationto consume a WCF service.
Creating a Simple Mobile Application
You ll have access to the latest templates andemulators to build and debug a mobile application after installing theprerequisites described earlier. So, to begin creating your first mobileapplication create a new project, then select the Smart Device project type andthe Smart Device Project template. This will lead to a second dialog box (bothshown in Figure 5) from which you can select from a few NetCF projecttemplates. It is important that you create mobile device projects using one ofthese templates as this restricts the project to using only NetCF assemblies (soyou are working with the correct functionality sandbox). By default, the NetCFversion will be 3.5 and this is what you want in order to support WCF clientcode. As for the target platform, you can select from Windows Mobile 6Professional or Standard SDK depending on if you want to create a Pocket PC orSmartphone application. With regards to communication with WCF services, bothsupport NetCF 3.5.
Figure 5: Smart Device templates for creatingmobile applications
In this case, you ll use the Device Applicationtemplate to create a mobile client. This generates a form that presents adevice image where you can drop controls, as you would any Windows Forms orWindows Presentation Foundation (WPF) application, to design the UI. Figure 6shows the UI for the GreetingService sample.
Figure 6: A sample mobile device applicationto call the GreetingService from Figure 2
The point of this section was to make sure you areaware of the requirement to use Smart Device templates for mobile clients. NextI ll explain how to generate a proxy to call a WCF service from a mobileapplication.
Proxy Generation for Mobile Applications
Traditionally you would use Add Service Referencefrom the Solution Explorer in Visual Studio, or directly call SvcUtil.exe(SvcUtil), to generate proxies for WCF client applications. For mobileapplications there isn t an Add Service Reference function, and you shouldn tuse SvcUtil to generate proxies because this does not generate code compatiblewith the subset of WCF functionality available to mobile devices. Fortunately,Power Toys (mentioned earlier) includes a SvcUtil equivalent for NetCF:NetCFSvcUtil.exe (NetCFSvcUtil).
Like SvcUtil, NetCFSvcUtil can be used to generatea proxy and related contracts from a WSDL document or from a metadata exchangeendpoint (like the one we enabled earlier). So, for example, you can write abatch file that generates a proxy for the GreetingService shown in Figure 2 byusing metadata exchange against the base address shown configured in Figure 4.The following example illustrates generating a proxy namedGreetingServiceClient for the GreetingService, including a namespace consistentwith the client application for generated code:
netcfsvcutil.exe/namespace:*,Greetings.MobileClient/
out:GreetingServiceClienthttp://localhost:8000
Note: As withSvcUtil, you also can specify /language (this defaults to C#), /reference (touse types in referenced assemblies), and /collectionType (to use a specifictype for arrays and dictionaries).
Figure 7 lists the code generated from thiscommand. The contents of CFClientBase.cs are consistent to all services forwhich proxies are generated. Types generated in GreetingServiceClient.cs arespecific to the service. In this example no data contracts are used; however,types representative of each data contract are also generated if they are partof the metadata for the service.
Figure 7: Files and types generated byNetCFSvcUtil for the GreetingService
When you use NetCFSvcUtil to generate a proxy, itinspects the service endpoint configuration and its metadata to ensure they aremobile-compatible. If the target service is not compatible, an error will bedisplayed. For example, a proxy cannot be generated if the service doesn texpose any endpoints compatible with mobile binding requirements. In some casesthe tool will still generate a proxy with a warning to the developer that it willnot work as expected. One example of this is when you try to generate a proxyfor a service that relies on message contracts (types marked withMessageContractAttribute) to require custom headers.
Because mobile devices do not have access to thecode necessary to process the configurationsection, NetCFSvcUtil generates code to produce the endpoint address andbinding configuration. For the service in Figures 2 and 4, theGreetingServiceClient proxy exposes a static property named EndpointAddress:
public static EndpointAddress EndpointAddress = newEndpointAddress("http://localhost:8000/GreetingService");
In addition, a static method namedCreateDefaultBinding returns a runtime representation of the binding. In thiscase, a CustomBinding equivalent for BasicHttpBinding defaults is returned:
public static Binding CreateDefaultBinding(){CustomBinding binding = new CustomBinding();binding.Elements.Add(newTextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8));binding.Elements.Add(newHttpTransportBindingElement());return binding;}
Note: Oneapparent limitation seems to be that NetCFSvcUtil only generates code for thefirst endpoint it finds with which it is compatible with mobile devices (duringproxy generation).
After you ve generated the proxy usingNetCFSvcUtil, you can write code to call the service from your mobileapplication. The following code illustrates using the static binding andendpoint address exposed by the proxy, GreetingServiceClient, to initialize theproxy before calling the Greet operation:
Binding binding =GreetingServiceClient.CreateDefaultBinding();string address =GreetingServiceClient.EndpointAddress.Uri.ToString();GreetingServiceClient m_proxy =new GreetingServiceClient(binding, newEndpointAddress(address));string result = m_proxy.Greet(txtName.Text).ToString();
Note: Mobiledevices are unable to resolve localhost to the correct IP address or machinename where the service is hosted. The accompanying code download provides areadme file with workarounds for this issue to streamline development.
Testing the Solution
So far I ve walked you through installing therequired prerequisites for mobile WCF development, creating a WCF service andhosting it with mobile-compatible endpoints, creating a simple mobileapplication, generating a proxy using NetCFSvcUtil, and writing code to invokethe service. Now it s time to test the code! To do this there are yet a fewmore steps to be aware of for running your mobile application in a mobiledevice emulator.
The following steps need only be performed once toset up your testing environment for your mobile application:
Launch the Windows Mobile Device Center fromControl Panel (discussed earlier)
From Visual Studio, launch the Device EmulatorManager (DEM), then connect a device emulator and cradle it
From the Windows Mobile Device Center connect tothe device
You can launch the Device Emulator Manager from theVisual Studio Tools menu. This brings up a dialog box from which you can selectthe emulator to which you want to connect for testing. You will typicallychoose an emulator from the Windows Mobile 6 Professional or Standard SDK root.Within these categories are several emulators, but you ll recognize the WindowsMobile 6 Professional, Classic, and Standard headings I mentioned earlier,which are representative of Pocket PC and Smartphone development. Figure 8illustrates connecting to the Professional emulator.
Figure 8: The Device Emulator Manager andWindows Mobile Device Center
You ll first right-click on the emulator and selectConnect from the context menu. A green arrow will appear next to the emulatorand the WMDC also will show as connected (see Figure 8). In addition, theselected emulator will be launched in a separate window in this case, theWindows Mobile 6 Professional Emulator. Next, right-click the emulator againand select Cradle. The arrow icon will change to a cradle icon. The final stepis to select the option to connect to the device without setting it up (fromWMDC). At this point, you can use WMDC to interact with the device, such ascopying files to and from the device for testing. This is useful for copyingcertificates for security scenarios, for example.
From the WMDC select Mobile Device Settings andedit Connection Settings to match those shown in Figure 9.
Figure 9: Recommended connection settings forWMDC
When you ve executed these steps, the DeviceEmulator Manager will continue to run in the background, and the selectedemulator also will remain open in a separate window. Even if you close allVisual Studio instances, these continue to run which saves you time if youreload your project and wish to continue testing with the same emulator. You llonly have to repeat these steps if you close the emulator window (which can bea force of habit while debugging) or if you shut down the DEM with brute force.
Now, with the emulator running, you can test yourcode. It is helpful to test the mobile client from a separate Visual Studioinstance. Run the service host first, then run the mobile client application indebug mode. This will bring up a deployment dialog box asking what you want todeploy. Select Windows Mobile Professional Device by selecting the device insteadof the emulator you are deploying to whichever device the WMDC isconnected which will be helpful when you are testing deployment to a physicalcradled device. This dialog box will be presented each time you debug theclient.
Contracts and Serialization
This example did not include any complex types inthe service contract, but of course this is necessary in any real businesscase. When you develop WCF services to be compatible with mobile applicationsyou can still work with the following:
Plain Old CLR Objects (POCO), which are plaintypes without any attributes
Traditional data contracts marked with theDataContractAttribute and DataMemberAttribute
Serializable types, marked with theSerializableAttribute
XML serializable types, which imply the XmlSerializeris in use and that types are decorated with XML serializer attributes tocontrol serialization (XmlElementAttribute, for example)
Regardless of how the service implements thesetypes included in the service contract, NetCFSvcUtil will generate XMLserializable types to be used by the proxy. These types are still wirecompatible with the service, and thus this is transparent to the developer. Infact, unless there is a problem, you should not have to look at the generatedtypes generated by the proxy.
Binding Compatibility
In this example I suggested you start withBasicHttpBinding because it is a simple way to verify that your mobile clientis connecting properly with your service. Only a limited set of configurationsfor BasicHttpBinding and CustomBinding are supported on mobile devices (thereare some other bindings based on mail transport, but I ll exclude these fromthe discussion for the sake of simplicity). First and foremost, only Textencoding over HTTP transport is supported so a CustomBinding configuration canonly use binding elements consistent with this requirement. As for securingcommunications, you ll typically use one of the following configurations:
HTTP messaging without security, although it israre that security is not a requirement for a production service
HTTPS messaging with SSL negotiation
Mutual certificate security without SSL
Unfortunately, username and password scenarios arenot directly supported; however, you could roll your own solution with customheaders sent from the mobile application, then rely on SSL to securecommunications. The accompanying sample code will illustrate these scenarios.
Conclusion
Developing applications for mobile devicesmay not be in your repertoire, but hopefully this article has given you thefundamentals so that if you wanted to go mobile and communicate with your WCFservices, you have the steps to get you there.
I want to give a shout out to Nick Landry,a good friend of mine who is a mobile genius and who contributed to the mobile aspectsof this article. For additional documentation, you should visit wcfguidanceformobile.codeplex.com,a community project on which I am working with Nick to provide a more completeset of resources for mobile WCF development. Enjoy!
Download thesamples for this article at www.dasblonde.net/downloads/aspprojuly09.zip.
Michele Leroux Bustamante ([email protected]) is ChiefArchitect of IDesign, Microsoft Regional Director for San Diego, Microsoft MVPfor Connected Systems, and is on the board of directors for the InternationalAssociation of Software Architects.
AdditionalResources
Learning WCF, O Reilly 2007 (reprinted for VS 2008,July 2008): www.thatindigogirl.com(get all the latest book code here!)
Michele sblog: www.dasblonde.net
IDesign:www.idesign.net
Michele Leroux Bustamante provides a crashcourse in Windows Mobile and WCF as she explores how to build connectedapplications for Windows Mobile devices using WCF as the communicationmechanism.
About the Author
You May Also Like