Using Symbian OS

. E e e o men NS 0 N TD v l p to 6

3

.NET Development on S60
part of the Using Symbian OS series
1st edition, 10/08 Published by: Symbian Software Limited 2-6 Boundary Row Southwark London SE1 8HP UK www.symbian.com Trademarks, copyright, disclaimer ‘Symbian’, ‘Symbian OS’ and other associated Symbian marks are all trademarks of Symbian Software Ltd. Symbian acknowledges the trademark rights of all third parties referred to in this material. Copyright © Symbian Software Ltd 2008. All rights reserved. No part of this material may be reproduced without the express written permission of Symbian Software Ltd. Symbian Software Ltd makes no warranty or guarantee about the suitability or the accuracy of the information contained in this document. The information contained in this document is for general information purposes only and should not be used or relied upon for any other purpose whatsoever. Compiled by: Paul Todd Managing Editor: Ashlee Godwin Reviewed by: Julian Ashworth David Caabeiro Antony Edwards Alexey Gusev Adriano Iorio Charlotte Mason Thibaut Rouffineau Jo Stichbury Alex Wilbur

4

Contents
S60 and Symbian OS ..................................................................................................................5 The .NET platform on S60...........................................................................................................5 The .NET runtime and C#............................................................................................................6 Using the .NET runtime: The basics ........................................................................................6 The benefits of the CLI............................................................................................................7 The .NET Compact Framework and Net60 ..................................................................................8 Net60: Under the hood ...........................................................................................................9 The application framework......................................................................................................9 Comparing Windows Mobile and S60 .......................................................................................10 Security and S60....................................................................................................................10 Getting started ...........................................................................................................................11 Building a simple application....................................................................................................12 Creating a new project...........................................................................................................12 Genesis ..................................................................................................................................14 Extending the application to access the network .....................................................................16 Extending the application to send an SMS ..............................................................................22 Examples and source code .......................................................................................................25 The RedFiveLabs.Mobile assembly and namespace. .......................................................25 Additional tools and utilities ....................................................................................................25 FXCop ....................................................................................................................................25 StyleCop ................................................................................................................................25 NDoc ......................................................................................................................................26 NUnit......................................................................................................................................26 Recommended S60 tools ..........................................................................................................26 A success story .........................................................................................................................26 Summary ...................................................................................................................................27 Recommended reading .............................................................................................................27 Developer resources..................................................................................................................28 Community web sites ............................................................................................................28

5

S60 and Symbian OS
Symbian OS is a modular operating system, constructed from well-defined, discrete components that combine to allow for configurability across a range of target hardware. At a high level, Symbian OS can be thought of as a layered model with a flexible architecture that allows different UI layers to run as platforms on top of the core operating system. The generic UI framework of Symbian OS supplies a common behavior and supports extension by UI vendors, who define their own look-and-feel. The S60 platform, supplied by Nokia, sits on top of Symbian OS. S60 is the world's most popular smartphone platform with 150 million units shipped, 80 models and four licensees (Nokia, Samsung, Lenovo and LG). S60 devices have become increasingly sophisticated, with high-resolution still and video cameras, location-based services, full web browsing, stereo music, mapping and Voice over IP (VoIP), to name just a few of the features now available. The range of S60 devices offered by licensees has also evolved, offering distinct collections of device models for consumers, enterprises and other specific market niches. For more information about S60, visit www.s60.com.

The .NET platform on S60
Applications on S60 are most frequently created using native C++ or Java ME, depending on the features required, but additional runtime support is available, including Python and Flash Lite (more information about the runtimes support can be found at developer.symbian.com/main/documentation/runtime_environments). If you prefer to use .NET for development then this booklet is for you! In this booklet, we explain how to use the .NET runtime on S60 devices using Net60, which provides an engine for running intermediate language code on S60 devices. Net60 is provided by Red Five Labs; see www.redfivelabs.com for further details. More specifically, this booklet is intended for you if you are: • A C# developer experienced with working on Microsoft Windows using .NET or with the .NET Compact Framework on Windows Mobile. • An S60 developer familiar with native C++ application development, taking your first steps into C# and the .NET runtime. • An Enterprise application developer looking to migrate .NET applications to, or develop them on, S60 devices. In this booklet, we will illustrate the key concepts and important features that will get you up to speed in building applications for S60 in C# and compiling them to the .NET framework. We will concentrate on the Windows Mobile Standard (Smartphone) edition as this is the Net60 target platform. You’ll notice some long URLs referenced in this booklet. Don’t worry – you don’t have to try to type them in! We’ve put each URL used in this booklet on its wiki page, at developer.symbian.com/nets60_wikipage, so that you can navigate to the web sites.

6

The .NET runtime and C#
This section provides a brief overview of the .NET Framework. If you already have experience with .NET, you may wish to skip this section and proceed to ‘The .NET Compact Framework and Net60.’ Further information about the history of .NET can be found on Wikipedia at en.wikipedia.org/wiki/Common_Language_Runtime, and at net-informations (vb.netinformations.com/framework/common_language_runtime.htm).

Using the .NET runtime: The basics
To use the .NET runtime, you’ll need to know about the Common Language Runtime and the Foundation Class Library. The Common Language Runtime (CLR) is the virtual machine component of the .NET Framework that provides an execution environment and common type system for all .NET applications. It is an implementation of an open standard called the Common Language Infrastructure (CLI), which specifies the byte code and the environment used as the .NET common runtime.1 The CLR executes programs that have been compiled into a platform-neutral language (a form of byte code) called Common Intermediate Language (CIL). Compilers that emit CIL are available for C#, Visual Basic .NET and many other popular programming languages including Python and Ruby (but this booklet will discuss only C#). The CLR usually translates CIL into native processor-specific instructions just prior to execution, as shown in Figure 1. The CLR provides a rich set of services such as memory management, resource management and exception handling, but its major function is to interpret byte code. The collection of classes that are compiled as IL in a DLL or executable is called an ‘assembly.’ An application built in Visual Studio is compiled into IL and is then packaged into an assembly which can be an executable or a DLL. In addition to the CLR, there is a large set of pre-built, tested functionality provided in assemblies to give access to services such as network access, data structure manipulation, XML parsing and so on. This is the Framework Class Library (FCL), although it may also sometimes be referred to as the Base Class Library (BCL).2 The FCL is a collection of thousands of reusable classes, interfaces and other types that provide rich support for a variety of application features. Because of its size, it is not practical or even possible to provide the desktop version of the FCL on a mobile device. Therefore, Microsoft provides a scaled-down version of the .NET Framework called the .NET Compact Framework (.NET CF) that has a CLR and class libraries specifically designed for Windows Mobile. A comparison of desktop and CF features can be found at msdn.microsoft.com/en-us/library/aa446549.aspx.

1 This specification now falls under open specifications ECMA-335 and ISO/IEC 23271. The most

notable implementation of this standard outside of that from Microsoft is the Mono Project which provides a CLR for Linux-based operating systems. 2 Technically speaking, the FCL comprises of Microsoft-specific extensions to the ECMA-approved BCL.

7

.NET compatible languages compile to a second platformneutral language, called Common Intermediate Language (CIL).

Figure 1: .NET build process components (Source: Wikimedia commons library at en.wikipedia.org/wiki/Image:Overview_of_the_Common_Language_Infrastructure.png) 1. C# developers using the .NET runtime write code using their preferred language. 2. At compile time, a .NET compiler converts this code into CIL code. 3. At runtime, the CLR converts the CIL code into binaries native to the operating system in question.

Benefits of the CLI
There are some key concepts to understand about the CLI. • The code that is run inside of the CLR interpreter is called ‘managed code.’ The CLR interpreter provides restricted access to native pointers and memory, meaning that typical application errors such as memory leaks and memory corruption will be significantly reduced. • Since managed code also manages memory and handles via the garbage collector, it is essential that you are familiar with how this works in order to understand when handles are freed. • Because of the strong type-checking, the compiler makes it extremely difficult to abuse type safety, which is moved into the realm of the CLR interpreter. Code that consists of compiled processor-specific instructions that are not portable between operating systems is called native code. A good example is the code that makes up system DLLs and provides access to system memory. Access to native code is strictly controlled by the CLR and needs to be performed within the confines of the CLI. Normally, managed code applications will access native code using a DLL. This is done using a specific API inside the CLR that hides the complexity by moving pointers from managed to unmanaged code in a safe and secure way.

8
Many of the issues that plague native code development, such as memory corruption, invalid pointers, resource leaks and type mismanagement, are handled by a combination of the CLR runtime and CLI compiler. For example, Symbian C++ developers need to use the cleanup stack and be very careful with memory and resource management. In contrast, when using the .NET runtime and the CLI, this is all moved to the CLR. You don’t need to worry about when an object will be deleted or what resources it owns because the CLR figures out when an object can be freed during a garbage collection cycle. Note that garbage collection is not ideally suited for resource-constrained devices, so there is also support within the runtime to allow you to control the destruction of objects. This is accomplished by implementing the IDisposable interface in a class, which tells the CLR that objects using this interface must be released immediately.

The .NET Compact Framework and Net60
In Net60, Red Five Labs provides a binary compatible version of the Microsoft .NET Compact Framework CLR and its associated libraries for S60. Applications built for Windows Mobile that use the .NET Compact Framework can thus run unchanged on S60, allowing easy porting from Windows Mobile to S60.

Figure 2: .NET Compact Framework on Symbian OS

9
At the time of writing, S60 applications are all keypad driven, and closely resemble those written for Microsoft smartphone devices. The form factor and functionality for S60 and Microsoft smartphones are very similar, making it much easier to port applications from one platform to the other. (Pocket PC applications are typically designed for touchscreen and keyboard-based devices). You should also note that, at the time of writing, Net60 only supports .NET CF 1.0, so you should be aware of the differences between this version and .NET CF 2.0. However, partial .NET CF 2.0 application support will be introduced in October 2008. Please see www.redfivelabs.com for updates about CF 2.0 support.

Net60: Under the hood
When installed on an S60 device, the Net60 CLR is installed into the \sys\bin folder. The framework class libraries are stored into the Global Assembly Cache (GAC) in the \resources folder. Net60 provides the following assemblies: • System.dll • System.Data.dll • System.Drawing.dll • System.Windows.Forms.dll • System.Web.Services.dll • System.Net.IrDA.dll • System.XML.dll • Microsoft.VisualBasic.dll • mscorlib.dll • RedFiveLabs.Mobile.dll. The Net60 installation package generator (Genesis) creates a simple native S60 application that registers itself with the application menu and installs the assembly that has been generated for .NET CF. When you click on the icon in the application menu, the executable starts the CLR and loads the managed application and all the required assemblies (the managed application is started in much the same way as on a Windows Mobile device).

The application framework
The application object’s Run() method is called and passed within the Main() function in a new form instance, which can hold controls. The controls for a C# form are created in code dynamically within the InitializeComponent() method (unlike traditional Windows and S60 applications, where a form is created from resources within a sophisticated application framework). This method creates and initializes each control, placing it on the form and filling it with the correct and relevant data. Fortunately, the Visual Studio IDE designer tool does this for you by allowing the controls to be dropped onto the form and their properties to be edited in a dialog. The application object then runs a message loop and processes events for the form control until Close() or Application.Exit() is called, at which point the form is closed and the application terminates. Take care when creating multiple forms, or forms with a large numbers of controls, as these can consume significant amounts of resources. You should assess carefully the trade-off between creating a form as needed and showing or hiding a form when designing an application. You should also be aware that some of the controls have minor

10
limitations when ported over to S60, such as not being skin aware. These limitations are discussed in the Net60 FAQ, at www.redfivelabs.com/content/faq.aspx. Note, too, that user interface objects are only accessible on the process thread on Windows Mobile and S60 because user interface responsiveness is critical. For example, if a thread is spawned to download some data from a remote site, any results from the thread object must be copied from the thread to the object; then, when the UI thread next executes, the data can be copied from the class to the UI controls. This technique uses objects called ‘delegates.’ It’s impossible to provide a full overview and details of how C# and its syntax work in this booklet alone. However, if you don’t already know C#, we recommended that you purchase a simple book on the language as it is used on Windows, since there are no differences in syntax between using C# with the Windows .NET framework and using Net60 on S60. There is a recommended reading list section at the end of this booklet.

Comparing Windows Mobile and S60
This booklet doesn’t discuss the fundamental differences between application development for Microsoft Windows Mobile and Symbian OS. If you’re coming from a Windows background, you may have some uncertainty about where to start with Symbian OS because the core APIs, tools and development environments are quite different to those used on Windows. If you need information about how to manage the differences, we recommend a paper on the Symbian Developer Network site that provides intermediate and advanced Windows CE and Windows Mobile developers with an introduction to porting applications from Windows Mobile to Symbian OS v9. The paper is available for download from developer.symbian.com/main/documentation/porting/#windows. We will, however, consider the issue of security and the differences in approach at this point, since it is a fundamental part of Symbian OS and S60 that also affects how you work with Net60.

Security and S60
Neither the .NET CF nor Net60 use the .NET policy-based security model. Instead, the CLR relies on the underlying operating system to provide security. Symbian OS and S60 have a very strict security model called ‘platform security,’ which is fundamentally different to that of Windows Mobile. More information about platform security can be found in the Symbian Press booklet, Platform security for all, available for download from developer.symbian.com/main/documentation/booklets/booklets_using.jsp. In Windows Mobile Standard (Smartphone), each executable code file (EXE or DLL) is signed with a certificate and then the installable CAB file is signed. There are a set of ‘privileged’ functions that perform highly restricted operations and require a special type of certificate from Microsoft. In general, these operations are very operator-centric and most developers will not need them. Windows Mobile also allows for executable files to be non-unique and to be placed anywhere on the device. The Windows loader searches the path in order to find the appropriate DLL or executable to be loaded or run respectively. This process is markedly different from the Symbian OS platform security model. On Symbian OS, each DLL or EXE file has a set of capabilities associated with it. A capability is used by the executable loader to prevent applications and DLLs from misusing APIs by controlling which APIs an application, and the DLLs that it loads, can access. In order to access a particular API group an application needs to have the right capability assigned to it.

11
Furthermore, a request to dynamically load a DLL will fail unless it has at least the same capabilities as the parent process; that is, if the DLL has a different set of capabilities to the parent process, or is missing a capability, then the DLL will not be loaded. This applies to both statically and dynamically linked DLLs. Capabilities are defined at compile time and checked during install time. The capabilities assigned to an executable cannot be changed after it has been installed. There is further information on DLLs and capabilities in the Platform security for all booklet. In addition, executable code must have a unique name and only executes if it’s stored in the \sys\bin folder. This folder is not visible or writable to applications except those deemed trusted by the system: the software installer, the file server and the kernel. In practice, this means that a binary must be placed in the \sys\bin folder by the software installer in order for code to run. During development, if you use certain APIs from the protected set (which is similar to the privileged APIs on Windows Mobile), you will need to obtain a developer certificate (a ‘devcert’) in order to sign and deploy the application onto a device. A devcert is associated with the IMEI of your device. When you are ready to release your application to a wider audience, you must submit it to Symbian Signed before you can distribute it. During the application’s subsequent installation on a mobile device, the Symbian OS software installer acts as the gatekeeper, and inspects software installation packages known as SIS files. It is responsible for ensuring that the capabilities required by the executable code in the package match those allowed by the certificate it was signed with. Further information about developer certificates and Symbian Signed can be found at www.symbiansigned.com, from where you can also download the introductory manual, A Guide to Symbian Signed. Fortunately, if you’re working on Net60, you should only ever need to use standard APIs. This means that devcerts or using Open Signed online is not generally necessary, and selfgenerated certificates are sufficient for self-signing, even for applications such as the SMS example provided later in this booklet.

Getting started
Net60 has been designed to make building applications as easy as possible and to make the most effective use of the best tools available for developing .NET applications. You need to use Visual Studio 2005 or 2008 Professional3 with Net60 as it allows you to develop mobile applications and to generate Microsoft .NET CF-compliant code suitable for running on the device. It provides a drag and drop environment as well as a Windows Mobile Standard emulator to help you debug your C# applications, which in turn reduces the write, run and debug cycle substantially. If you’re using Visual Studio 2005, we also recommend that you install Visual Studio Service Pack One, because this has a number of critical bug fixes that will improve its usability. You can find more information on Visual Studio 2005 on the MSDN site at msdn.microsoft.com/en-us/vs2005/aa718668.aspx.

3 Note that the Express version of Visual Studio does not support the creation of mobile

applications and so is unsuitable for the development of .NET CF applications.

12
For Net60 development, you should download the Net60.exe Windows installer from the Red Five Labs’ web site (www.redfivelabs.com/net60.exe) and install it to your Windows PC. You must install the Net60 SIS file that is included in this download on any device that you wish to deploy the .NET application on. This will ensure that the CLR is deployed to, and that the intermediate language code can be run on, the device. Details of licensing requirements and registration details can be obtained from Red Five Labs, as can a useful quick start guide, which is available at www.redfivelabs.com/content/quickstart.aspx.

Building a simple application
This tutorial creates a basic GUI application, and then extends it to communicate with the network to get the HTML text from the Internet. In the final section, the application is further extended so that it can send SMS messages to a specified phone number to illustrate how you can use code that interfaces with the native operating system outside of the CLR sandbox (although the same can be achieved with managed code using the RedFiveLabs.Mobile.dll namespace).

Creating a new project
It is as simple to build a GUI application for S60 as it is to build one for Windows Mobile Standard. 1. Start Visual Studio 2005, select New and Project from the File Menu and then navigate down the tree to select the Visual C# > Smart Device > Smartphone 2003 template list. 2. In the list of templates, select Device Application 1.0. (Readers using Visual Studio 2008 should follow a similar sequence, except that the target platform selected must be Windows Mobile 5.0 Smartphone SDK and the .NET framework targeted must be selected as .NET Compact Framework 2.0.) 3. At this point you must also enter a project and solution name, as shown in Figure 3.

Figure 3: Creating a mobile application project

13

4. Once you’ve created the project, the next step is to take the default project and drop the required controls onto the form. For this example, a label and an edit control have been placed on the form to allow the entry of a URL. The ‘Open’ command has been added to the menu bar at the bottom of the screen, as shown in Figure 4.

Figure 4: The .NET form designer

Microsoft Windows Mobile Standard devices have a different layout to that used by S60. The menu option is found on the right softkey and the action on the left softkey. To create a user experience in a Net60 application that is similar to a corresponding native S60 application, the Windows Mobile menus are swapped, so that the menu appears on the left softkey and the action on the right softkey. For more information about the standard look-and-feel of S60 devices, please consult the Usability documentation on the Forum Nokia web site, at www.forum.nokia.com/usability. For the first part of the example code, clicking the Open softkey displays a standard message box. Right clicking over the form and selecting View Code will display the C# code. Expanding the various, folded code blocks will show how a C# application is put together. Below is the event method that is called when a soft key is pressed; in this case it is the Exit and Open softkeys. private void MenuItemExit_Click(object sender, EventArgs e) { this.Close();

14
} private void MenuItemOpen_Click(object sender, EventArgs e) { string s = String.Format("You entered {0}", edtUrl.Text); MessageBox.Show(s, "Url to open", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1); } The code above is for the two command handlers that were added by clicking on the button and then choosing the Events tab in the Properties panel on the right and adding the ‘Click’ handler.

Genesis
Once you’ve written the application, the final step is to convert the Windows Mobile Standard (Smartphone) application to a S60 application. You also need to generate a Symbian SIS file (see the ‘Security and S60’ section for more information about signing your application). This is done using the Genesis project type, which is installed as part of Net60. 1. You will need to add a new project to the solution to create the SIS file, as shown in Figure 5. This project will be the Genesis project type under the Other Project Types node in the New Projects section. You should add this to the existing solution, rather than creating a new solution, so that it may pick up the build time dependencies and ensure that the resultant file to be deployed is up-to-date. 2. When you add a Genesis project, a wizard is launched that will help you to complete the configuration properties.

Figure 5: Creating a Genesis project

3. Once you’ve created the new project, you must remember to set up the dependencies by right clicking over the Genesis project node and choosing Add Dependency File to add the license file for Net60.

15
4. Right click over the Genesis project node, choose Add Project output and then select Primary output from the displayed list of projects and options. The .NET binary output (.exe) will be added as a result. 5. At this point, you can also add a dependency to the Net60 runtime (Net60.sisx) to the installation components. This will cause the Net60 platform to be embedded in the SIS file and installed to the device along with the S60 application you’ve created. 6. After you’ve set up the dependencies, right click over the Genesis project node and select Properties. This will display the options for configuring the generation of the SIS file, which is shown in Figure 6.

Figure 6: Genesis project settings

Generally speaking, the settings in the Project section should not be changed from their defaults and so these have been rolled up in Figure 6. Note: The Application UID3 (as seen in Figure 6) should be in the range 0xExxxxxxx, as this is a development UID. If you intend to distribute the application so that it runs on any device then you should obtain a unique UID from the Symbian Signed portal. Whether you need this UID, and whether you should submit the application for Symbian Signed validation, depends on which capabilities are being used and for whom the application is intended. A fuller explanation can be obtained from A Guide to Symbian Signed (available at www.symbiansigned.com) in the ‘UIDs for Symbian Development’ section. The application icon, which appears in the applications menu, is defined in the Scalable Vector Graphic (SVG) file. This format provides superior resolution-independent images and the format must be TinySVG 1.1, 1.1+ or 1.2. Free open source tools such as Inkscape (www.inkscape.org) or commercially available tools such as Adobe Photoshop (www.adobe.com) can be used to create and edit icons.4 7. You must enter the name, version number and company name because these will appear in the installation log and installed applications list. These cannot be changed after the application is installed or upgraded, with the exception of the version number.
4 However, you should be aware there are some known issues with SVG images on S60. You can find

further information at wiki.forum.nokia.com/index.php/KIS000398__SVG_rendering_problems_caused_by_missing_viewBox_attribute and wiki.forum.nokia.com/index.php/KIS000531_-_Compatibility_problem_with_binary-encoded_SVG_images. We’ll put this link on the wiki page for this booklet at developer.symbian.com/nets60_wikipage.

16
The second tab is used to specify the certificate to be used to sign the SIS file. Providing the application is only using capabilities from the user set (ReadUserData, WriteUserData, NetworkServices, UserEnvironment and LocalServices), you can use a self-signed certificate, which you can create on your machine. See wiki.forum.nokia.com/index.php/Creating_and_using_self-signed_certificate for more information on how to generate a self-signed certificate. In addition to the capability issues which depend on which APIs are being used by the application, you should take care not to alter the following items once an application is deployed: • executable filenames • UID3 • application name • company name. Changing these will make it impossible to update the application after it is deployed, and your users will need to fully uninstall the application and then reinstall the new version before they update it. Symbian OS requires that each filename is unique on a device. This means that a filename cannot be the same in two different installations, otherwise the installer will fail and indicate an update error. Including an executable DLL in multiple SIS files to provide common functionality is also not allowed; the DLL must be moved to its own SIS file. Once the Genesis project has been built, it generates a SISX file that may then be copied to the device, installed and run. The SISX file is normally installed on the device using the Nokia PC Suite (europe.nokia.com/pcsuite), which is a free Nokia product that allows you to connect your Nokia device to a PC. Alternatively, the SISX file can be pushed via Bluetooth to the device inbox and installed directly onto the device. Note: the installation of self-signed applications onto Nokia Eseries devices is disabled by default, and users are required to enable self-signed installation in the software installer before continuing. More information on this can be obtained from the following wiki posting on the Forum Nokia site: wiki.forum.nokia.com/index.php/KIS000451_-_Installing_selfsigned_SIS_files_to_Nokia_Eseries_devices_not_allowed_by_default.

Extending the application to access the network
Once you’ve deployed and installed the example to an S60 device, you can run it by navigating to its icon in the Applications folder (sometimes referred to as Installations) and opening it. Figure 7 shows the application running on a Nokia N82 device.

Figure 7: The example application running on a Nokia N82

17
With the basic UI application now complete, you can then add an engine to the UI to enable the application to access the Internet. To do this, it is a simple matter of creating a new C# class for the HTTP engine and then letting the HTTP engine provide a callback to the registered observer when the data has been downloaded or an error has occurred. This example concentrates on making the network connection to access the network and then to return data back to the caller asynchronously. This model is very similar to the Symbian OS active object model (which is well documented in the Symbian Developer Library at developer.symbian.com/main/documentation/sdl and on the Symbian Developer Network at developer.symbian.com) as it also allows you to do asynchronous processing or to cancel the request whilst waiting for the data to download. (More information about how to make the user interface responsive can be found on the MSDN web site at msdn.microsoft.com/enus/library/aa446572.aspx). We will now extend the example in the previous section so that the application can access the Internet. In this case, the engine will download the data at the specified URL and put the text into a text box to display to the user.

Figure 8: Form designer with added controls

As can be seen from Figure 8, we have added a new text box control to the form called edtResult that will hold the response from the URL. There is also a check box to indicate whether the content body will be displayed in addition to the response itself. The engine needs to be able to access the network and hide the HTTP protocol implementation. The engine class then needs to have a bridge (or observer) to the UI to report progress and return the results of the operation. It is common to use namespaces in C# to group together sets of functionality. For the HTTP

18
engine, all the classes dealing with HTTP are grouped into the HTTPEngine namespace. The namespace will consist of the enumerations for the state machine, the state observer and the engine itself. 1. From the Project menu, select Add Class and create a new interface called IHttpEngineObserver. This class will form the bridge between the UI and the HTTP engine. The asynchronous states will also be put into this namespace. namespace HTTPEngine { public enum HTTPEngineStates { Start, Response, Content, Complete, Error }; /// <summary> /// Observer interface that reports changes to the caller /// </summary> public interface IHttpEngineObserver { void Update(HTTPEngineStates State, string HTTPData); } } 2. To be able to pass state asynchronously with the BeginGetResponse() method, create a helper class called RequestState that holds the request and observer instances so that when the asynchronous call completes later these are still available. class RequestState { // This class stores the State of the request. public RequestState(HttpWebRequest Request, IHttpEngineObserver Observer) { _request = Request; _observer = Observer; } public HttpWebRequest Request { get { return _request; } } public IHttpEngineObserver Observer {

19
get { return _observer; } } private HttpWebRequest _request; private IHttpEngineObserver _observer; } There are only two functions you’ll need in order to fully understand the way the HTTP engine works. The first, Start(), is called from the UI when the user clicks a button. This method starts the asynchronous HTTP request and returns control back to the UI. public void Start(string Url, IHttpEngineObserver Observer) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); // Create an instance of the RequestState and assign the // request and callback to it so its available when the // http request completes RequestState state = new RequestState(request, Observer); AsyncCallback callback = new AsyncCallback(RespCallback); // Start the asynchronous request. request.BeginGetResponse(callback, state); // Tell the observer that we have started Observer.Update(HTTPEngineStates.Start, String.Empty); } Note that the HttpWebRequest() is started asynchronously using BeginGetResponse(), and when the response is received this will call the second function in the class: RespCallback(). RespCallback() will also retrieve the state held in the state variable so that there is sufficient information to be able to report changes and parse the response data. private static void RespCallback(IAsyncResult asynchronousResult) { RequestState state = (RequestState)asynchronousResult.AsyncState; try { // State of request is asynchronous. HttpWebResponse response = (HttpWebResponse)state.Request. EndGetResponse(asynchronousResult); // print the method get/post/headers string method = String.Format("Method: {0}\r\n", response.Method);

20
state.Observer.Update(HTTPEngineStates.Response, method); string server = String.Format("Server: {0}\r\n", response.Server); state.Observer.Update(HTTPEngineStates.Response, server); string version = String.Format("Version: {0}.{1}\r\n", response.ProtocolVersion.Major, response.ProtocolVersion.Minor); state.Observer.Update(HTTPEngineStates.Response, version); string content = String.Format("Content: {0}\r\n", response.ContentType); state.Observer.Update(HTTPEngineStates.Response, content); string encoding = String.Format("Encoding: {0}\r\n", response.ContentEncoding); state.Observer.Update(HTTPEngineStates.Response, encoding); string length = String.Format("Length: {0}\r\n", response.ContentLength); state.Observer.Update(HTTPEngineStates.Response, length); string status = String.Format("Status: {0}\r\n", response.StatusDescription); state.Observer.Update(HTTPEngineStates.Response, status); // Read the response into a Stream object. StreamReader reader = new StreamReader(response.GetResponseStream()); String httpData = reader.ReadToEnd(); state.Observer.Update(HTTPEngineStates.Content, httpData); } catch (WebException e) { state.Observer.Update(HTTPEngineStates.Error, e.Message); } state.Observer.Update(HTTPEngineStates.Complete, String.Empty); } As each section of the response is processed, the data is reported back to the observer via the callback, which then ensures that it is on the correct thread to be able to update the edit control with the text. As the form implements the observer methods that are defined in the interface, these are called on the thread that the engine instance is running on. Note that this is not necessarily the UI thread, and the data therefore needs to be moved to the thread that the UI was created on. To do this, a special type of delegate is used, called an EventHandler.

21
public void Update(HTTPEngineStates State, string HTTPData) { // Store the state into variables state = State; strData = HTTPData; // Now synchronously invoke the code to force a thread switch // to the correct thread for the UI this.Invoke(new EventHandler(ForceToUIThread)); } Finally, the event handler is called via the Invoke() call and this is executed on the UI thread to ensure that the controls are synchronously updated on the correct thread. public void ForceToUIThread(object sender, EventArgs e) { // Set the text and finally hide the cursor // as we have finished downloading the data switch (state) { case HTTPEngineStates.Start: Cursor.Current = Cursors.WaitCursor; edtResult.Text = String.Empty; break; case HTTPEngineStates.Response: edtResult.Text = String.Concat(edtResult.Text, strData); break; case HTTPEngineStates.Content: if (chkResponseAndContent.Checked) edtResult.Text = String.Concat(edtResult.Text, strData); break; case HTTPEngineStates.Error: edtResult.Text = String.Concat(edtResult.Text, strData); break; case HTTPEngineStates.Complete: Cursor.Current = Cursors.Default; break; } } 3. You should now run this code to ensure that it functions correctly on the Windows Mobile device with no errors. 4. The next stage is to use Genesis to convert the project to an S60 application. The steps to do this are the same as in the previous example, except that the following must be considered: • If the UI and the HTTP examples are going to be installed side by side on the same device then a different UID3 will need to be used. • The HTTP application communicates with the network and so the NetworkServices capability needs to be set in the capabilities section to comply with Symbian OS platform security requirements. You may need to update the certificate so that it includes this capability if it doesn’t have it yet. 5. The application may now be deployed to the S60 device and tested. Figure 9 shows the application running on a Nokia N82 device.

22

Figure 9: Net60 Network access extensions

Extending the application to send an SMS
One of the major strengths of the .NET runtime is that access to the operating system can be obtained using the Platform Invoke (P/Invoke) API. P/Invoke specifies an API and protocols for talking to the underlying operating system using native code. It is important to remember that any DLLs and APIs must also comply with the platform security requirements, and so all third-party DLLs need to have at least the capabilities of the hosting process. You should check any APIs that are used to make sure that the process and certificate have at least the same capabilities. There is a different API for sending an SMS message on each operating system, but in this example a native S60 DLL will be created and then the .NET runtime will call the DLL via the P/Invoke mechanism. The native C++ code resides in a DLL that was created using Carbide.c++. This exports one function called SendMessageWrapper::SendSMSMessage() that uses the Symbian OS RSendAs APIs to send a message. The following code is Symbian C++ and it uses the RSendAs API to send the message in a standard manner. This code assumes the existence of an active scheduler and TRAP harness on the current thread so that IPC calls can be made and leaving functions can be used.

23
EXPORT_C TInt SendSMSMessage(const TUint16* aTo, const TInt aToLen, const TUint16* aMsg, const TInt aMsgLen) { const TPtrC16 to(aTo, aToLen); const TPtrC16 message(aMsg, aMsgLen); TRAPD(err, SendSMSMessageL(to, message)); return err; } void SendSMSMessageL(const TDesC& aTo, const TDesC& aMessage) { RSendAs session; User::LeaveIfError(session.Connect()); CleanupClosePushL(session); RSendAsMessage message; message.CreateL(session, KSenduiMtmSmsUid); CleanupClosePushL(message); message.SetBodyTextL(aMessage); message.AddRecipientL(aTo, RSendAsMessage::ESendAsRecipientTo); message.SendMessageAndCloseL(); CleanupStack::PopAndDestroy(2, &session); } This is all it takes to send an SMS message on S60 using native C++ code. Performing the same task using C# is slightly complicated by the fact that Net60 does not currently support native marshalling of string objects between processes. As a result, all strings need to be converted to arrays of Unicode characters and then these strings must be sent over the P/Invoke boundary. Fortunately, the CLR handles memory via a garbage collector, so it’s easy just to allocate an array of characters and then call the unmanaged code. When the unmanaged code returns, the character arrays will be cleaned up by the garbage collector at some point. On the client side, the code is even simpler. All that is required is a declaration to the function with sufficient information for the CLR to be able to convert the parameter to a P/Invoke call and to identify the DLL and ordinal export number that will be used to call the function. [DllImport("SendMessageWrapper.dll", EntryPoint = "#1")] private static extern ErrorCode SendSMSMessage(char[] phonenumber, int phonenumberlength, char[] message, int messageLength); public static void SendSMS(String PhoneNumber, String Message) { char[] phonenumber = PhoneNumber.ToCharArray(); char[] message = Message.ToCharArray(); ErrorCode result = SendSMSMessage(phonenumber, phonenumber.Length, message, message.Length); if (result != ErrorCode.KErrNone) throw new SymbianException("SendSMSMessage Failed", result); }

24
When the SendSMS()function is called, this calls SendSMSMessage(). In turn, this dynamically loads the SendMessageWrapper DLL and calls the function at index 1 with two Unicode string parameters and their lengths. It may seem strange that the function is referenced by its ordinal number, rather than by its name, but the Symbian OS loader currently only binds the functions in a DLL by exported ordinal number when the executable is launched or the DLL is loaded dynamically. The names of the functions are not present in the DLL shipped on the device. You should bear the following platform security and signing requirements in mind as you extend your application: • The SendMessageWrapper DLL must have at least the same capabilities as the hosting process. When creating the hosting process in Genesis, the capabilities section needs to specify the same capabilities as the DLL (or fewer) in order for the DLL to be loaded into the .NET application’s process. • If your Net60 application needs additional APIs that require more capabilities, then you will need to rebuild the DLL so that it reflects these new capabilities. • You should check the devcert shows the same set of capabilities as those specified in the Genesis project, otherwise you must obtain a new certificate. • You should check carefully which signing option is best for you: self-signing, Open Signed, Express Signed or Certified Signed (see www.symbiansigned.com for more details). There are further notes about submitting the SIS file generated by Genesis to the Open Signed online portal in the CHM help file supplied with Net60 (usually found in \Program Files\Red Five Labs\Net60\Documentation or your chosen installation directory). The DLL must be installed as a separate SIS file because Genesis cannot support installation of third-party native code as part of its build process. The SIS file must be signed with at least the capabilities that the DLL requires in order for the installer to accept it. This means that the .NET application’s SIS file must be signed using a certificate with at least those capabilities. Net60 is signed with the following capabilities: • ReadDeviceData • NetworkServices • LocalServices • ReadUserData • WriteUserData • Location • UserEnvironment. The effect of this is that access to third-party code that requires capabilities outside of the Net60 set (for example, AllFiles or DRM) is not allowed.

25

Examples and source code
This completes the examples showing how to build a simple GUI application, and how to extend it so that it accesses the Internet to download some data and interfaces with the native operating system. The source code for the examples may be obtained the Red Five Labs web site. We have placed a link to the exact location on the wiki page for this booklet, at developer.symbian.com/nets60_wikipage.

The RedFiveLabs.Mobile assembly and namespace
Red Five Labs provide a specific assembly targeting S60 APIs that will make it easier to access underlying S60 and Symbian OS services using .NET classes, including: • location • audio • Bluetooth wireless technology • OpenGL • telephony. If you use these classes, you get a common S60 infrastructure and you won’t need to create managed code wrapper classes for specific APIs. You can also avoid using Symbian C++ programming idioms, such as active objects and descriptors, which are devolved to the Red Five Labs assembly.

Additional tools and utilities
While Microsoft Visual Studio is an impressive piece of technology in its own right, there are additional tools free from Microsoft and third parties to make developing in C# much easier. You may have used them already if you’re a .NET developer. Most of these tools have command line equivalents that can be integrated easily and quickly into any build toolchain to improve code quality and reliability.

FXCop
This tool takes a project and analyses the C# code to identify errors and misuse of APIs or coding standards. FXCop can be integrated into the project workflow so that it can be run during an automated build and the results fed into a defect workflow for triage and fixing. This therefore makes for a more robust project. FXCop identifies rules from the following sets: • Design and naming issues such as design flaws, variable and method casing, variable and method names, and cross language keyword usage, to mention just some of the issues. • Localization and globalization issues. • Performance issues in code. • API usage issues that attackers could exploit. FXCop can be downloaded from msdn.microsoft.com/en-us/library/bb429476(VS.80).aspx.

StyleCop
This is a Microsoft internal tool that takes code and ensures that conventions, naming and style match those suggested as best practice for C#. It also provides a corporate standard for code in C#. More information on StyleCop can be found at the StyleCop blog (blogs.msdn.com/sourceanalysis). It may be also be downloaded from code.msdn.microsoft.com/sourceanalysis/Release/ProjectReleases.aspx?ReleaseId=1047.

26 NDoc
This tool is similar in many ways to Doxygen, the standard documentation generator for the S60 and Symbian OS documentation. However, NDoc generates documentation that is suitable for integration into MSDN help and it interfaces with the auto help commands in Microsoft Visual Studio to assign help comments to a function. NDoc can be downloaded from ndoc.sourceforge.net.

NUnit
This tool completes the suite of tools and provides unit tests to each module. NUnit uses the attributes framework of the CLI so that unit tests can be incorporated into the module source code. This promotes a high degree of cohesion and very little coupling, making for improved code reuse as well as significant improvements in the quality of the code. NUnit can be downloaded from www.nunit.org/index.php.

Recommended S60 tools
Extended panic logging is disabled on S60 devices by default. This means that any application errors will not be displayed to the user and the application will simply exit. You can find more about enabling extended panic codes at wiki.forum.nokia.com/index.php/Extended_panic_code. Another useful tool is a file browser that can browse files outside the data folder. Y-Browser and Y-Tasks, together with their various plug-ins, help to isolate problems and errors on the device as well as giving access to files. Y-Browser and its plug-ins can be downloaded from www.drjukka.com/YBrowser.html and www.drjukka.com/YTasks.html. The final tool in the arsenal of device-side debugging tools is the Log Viewer for Net60. This is available with the debug version of the Net60 runtime. This application provides a post mortem view of significant events and profiling information during the running of an application. For more information on the Log Viewer and configuring logging, consult the Net60.chm help file and associated readme file, which can be found in \Program Files\Red Five Labs\Net60\Documentation. Finally, with the profusion of developer certificates that are generated during a project, it can be a chore to know which certificate has which capabilities and which certificate is associated with which IMEI. The ‘DevcertList’ application extracts this information from the devcert and displays this as a usable list. You can download this application from wiki.forum.nokia.com/index.php/Listing_IMEIs_and_Capabilities_in_a_DevCert.

A success story
What really counts is whether a new technology will help customers to capture returns on their investment. Below is a testimonial from TravelGuides ToGo (www.co-ordinategps.com) about their experiences with Net60:

‘TravelGuides ToGo, our travel guide application for location-aware mobile devices, was initially developed using the .NET Compact Framework. We wanted to expand our range of compatible devices beyond Windows Mobile, and since the S60 platform was the logical next step, Net60 was the logical choice for leveraging our .NET development effort. The phrase “sounds too good to be true” crossed our minds, but the excellent support we have received from Red Five Labs, and the ease of getting our application up and running at a cost effective price, has made Net60 an integral part of our development team.’

27

Summary
Net60 provides you with new opportunities to find the right balance between access to low level S60 platform features and development complexity. The C# language is similar to C++, which makes it easy to get up to speed quickly if you know C++ already. In addition, the large collection of standardized classes in the framework library makes code reuse a reality. And finally, many of the time consuming development issues plaguing native C++, such as resource leaks and memory corruption, can largely be eliminated with C#. The binary compatible version of the .NET Compact Framework provided by Red Five Labs makes porting the major components of Windows Mobile smartphone applications to S60 easy. Often, only minor changes are required to get the same application running on an S60 device, although there are some limitations to Net60 at the time of writing, such as its partial support for .NET CF 2.0.5 As the S60 platform continues to evolve, offering users the leading smartphone devices and developers the cutting edge tools to deliver applications to those devices, Red Five Labs will be part of this, offering you the tools and languages to create successful mobile application businesses.

Recommended reading
For those unfamiliar with Symbian OS and S60: • Aubert, Michael (2008) Quick Recipes on Symbian OS, John Wiley & Sons, Ltd, Chichester (ISBN-10: 0470997834) • Harrison, Richard and Shackman, Mark (2007) Symbian OS C++ for Mobile Phones, Volume 3, John Wiley & Sons, Ltd, Chichester (ISBN: 0470066415) • Coulton, Paul and Edwards, Reuben (2007) S60 Programming – A Tutorial Guide, John Wiley & Sons, Ltd, Chichester (ISBN-13: 9780470027653) For those unfamiliar with .NET or C#: • Yao, Paul and Durant, David (2004) .NET Compact Framework Programming with C#, Addison Wesley, Rugby (ISBN-10: 0321174038) • Troelsen, Andrew (2004) Pro C# 2005 and the .NET 2.0 Platform, Third Edition, Apress, Berkeley (ISBN-10: 1590590554) • Richter, Jeffrey (2006) CLR via C#, Second Edition (Pro Developer), Microsoft Press (ISBN10: 0735621632)

5 Other minor limitations are discussed in the Net60 FAQ found at

www.redfivelabs.com/content/faq.aspx.

28

Developer resources
Symbian Developer Network developer.symbian.com Symbian Developer Network Newsletter developer.symbian.com/register

Community web sites
Forum Nokia forum.nokia.com MOTODEV developer.motorola.com Samsung Mobile Innovator innovator.samsungmobile.com

New from

Common Design Patterns for Symbian OS: The Foundations of Smartphone Software
Common Design Patterns for Symbian OS introduces the common design patterns used to implement a variety of applications and services on Symbian OS. The book describes patterns based on the architectural elements of Symbian OS and discusses how patterns suited for desktop software must be adapted or even avoided on a mobile platform.

Multimedia on Symbian OS: Inside the Convergence Device
Combining the insights and experience of subject experts within Symbian and the third-party developer community, this book will be an invaluable reference for anyone working with multimedia on Symbian OS. The authors provide details of the native C++ APIs for accessing camera, video, audio, image manipulation and radio tuner functionality, and discuss best practice, tips and tricks.

Symbian Press: developer.symbian.com/books

New from

Quick Recipes on Symbian OS
This book aims to make it easier to develop applications by describing a number of common programming tasks and providing clear explanations of how to complete them. The recipes are divided by technology, including graphics, multimedia, location-based services, networking, telephony, connectivity and messaging. Full sample code is available for download, so it can be used as a starting point in your own projects.

Games on Symbian OS: A Handbook for Mobile Development
This book forms part of the Technology Series from Symbian Press. It describes the key aspects of the mobile games marketplace, with particular emphasis on creating games for smartphones based on Symbian OS v9.x. It also looks at C/C++ Standards support available for developers porting games to Symbian OS, how to write for the N-Gage platform, and coding for runtimes such as Java ME and Flash Lite.

Symbian Press: developer.symbian.com/books

from

Developing Software for Symbian OS, Second Edition
This second edition of Developing Software for Symbian OS helps software developers new to Symbian OS to create smartphone applications. The original book has been updated for Symbian OS v9 and now includes a new chapter on application signing and platform security, and updates throughout for Symbian OS v9 and changes to the development environment.

Symbian OS C++ for Mobile Phones, Volume 3
The latest edition of Richard Harrison’s existing bestsellers draws on the experience of Symbian’s own engineers to help you become an effective Symbian OS developer. If you’ve programmed in C++ at any level and wish to develop software for Symbian smartphones, this book gives you a thorough grounding in writing C++ applications for Symbian OS v9.

from

For all Symbian C++ developers:
Symbian OS Communications Programming, 2nd Edition by Iain Campbell S60 Programming - A Tutorial Guide by Coulton & Edwards Symbian OS Explained by Jo Stichbury Symbian OS Internals by Jane Sales Symbian OS Platform Security by Craig Heath Smartphone Operating System Concepts with Symbian OS by Mike Jipping
Accredited Symbian Developer Primer by Jo Stichbury & Mark Jacobs

from

Published Booklets
A Guide to P.I.P.S. Carbide.c++ v1.3 Coding Standards Coding Tips Coverity Prevent on Symbian OS Creating Location-Aware Applications Data Sharing Tips Essential S60 - Developers’ Guide Essential UIQ - Getting Started Getting Started Getting to Market Java ME on Symbian OS Localization Performance Tips Platform Security for all Quick Recipes Taster

Translated Booklets
Chinese Japanese Korean Spanish Russian Persian Italian

Notes:

Notes:

Using Symbian OS

.NETDevelopmentons60
Why? What? Where? How?

If you like to use C# and .NET for development, and want to get into mobile development then this booklet is for you! We explain how to use the .NET runtime on S60 devices using Net60 from Red Five Labs. The booklet shows how to get started, and how to extend a basic application to access underlying operating system APIs. Information about where to find recommended tools, example code and further reference material is also included. .NET Development on S60 is part of the Using Symbian OS series, designed to provide information in a handy format to S60 developers.

Symbian Press Symbian Press publishes books designed to communicate authoritative, timely, relevant and practical information about Symbian OS and related technologies. Information about the Symbian Press series can be found at developer.symbian.com/books

Sign up to vote on this title
UsefulNot useful