Skip navigation

Going Mobile with WCF

A Crash Course in Windows Mobile and WCF

I have received many questions about mobile devices communicating with WCF services. There are not a lot of resources available on this subject, so I decided to brush up on the details myself to provide some guidance 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 a crash course in WCF for the Windows Mobile device. If you are new to mobile development, I hope to provide you with the steps necessary to dip your toes in that pool of knowledge. If you also are new to WCF, you may find this article at least brings you up to speed in the context of mobile communications but discussions will also focus on how mobile communications with WCF compare to what the seasoned WCF developer would expect. I ll provide you with system set-up requirements to get started with mobile WCF clients; I ll explain how to design a WCF service for mobile consumption; I ll walk you through proxy generation for mobile applications, and; I ll summarize several relevant feature differences you ll encounter with WCF for mobile applications.

Windows Mobile and the .NET Compact Framework for Newbies

Windows Mobile is Microsoft s operating platform for running mobile applications the latest version being Windows Mobile 6.1. To build managed applications for Windows Mobile devices, developers use the .NET Compact Framework, which provides a subset of .NET Framework functionality with a much smaller footprint. Windows Mobile 6 devices include the latest version of the .NET Compact Framework 3.5.

Windows Mobile devices are either Pocket PCs or Smartphones. A Pocket PC is a Personal Digital Assistant (PDA), which is basically a hand-held computer that receives input from a stylus or keyboard, depending on the device. Pocket PCs that double as phones usually have a keyboard for input. For development purposes, standard Pocket PC devices are referred to as Windows Mobile 6 Classic devices, while Pocket PC phone devices are referred to as Windows Mobile 6 Professional devices. Smartphones are like Pocket PCs with a smaller form factor and typically rely only on keyed input of some sort, not a stylus or touch screen. For development purposes, these devices 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 or device 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 for Windows Mobile 6 devices:

         Microsoft Windows Mobile Device Center 6.1 for Windows Vista

         Windows Mobile 6 Professional and Standard Software Development Kits Refresh

         Windows Mobile 6.1 Emulator Images

         Power Toys for .NET Compact Framework 3.5

Note: Links to 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) is accessible as a Control Panel feature (see Figure 1). WMDC lets you interact with your cradled devices or emulators including file copying and synchronization activities.

Figure 1

Figure 1: Windows Mobile Device Center from Control Panel

The Windows Mobile 6 SDKs provide necessary Visual Studio tools, templates, and emulator images for Windows Mobile 6, as well as code samples. There are two SDKs:

         Windows Mobile 6 Standard (provides tools for Smartphone development).

         Windows Mobile 6 Professional (provides tools for Pocket PC development).

You should install both SDKs, as they are not cumulative. In addition, install the Windows Mobile 6.1 Emulator Images if you want to work with the latest emulators. Later in this article I ll walk through using a device template and setting up Visual Studio for emulator testing.

Power Toys for the .NET Compact Framework 3.5 provides several tools for Windows Mobile development. The most relevant to this discussion 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 mobile application to consume a WCF service, let s create a simple WCF service and discuss some of the design constraints you should consider for mobile scenarios. The steps for designing, implementing, and hosting a WCF service are as follows:

         Design the service contract

         Implement the service contract on a service type

         Initialize the ServiceHost for that service type

         Supply service endpoints, custom binding configurations if applicable, and configure runtime behaviors

As we walk through these steps I will comment on any special considerations for mobile clients.

Consider the simple example of a service contract and service type implementation shown in Figure 2. The service contract is a CLR interface (IGreetingService) decorated with the ServiceContractAttribute, each method decorated with the OperationContractAttribute to include it in the service metadata. You typically supply a Namespace to the ServiceContractAttribute to disambiguate messages on the wire. So far, this is typical 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 and implementation for mobile clients

The service type (GreetingService) implements the service contract and coordinates calls to the business and data tier. In this case, it is a simple service and the implementation is in the service type. The ServiceBehaviorAttribute is used to apply service behaviors that are tightly coupled 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 contract that will work for both non-mobile and mobile clients although there are many differences in how the mobile client code is generated. Figure 3 describes key features of a service contract, whether or not they can be implemented at the service and still support mobile clients, and how that feature is supported in the mobile client proxy.

Figure 3

Figure 3: Mobile support for service contract features

What this should tell you is that requiring sessions or transactions, employing stream parameters, and the use of callback contracts are all deal breakers for calling a service from a mobile device. In later 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 contract respecting the limitations in Figure 3, and implemented your service type, you can host the service and expose endpoints that can be called by your mobile application. Assuming you are hosting on Windows Server 2003 or Windows Server 2008 machines you ll typically host services in Internet Information Services (IIS), Windows Process Activation Service (WAS), or self host in a Windows Service the only requirement is that you expose one or more HTTP-based endpoints configured to be compatible with mobile client requirements.

For testing purposes I always create a console host. 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();

else

host.Close();

}

Instead of hard-coding endpoints, this code assumes that endpoints will be configured in the app.config (or web.config for IIS and WAS hosting). Figure 4 shows the section for the GreetingService described in Figure 2. A single endpoint is exposed over BasicHttpBinding which means it is a simple SOAP 1.1 endpoint without security features. This is a good way to test that your mobile application can reach the service before you begin adding necessary security features (which I ll discuss later). In addition, you ll want to expose a metadata exchange endpoint, using MexHttpBinding (a variation of WSHttpBinding without security) so that you can generate a proxy for the mobile application.









































Figure 4: A simple example of a mobile-compatible service model configuration

The associated service behavior (see the section) enables metadata exchange behavior to support the endpoint, and HTTP browsing (so you can view the WSDL document in the browser). The debug setting to includeExceptionDetailsInFaults should be set to false on production (frankly, this setting is not very useful for debugging mobile applications, as NetCF leaves much to be desired in the way of handling faults thrown by the service channel).

With this you now have a mobile-compatible service configuration and can begin to look at creating your first mobile application to consume a WCF service.

Creating a Simple Mobile Application

You ll have access to the latest templates and emulators to build and debug a mobile application after installing the prerequisites described earlier. So, to begin creating your first mobile application create a new project, then select the Smart Device project type and the Smart Device Project template. This will lead to a second dialog box (both shown in Figure 5) from which you can select from a few NetCF project templates. It is important that you create mobile device projects using one of these templates as this restricts the project to using only NetCF assemblies (so you are working with the correct functionality sandbox). By default, the NetCF version will be 3.5 and this is what you want in order to support WCF client code. As for the target platform, you can select from Windows Mobile 6 Professional or Standard SDK depending on if you want to create a Pocket PC or Smartphone application. With regards to communication with WCF services, both support NetCF 3.5.

Figure 5

Figure 5: Smart Device templates for creating mobile applications

In this case, you ll use the Device Application template to create a mobile client. This generates a form that presents a device image where you can drop controls, as you would any Windows Forms or Windows Presentation Foundation (WPF) application, to design the UI. Figure 6 shows the UI for the GreetingService sample.

Figure 6

Figure 6: A sample mobile device application to call the GreetingService from Figure 2

The point of this section was to make sure you are aware of the requirement to use Smart Device templates for mobile clients. Next I ll explain how to generate a proxy to call a WCF service from a mobile application.

Proxy Generation for Mobile Applications

Traditionally you would use Add Service Reference from the Solution Explorer in Visual Studio, or directly call SvcUtil.exe (SvcUtil), to generate proxies for WCF client applications. For mobile applications there isn t an Add Service Reference function, and you shouldn t use SvcUtil to generate proxies because this does not generate code compatible with 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 generate a proxy and related contracts from a WSDL document or from a metadata exchange endpoint (like the one we enabled earlier). So, for example, you can write a batch file that generates a proxy for the GreetingService shown in Figure 2 by using metadata exchange against the base address shown configured in Figure 4. The following example illustrates generating a proxy named GreetingServiceClient for the GreetingService, including a namespace consistent with the client application for generated code:

netcfsvcutil.exe /namespace:*,Greetings.MobileClient/

out:GreetingServiceClient http://localhost:8000

Note: As with SvcUtil, you also can specify /language (this defaults to C#), /reference (to use types in referenced assemblies), and /collectionType (to use a specific type for arrays and dictionaries).

Figure 7 lists the code generated from this command. The contents of CFClientBase.cs are consistent to all services for which proxies are generated. Types generated in GreetingServiceClient.cs are specific to the service. In this example no data contracts are used; however, types representative of each data contract are also generated if they are part of the metadata for the service.

Figure 7

Figure 7: Files and types generated by NetCFSvcUtil for the GreetingService

When you use NetCFSvcUtil to generate a proxy, it inspects the service endpoint configuration and its metadata to ensure they are mobile-compatible. If the target service is not compatible, an error will be displayed. For example, a proxy cannot be generated if the service doesn t expose any endpoints compatible with mobile binding requirements. In some cases the tool will still generate a proxy with a warning to the developer that it will not work as expected. One example of this is when you try to generate a proxy for a service that relies on message contracts (types marked with MessageContractAttribute) to require custom headers.

Because mobile devices do not have access to the code necessary to process the configuration section, NetCFSvcUtil generates code to produce the endpoint address and binding configuration. For the service in Figures 2 and 4, the GreetingServiceClient proxy exposes a static property named EndpointAddress:

public static EndpointAddress EndpointAddress = new
EndpointAddress("http://localhost:8000/GreetingService");

In addition, a static method named CreateDefaultBinding returns a runtime representation of the binding. In this case, a CustomBinding equivalent for BasicHttpBinding defaults is returned:

public static Binding CreateDefaultBinding()

{

CustomBinding binding = new CustomBinding();

binding.Elements.Add(new

TextMessageEncodingBindingElement(

MessageVersion.Soap11, Encoding.UTF8));

binding.Elements.Add(new

HttpTransportBindingElement());

return binding;

}

Note: One apparent limitation seems to be that NetCFSvcUtil only generates code for the first endpoint it finds with which it is compatible with mobile devices (during proxy generation).

After you ve generated the proxy using NetCFSvcUtil, you can write code to call the service from your mobile application. The following code illustrates using the static binding and endpoint address exposed by the proxy, GreetingServiceClient, to initialize the proxy before calling the Greet operation:

Binding binding =

GreetingServiceClient.CreateDefaultBinding();

string address =

GreetingServiceClient.EndpointAddress.Uri.ToString();

GreetingServiceClient m_proxy =

new GreetingServiceClient(binding, new

EndpointAddress(address));

string result = m_proxy.Greet(txtName.Text).ToString();

Note: Mobile devices are unable to resolve localhost to the correct IP address or machine name where the service is hosted. The accompanying code download provides a readme file with workarounds for this issue to streamline development.

Testing the Solution

So far I ve walked you through installing the required prerequisites for mobile WCF development, creating a WCF service and hosting it with mobile-compatible endpoints, creating a simple mobile application, generating a proxy using NetCFSvcUtil, and writing code to invoke the service. Now it s time to test the code! To do this there are yet a few more steps to be aware of for running your mobile application in a mobile device emulator.

The following steps need only be performed once to set up your testing environment for your mobile application:

         Launch the Windows Mobile Device Center from Control Panel (discussed earlier)

         From Visual Studio, launch the Device Emulator Manager (DEM), then connect a device emulator and cradle it

         From the Windows Mobile Device Center connect to the device

You can launch the Device Emulator Manager from the Visual Studio Tools menu. This brings up a dialog box from which you can select the emulator to which you want to connect for testing. You will typically choose an emulator from the Windows Mobile 6 Professional or Standard SDK root. Within these categories are several emulators, but you ll recognize the Windows Mobile 6 Professional, Classic, and Standard headings I mentioned earlier, which are representative of Pocket PC and Smartphone development. Figure 8 illustrates connecting to the Professional emulator.

Figure 8

Figure 8: The Device Emulator Manager and Windows Mobile Device Center

You ll first right-click on the emulator and select Connect from the context menu. A green arrow will appear next to the emulator and the WMDC also will show as connected (see Figure 8). In addition, the selected emulator will be launched in a separate window in this case, the Windows Mobile 6 Professional Emulator. Next, right-click the emulator again and select Cradle. The arrow icon will change to a cradle icon. The final step is to select the option to connect to the device without setting it up (from WMDC). At this point, you can use WMDC to interact with the device, such as copying files to and from the device for testing. This is useful for copying certificates for security scenarios, for example.

From the WMDC select Mobile Device Settings and edit Connection Settings to match those shown in Figure 9.

Figure 9

Figure 9: Recommended connection settings for WMDC

When you ve executed these steps, the Device Emulator Manager will continue to run in the background, and the selected emulator also will remain open in a separate window. Even if you close all Visual Studio instances, these continue to run which saves you time if you reload your project and wish to continue testing with the same emulator. You ll only have to repeat these steps if you close the emulator window (which can be a force of habit while debugging) or if you shut down the DEM with brute force.

Now, with the emulator running, you can test your code. It is helpful to test the mobile client from a separate Visual Studio instance. Run the service host first, then run the mobile client application in debug mode. This will bring up a deployment dialog box asking what you want to deploy. Select Windows Mobile Professional Device by selecting the device instead of the emulator you are deploying to whichever device the WMDC is connected which will be helpful when you are testing deployment to a physical cradled device. This dialog box will be presented each time you debug the client.

Contracts and Serialization

This example did not include any complex types in the service contract, but of course this is necessary in any real business case. When you develop WCF services to be compatible with mobile applications you can still work with the following:

         Plain Old CLR Objects (POCO), which are plain types without any attributes

         Traditional data contracts marked with the DataContractAttribute and DataMemberAttribute

         Serializable types, marked with the SerializableAttribute

         XML serializable types, which imply the XmlSerializer is in use and that types are decorated with XML serializer attributes to control serialization (XmlElementAttribute, for example)

Regardless of how the service implements these types included in the service contract, NetCFSvcUtil will generate XML serializable types to be used by the proxy. These types are still wire compatible with the service, and thus this is transparent to the developer. In fact, unless there is a problem, you should not have to look at the generated types generated by the proxy.

Binding Compatibility

In this example I suggested you start with BasicHttpBinding because it is a simple way to verify that your mobile client is connecting properly with your service. Only a limited set of configurations for BasicHttpBinding and CustomBinding are supported on mobile devices (there are some other bindings based on mail transport, but I ll exclude these from the discussion for the sake of simplicity). First and foremost, only Text encoding over HTTP transport is supported so a CustomBinding configuration can only use binding elements consistent with this requirement. As for securing communications, you ll typically use one of the following configurations:

         HTTP messaging without security, although it is rare 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 are not directly supported; however, you could roll your own solution with custom headers sent from the mobile application, then rely on SSL to secure communications. The accompanying sample code will illustrate these scenarios.

Conclusion

Developing applications for mobile devices may not be in your repertoire, but hopefully this article has given you the fundamentals so that if you wanted to go mobile and communicate with your WCF services, 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 aspects of 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 complete set of resources for mobile WCF development. Enjoy!

Download the samples for this article at www.dasblonde.net/downloads/aspprojuly09.zip.

Michele Leroux Bustamante ([email protected]) is Chief Architect of IDesign, Microsoft Regional Director for San Diego, Microsoft MVP for Connected Systems, and is on the board of directors for the International Association of Software Architects.

Additional Resources

Learning WCF, O Reilly 2007 (reprinted for VS 2008, July 2008): www.thatindigogirl.com (get all the latest book code here!)

Michele s blog: www.dasblonde.net

IDesign: www.idesign.net

Michele Leroux Bustamante provides a crash course in Windows Mobile and WCF as she explores how to build connected applications for Windows Mobile devices using WCF as the communication mechanism.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish