36
Using Symbian OS .NET Development oN S60

NET Development on S60

  • Upload
    symbian

  • View
    2.491

  • Download
    3

Embed Size (px)

DESCRIPTION

Booklet explaining how to get started developing with the NET runtime environment on the S60 platform and Symbian platform.

Citation preview

Page 1: NET Development on S60

Using Symbian OS

.NETDevelopmentoNS60

Page 2: NET Development on S60
Page 3: NET Development on S60

Reviewed by:Julian AshworthDavid CaabeiroAntony EdwardsAlexey GusevAdriano IorioCharlotte MasonThibaut RouffineauJo StichburyAlex Wilbur

3

.NET Development on S60part of the Using Symbian OS series

1st edition, 10/08

Published by:Symbian Software Limited2-6 Boundary RowSouthwarkLondon SE1 8HPUKwww.symbian.com

Trademarks, copyright, disclaimer‘Symbian’, ‘Symbian OS’ and other associated Symbian marks are all trademarks of SymbianSoftware Ltd. Symbian acknowledges the trademark rights of all third parties referred to in thismaterial. Copyright © Symbian Software Ltd 2008. All rights reserved. No part of this materialmay be reproduced without the express written permission of Symbian Software Ltd. SymbianSoftware Ltd makes no warranty or guarantee about the suitability or the accuracy of theinformation contained in this document. The information contained in this document is forgeneral information purposes only and should not be used or relied upon for any otherpurpose whatsoever.

Compiled by:Paul Todd

Managing Editor:Ashlee Godwin

Page 4: NET Development on S60

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

4

Page 5: NET Development on S60

S60 and Symbian OSSymbian OS is a modular operating system, constructed from well-defined, discretecomponents that combine to allow for configurability across a range of target hardware. At ahigh level, Symbian OS can be thought of as a layered model with a flexible architecture thatallows different UI layers to run as platforms on top of the core operating system. The genericUI framework of Symbian OS supplies a common behavior and supports extension by UIvendors, who define their own look-and-feel.

The S60 platform, supplied by Nokia, sits on top of Symbian OS. S60 is the world's mostpopular smartphone platform with 150 million units shipped, 80 models and four licensees(Nokia, Samsung, Lenovo and LG). S60 devices have become increasingly sophisticated, withhigh-resolution still and video cameras, location-based services, full web browsing, stereomusic, mapping and Voice over IP (VoIP), to name just a few of the features now available. Therange of S60 devices offered by licensees has also evolved, offering distinct collections ofdevice models for consumers, enterprises and other specific market niches. For moreinformation about S60, visit www.s60.com.

The .NET platform on S60Applications on S60 are most frequently created using native C++ or Java ME, depending onthe features required, but additional runtime support is available, including Python and FlashLite (more information about the runtimes support can be found atdeveloper.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, whichprovides an engine for running intermediate language code on S60 devices. Net60 is providedby 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 upto speed in building applications for S60 in C# and compiling them to the .NET framework. Wewill concentrate on the Windows Mobile Standard (Smartphone) edition as this is the Net60target platform.

You’ll notice some long URLs referenced in this booklet. Don’t worry – you don’t have to try totype them in! We’ve put each URL used in this booklet on its wiki page, atdeveloper.symbian.com/nets60_wikipage, so that you can navigate to the web sites.

5

Page 6: NET Development on S60

The .NET runtime and C#

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

Using the .NET runtime: The basicsTo use the .NET runtime, you’ll need to know about the Common Language Runtime and theFoundation Class Library.

The Common Language Runtime (CLR) is the virtual machine component of the .NETFramework that provides an execution environment and common type system for all .NETapplications. It is an implementation of an open standard called the Common LanguageInfrastructure (CLI), which specifies the byte code and the environment used as the .NETcommon runtime.1

The CLR executes programs that have been compiled into a platform-neutral language (a formof byte code) called Common Intermediate Language (CIL). Compilers that emit CIL areavailable for C#, Visual Basic .NET and many other popular programming languages includingPython and Ruby (but this booklet will discuss only C#). The CLR usually translates CIL intonative 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 managementand exception handling, but its major function is to interpret byte code. The collection ofclasses that are compiled as IL in a DLL or executable is called an ‘assembly.’ An applicationbuilt in Visual Studio is compiled into IL and is then packaged into an assembly which can bean executable or a DLL.

In addition to the CLR, there is a large set of pre-built, tested functionality provided inassemblies 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 alsosometimes be referred to as the Base Class Library (BCL).2

The FCL is a collection of thousands of reusable classes, interfaces and other types thatprovide 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 theFCL on a mobile device. Therefore, Microsoft provides a scaled-down version of the .NETFramework called the .NET Compact Framework (.NET CF) that has a CLR and class librariesspecifically designed for Windows Mobile. A comparison of desktop and CF features can befound at msdn.microsoft.com/en-us/library/aa446549.aspx.

6

1 This specification now falls under open specifications ECMA-335 and ISO/IEC 23271. The mostnotable implementation of this standard outside of that from Microsoft is the Mono Project whichprovides a CLR for Linux-based operating systems.

2 Technically speaking, the FCL comprises of Microsoft-specific extensions to the ECMA-approved BCL.

Page 7: NET Development on S60

Figure 1: .NET build process components (Source: Wikimedia commons library aten.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 CLIThere are some key concepts to understand about the CLI.

• The code that is run inside of the CLR interpreter is called ‘managed code.’ The CLRinterpreter provides restricted access to native pointers and memory, meaning that typicalapplication errors such as memory leaks and memory corruption will be significantlyreduced.

• Since managed code also manages memory and handles via the garbage collector, it isessential that you are familiar with how this works in order to understand when handlesare freed.

• Because of the strong type-checking, the compiler makes it extremely difficult to abusetype safety, which is moved into the realm of the CLR interpreter.

Code that consists of compiled processor-specific instructions that are not portable betweenoperating systems is called native code. A good example is the code that makes up system DLLs andprovides access to system memory. Access to native code is strictly controlled by the CLR and needsto be performed within the confines of the CLI. Normally, managed code applications will accessnative code using a DLL. This is done using a specific API inside the CLR that hides the complexityby moving pointers from managed to unmanaged code in a safe and secure way.

7

.NET compatible languagescompile to a second platform-neutral language, called CommonIntermediate Language (CIL).

Page 8: NET Development on S60

Many of the issues that plague native code development, such as memory corruption, invalidpointers, resource leaks and type mismanagement, are handled by a combination of the CLRruntime and CLI compiler.

For example, Symbian C++ developers need to use the cleanup stack and be very careful withmemory and resource management. In contrast, when using the .NET runtime and the CLI, thisis all moved to the CLR. You don’t need to worry about when an object will be deleted or whatresources it owns because the CLR figures out when an object can be freed during a garbagecollection cycle. Note that garbage collection is not ideally suited for resource-constraineddevices, so there is also support within the runtime to allow you to control the destruction ofobjects. This is accomplished by implementing the IDisposable interface in a class, whichtells the CLR that objects using this interface must be released immediately.

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

Figure 2: .NET Compact Framework on Symbian OS

8

Page 9: NET Development on S60

At the time of writing, S60 applications are all keypad driven, and closely resemble thosewritten for Microsoft smartphone devices. The form factor and functionality for S60 andMicrosoft smartphones are very similar, making it much easier to port applications from oneplatform to the other. (Pocket PC applications are typically designed for touchscreen andkeyboard-based devices).

You should also note that, at the time of writing, Net60 only supports .NET CF 1.0, so youshould be aware of the differences between this version and .NET CF 2.0. However, partial .NETCF 2.0 application support will be introduced in October 2008. Please seewww.redfivelabs.com for updates about CF 2.0 support.

Net60: Under the hoodWhen installed on an S60 device, the Net60 CLR is installed into the \sys\bin folder. Theframework class libraries are stored into the Global Assembly Cache (GAC) in the \resourcesfolder.

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 thatregisters 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 themanaged application and all the required assemblies (the managed application is started inmuch the same way as on a Windows Mobile device).

The application frameworkThe application object’s Run() method is called and passed within the Main() function in anew form instance, which can hold controls.

The controls for a C# form are created in code dynamically within theInitializeComponent() method (unlike traditional Windows and S60 applications, wherea form is created from resources within a sophisticated application framework). This methodcreates and initializes each control, placing it on the form and filling it with the correct andrelevant data. Fortunately, the Visual Studio IDE designer tool does this for you by allowing thecontrols 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 controluntil Close() or Application.Exit() is called, at which point the form is closed and theapplication terminates. Take care when creating multiple forms, or forms with a large numbersof controls, as these can consume significant amounts of resources. You should assesscarefully the trade-off between creating a form as needed and showing or hiding a form whendesigning an application. You should also be aware that some of the controls have minor

9

Page 10: NET Development on S60

limitations when ported over to S60, such as not being skin aware. These limitations arediscussed 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 WindowsMobile and S60 because user interface responsiveness is critical. For example, if a thread isspawned to download some data from a remote site, any results from the thread object mustbe copied from the thread to the object; then, when the UI thread next executes, the data canbe 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 thisbooklet alone. However, if you don’t already know C#, we recommended that you purchase asimple book on the language as it is used on Windows, since there are no differences insyntax between using C# with the Windows .NET framework and using Net60 on S60. There isa recommended reading list section at the end of this booklet.

Comparing Windows Mobile and S60This booklet doesn’t discuss the fundamental differences between application development forMicrosoft 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 youneed information about how to manage the differences, we recommend a paper on theSymbian Developer Network site that provides intermediate and advanced Windows CE andWindows Mobile developers with an introduction to porting applications from Windows Mobileto Symbian OS v9. The paper is available for download fromdeveloper.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 withNet60.

Security and S60 Neither the .NET CF nor Net60 use the .NET policy-based security model. Instead, the CLR relieson the underlying operating system to provide security. Symbian OS and S60 have a very strictsecurity model called ‘platform security,’ which is fundamentally different to that of WindowsMobile. More information about platform security can be found in the Symbian Press booklet,Platform security for all, available for download fromdeveloper.symbian.com/main/documentation/booklets/booklets_using.jsp.

In Windows Mobile Standard (Smartphone), each executable code file (EXE or DLL) is signedwith 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 fromMicrosoft. In general, these operations are very operator-centric and most developers will notneed them. Windows Mobile also allows for executable files to be non-unique and to beplaced anywhere on the device. The Windows loader searches the path in order to find theappropriate DLL or executable to be loaded or run respectively. This process is markedlydifferent 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 isused by the executable loader to prevent applications and DLLs from misusing APIs bycontrolling which APIs an application, and the DLLs that it loads, can access. In order to accessa particular API group an application needs to have the right capability assigned to it.

10

Page 11: NET Development on S60

Furthermore, a request to dynamically load a DLL will fail unless it has at least the samecapabilities as the parent process; that is, if the DLL has a different set of capabilities to theparent process, or is missing a capability, then the DLL will not be loaded. This applies to bothstatically and dynamically linked DLLs.

Capabilities are defined at compile time and checked during install time. The capabilitiesassigned to an executable cannot be changed after it has been installed. There is furtherinformation 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 deemedtrusted by the system: the software installer, the file server and the kernel. In practice, thismeans that a binary must be placed in the \sys\bin folder by the software installer in orderfor code to run.

During development, if you use certain APIs from the protected set (which is similar to theprivileged 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 associatedwith the IMEI of your device. When you are ready to release your application to a wideraudience, 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 softwareinstaller acts as the gatekeeper, and inspects software installation packages known as SISfiles. It is responsible for ensuring that the capabilities required by the executable code in thepackage match those allowed by the certificate it was signed with.

Further information about developer certificates and Symbian Signed can be found atwww.symbiansigned.com, from where you can also download the introductory manual, A Guideto Symbian Signed.

Fortunately, if you’re working on Net60, you should only ever need to use standard APIs. Thismeans that devcerts or using Open Signed online is not generally necessary, and self-generated certificates are sufficient for self-signing, even for applications such as the SMSexample provided later in this booklet.

Getting startedNet60 has been designed to make building applications as easy as possible and to make themost 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 todevelop mobile applications and to generate Microsoft .NET CF-compliant code suitable forrunning on the device. It provides a drag and drop environment as well as a Windows MobileStandard 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 ServicePack One, because this has a number of critical bug fixes that will improve its usability. Youcan find more information on Visual Studio 2005 on the MSDN site at msdn.microsoft.com/en-us/vs2005/aa718668.aspx.

11

3 Note that the Express version of Visual Studio does not support the creation of mobileapplications and so is unsuitable for the development of .NET CF applications.

Page 12: NET Development on S60

For Net60 development, you should download the Net60.exe Windows installer from the RedFive Labs’ web site (www.redfivelabs.com/net60.exe) and install it to your Windows PC. Youmust install the Net60 SIS file that is included in this download on any device that you wish todeploy the .NET application on. This will ensure that the CLR is deployed to, and that theintermediate language code can be run on, the device. Details of licensing requirements andregistration 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 applicationThis tutorial creates a basic GUI application, and then extends it to communicate with thenetwork to get the HTML text from the Internet. In the final section, the application is furtherextended so that it can send SMS messages to a specified phone number to illustrate how youcan use code that interfaces with the native operating system outside of the CLR sandbox(although the same can be achieved with managed code using theRedFiveLabs.Mobile.dll namespace).

Creating a new projectIt is as simple to build a GUI application for S60 as it is to build one for Windows MobileStandard.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 WindowsMobile 5.0 Smartphone SDK and the .NET framework targeted must be selected as .NETCompact 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

12

Page 13: NET Development on S60

4. Once you’ve created the project, the next step is to take the default project and drop therequired controls onto the form.

For this example, a label and an edit control have been placed on the form to allow the entryof 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. Themenu option is found on the right softkey and the action on the left softkey. To create a userexperience in a Net60 application that is similar to a corresponding native S60 application, theWindows Mobile menus are swapped, so that the menu appears on the left softkey and theaction on the right softkey. For more information about the standard look-and-feel of S60devices, please consult the Usability documentation on the Forum Nokia web site, atwww.forum.nokia.com/usability.

For the first part of the example code, clicking the Open softkey displays a standard messagebox.

Right clicking over the form and selecting View Code will display the C# code. Expanding thevarious, 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();

13

Page 14: NET Development on S60

}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 buttonand then choosing the Events tab in the Properties panel on the right and adding the ‘Click’handler.

GenesisOnce 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). Thisis 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 nodein the New Projects section. You should add this to the existing solution, rather thancreating a new solution, so that it may pick up the build time dependencies and ensurethat 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 theconfiguration properties.

Figure 5: Creating a Genesis project

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

14

Page 15: NET Development on S60

15

4. Right click over the Genesis project node, choose Add Project output and then selectPrimary 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 fileand 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 selectProperties. This will display the options for configuring the generation of the SIS file, whichis shown in Figure 6.

Figure 6: Genesis project settings

Generally speaking, the settings in the Project section should not be changed from theirdefaults 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 adevelopment UID. If you intend to distribute the application so that it runs on any device thenyou 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 onwhich capabilities are being used and for whom the application is intended. A fullerexplanation can be obtained from A Guide to Symbian Signed (available atwww.symbiansigned.com) in the ‘UIDs for Symbian Development’ section.

The application icon, which appears in the applications menu, is defined in the Scalable VectorGraphic (SVG) file. This format provides superior resolution-independent images and the formatmust 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 tocreate and edit icons.4

7. You must enter the name, version number and company name because these will appear inthe installation log and installed applications list. These cannot be changed after theapplication 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 findfurther information at wiki.forum.nokia.com/index.php/KIS000398_-_SVG_rendering_problems_caused_by_missing_viewBox_attribute andwiki.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.

Page 16: NET Development on S60

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), youcan use a self-signed certificate, which you can create on your machine. Seewiki.forum.nokia.com/index.php/Creating_and_using_self-signed_certificate for moreinformation on how to generate a self-signed certificate.

In addition to the capability issues which depend on which APIs are being used by theapplication, you should take care not to alter the following items once an application isdeployed:

• executable filenames• UID3• application name • company name.

Changing these will make it impossible to update the application after it is deployed, and yourusers will need to fully uninstall the application and then reinstall the new version before theyupdate it. Symbian OS requires that each filename is unique on a device. This means that afilename cannot be the same in two different installations, otherwise the installer will fail andindicate an update error. Including an executable DLL in multiple SIS files to provide commonfunctionality 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 tothe device, installed and run. The SISX file is normally installed on the device using the NokiaPC Suite (europe.nokia.com/pcsuite), which is a free Nokia product that allows you to connectyour Nokia device to a PC. Alternatively, the SISX file can be pushed via Bluetooth to thedevice inbox and installed directly onto the device.

Note: the installation of self-signed applications onto Nokia Eseries devices is disabled bydefault, and users are required to enable self-signed installation in the software installerbefore continuing. More information on this can be obtained from the following wiki postingon the Forum Nokia site: wiki.forum.nokia.com/index.php/KIS000451_-_Installing_self-signed_SIS_files_to_Nokia_Eseries_devices_not_allowed_by_default.

Extending the application to access the networkOnce you’ve deployed and installed the example to an S60 device, you can run it by navigatingto 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

16

Page 17: NET Development on S60

With the basic UI application now complete, you can then add an engine to the UI to enablethe 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 theregistered 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 thento return data back to the caller asynchronously. This model is very similar to the Symbian OSactive object model (which is well documented in the Symbian Developer Library atdeveloper.symbian.com/main/documentation/sdl and on the Symbian Developer Network atdeveloper.symbian.com) as it also allows you to do asynchronous processing or to cancel therequest whilst waiting for the data to download. (More information about how to make theuser interface responsive can be found on the MSDN web site at msdn.microsoft.com/en-us/library/aa446572.aspx).

We will now extend the example in the previous section so that the application can access theInternet. In this case, the engine will download the data at the specified URL and put the textinto 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 callededtResult that will hold the response from the URL. There is also a check box to indicatewhether 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 protocolimplementation. The engine class then needs to have a bridge (or observer) to the UI to reportprogress and return the results of the operation.

It is common to use namespaces in C# to group together sets of functionality. For the HTTP

17

Page 18: NET Development on S60

engine, all the classes dealing with HTTP are grouped into the HTTPEngine namespace. Thenamespace will consist of the enumerations for the state machine, the state observer and theengine itself.

1. From the Project menu, select Add Class and create a new interface calledIHttpEngineObserver. This class will form the bridge between the UI and the HTTPengine. 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, createa helper class called RequestState that holds the request and observer instances so thatwhen 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{

18

Page 19: NET Development on S60

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 engineworks.

The first, Start(), is called from the UI when the user clicks a button. This method starts theasynchronous 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 completesRequestState state = new RequestState(request, Observer);AsyncCallback callback = new AsyncCallback(RespCallback);

// Start the asynchronous request.request.BeginGetResponse(callback, state);

// Tell the observer that we have startedObserver.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 variableso that there is sufficient information to be able to report changes and parse the responsedata.

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/headersstring method = String.Format("Method: {0}\r\n", response.Method);

Page 20: NET Development on S60

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 thecallback, which then ensures that it is on the correct thread to be able to update the editcontrol with the text. As the form implements the observer methods that are defined in theinterface, these are called on the thread that the engine instance is running on. Note that thisis not necessarily the UI thread, and the data therefore needs to be moved to the thread thatthe UI was created on. To do this, a special type of delegate is used, called anEventHandler.

20

Page 21: NET Development on S60

public void Update(HTTPEngineStates State, string HTTPData){

// Store the state into variablesstate = State;strData = HTTPData;// Now synchronously invoke the code to force a thread switch// to the correct thread for the UIthis.Invoke(new EventHandler(ForceToUIThread));

}

Finally, the event handler is called via the Invoke() call and this is executed on the UIthread 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 dataswitch (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 Mobiledevice 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 followingmust 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 platformsecurity requirements. You may need to update the certificate so that it includes thiscapability if it doesn’t have it yet.

5. The application may now be deployed to the S60 device and tested. Figure 9 shows theapplication running on a Nokia N82 device.

21

Page 22: NET Development on S60

Figure 9: Net60 Network access extensions

Extending the application to send an SMSOne of the major strengths of the .NET runtime is that access to the operating system can beobtained using the Platform Invoke (P/Invoke) API.

P/Invoke specifies an API and protocols for talking to the underlying operating system usingnative code. It is important to remember that any DLLs and APIs must also comply with theplatform security requirements, and so all third-party DLLs need to have at least thecapabilities of the hosting process. You should check any APIs that are used to make sure thatthe 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 thisexample a native S60 DLL will be created and then the .NET runtime will call the DLL via theP/Invoke mechanism.

The native C++ code resides in a DLL that was created using Carbide.c++. This exports onefunction called SendMessageWrapper::SendSMSMessage() that uses the Symbian OSRSendAs APIs to send a message.

The following code is Symbian C++ and it uses the RSendAs API to send the message in astandard manner. This code assumes the existence of an active scheduler and TRAP harness onthe current thread so that IPC calls can be made and leaving functions can be used.

22

Page 23: NET Development on S60

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 notcurrently support native marshalling of string objects between processes. As a result, all stringsneed to be converted to arrays of Unicode characters and then these strings must be sent overthe P/Invoke boundary. Fortunately, the CLR handles memory via a garbage collector, so it’s easyjust to allocate an array of characters and then call the unmanaged code. When the unmanagedcode 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 functionwith sufficient information for the CLR to be able to convert the parameter to a P/Invoke call andto 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);}

23

Page 24: NET Development on S60

When the SendSMS()function is called, this calls SendSMSMessage(). In turn, this dynamicallyloads the SendMessageWrapper DLL and calls the function at index 1 with two Unicode stringparameters and their lengths. It may seem strange that the function is referenced by its ordinalnumber, rather than by its name, but the Symbian OS loader currently only binds the functionsin a DLL by exported ordinal number when the executable is launched or the DLL is loadeddynamically. 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 extendyour application:

• The SendMessageWrapper DLL must have at least the same capabilities as the hostingprocess. When creating the hosting process in Genesis, the capabilities section needs tospecify the same capabilities as the DLL (or fewer) in order for the DLL to be loaded intothe .NET application’s process.

• If your Net60 application needs additional APIs that require more capabilities, then youwill 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 theGenesis project, otherwise you must obtain a new certificate.

• You should check carefully which signing option is best for you: self-signing, OpenSigned, Express Signed or Certified Signed (see www.symbiansigned.com for moredetails). There are further notes about submitting the SIS file generated by Genesis to theOpen Signed online portal in the CHM help file supplied with Net60 (usually found in\Program Files\Red Five Labs\Net60\Documentation or your choseninstallation directory).

The DLL must be installed as a separate SIS file because Genesis cannot support installation ofthird-party native code as part of its build process. The SIS file must be signed with at least thecapabilities that the DLL requires in order for the installer to accept it. This means that the .NETapplication’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 Net60set (for example, AllFiles or DRM) is not allowed.

24

Page 25: NET Development on S60

Examples and source codeThis completes the examples showing how to build a simple GUI application, and how toextend it so that it accesses the Internet to download some data and interfaces with the nativeoperating system.

The source code for the examples may be obtained the Red Five Labs web site. We haveplaced a link to the exact location on the wiki page for this booklet, atdeveloper.symbian.com/nets60_wikipage.

The RedFiveLabs.Mobile assembly and namespaceRed Five Labs provide a specific assembly targeting S60 APIs that will make it easier to accessunderlying 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 createmanaged 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 RedFive Labs assembly.

Additional tools and utilitiesWhile Microsoft Visual Studio is an impressive piece of technology in its own right, there areadditional 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 quicklyinto any build toolchain to improve code quality and reliability.

FXCopThis tool takes a project and analyses the C# code to identify errors and misuse of APIs orcoding standards. FXCop can be integrated into the project workflow so that it can be runduring an automated build and the results fed into a defect workflow for triage and fixing. Thistherefore 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 theissues.

• 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.

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

25

Page 26: NET Development on S60

NDocThis tool is similar in many ways to Doxygen, the standard documentation generator for theS60 and Symbian OS documentation. However, NDoc generates documentation that is suitablefor integration into MSDN help and it interfaces with the auto help commands in MicrosoftVisual Studio to assign help comments to a function. NDoc can be downloaded fromndoc.sourceforge.net.

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

Recommended S60 toolsExtended panic logging is disabled on S60 devices by default. This means that any applicationerrors will not be displayed to the user and the application will simply exit. You can find moreabout 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 errorson the device as well as giving access to files. Y-Browser and its plug-ins can be downloadedfrom 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 isavailable with the debug version of the Net60 runtime. This application provides a postmortem view of significant events and profiling information during the running of anapplication. For more information on the Log Viewer and configuring logging, consult theNet60.chm help file and associated readme file, which can be found in \ProgramFiles\Red Five Labs\Net60\Documentation.

Finally, with the profusion of developer certificates that are generated during a project, it canbe a chore to know which certificate has which capabilities and which certificate is associatedwith which IMEI. The ‘DevcertList’ application extracts this information from the devcert anddisplays this as a usable list. You can download this application fromwiki.forum.nokia.com/index.php/Listing_IMEIs_and_Capabilities_in_a_DevCert.

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

‘TravelGuides ToGo, our travel guide application for location-aware mobile devices, wasinitially developed using the .NET Compact Framework. We wanted to expand our range ofcompatible devices beyond Windows Mobile, and since the S60 platform was the logical nextstep, 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 receivedfrom Red Five Labs, and the ease of getting our application up and running at a cost effectiveprice, has made Net60 an integral part of our development team.’

26

Page 27: NET Development on S60

SummaryNet60 provides you with new opportunities to find the right balance between access to lowlevel 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 largecollection of standardized classes in the framework library makes code reuse a reality. Andfinally, many of the time consuming development issues plaguing native C++, such as resourceleaks and memory corruption, can largely be eliminated with C#.

The binary compatible version of the .NET Compact Framework provided by Red Five Labsmakes 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 supportfor .NET CF 2.0.5

As the S60 platform continues to evolve, offering users the leading smartphone devices anddevelopers the cutting edge tools to deliver applications to those devices, Red Five Labs will bepart of this, offering you the tools and languages to create successful mobile applicationbusinesses.

Recommended readingFor 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, JohnWiley & 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 (ISBN-

10: 0735621632)

5 Other minor limitations are discussed in the Net60 FAQ found atwww.redfivelabs.com/content/faq.aspx.

27

Page 28: NET Development on S60

Developer resourcesSymbian Developer Networkdeveloper.symbian.com

Symbian Developer Network Newsletterdeveloper.symbian.com/register

Community web sites

Forum Nokiaforum.nokia.com

MOTODEVdeveloper.motorola.com

Samsung Mobile Innovatorinnovator.samsungmobile.com

28

Page 29: NET Development on S60

New from

Common Design Patterns for Symbian OS: The Foundations of Smartphone Software

Multimedia on Symbian OS: Inside the Convergence Device

Common Design Patterns for Symbian OSintroduces the common design patterns usedto implement a variety of applications andservices on Symbian OS. The book describespatterns based on the architectural elementsof Symbian OS and discusses how patternssuited for desktop software must be adaptedor even avoided on a mobile platform.

Combining the insights and experience ofsubject experts within Symbian and thethird-party developer community, this bookwill be an invaluable reference for anyoneworking with multimedia on Symbian OS.The authors provide details of the nativeC++ APIs for accessing camera, video,audio, image manipulation and radio tunerfunctionality, and discuss best practice,tips and tricks.

Symbian Press: developer.symbian.com/books

Page 30: NET Development on S60

New from

Quick Recipes on Symbian OS

Games on Symbian OS: A Handbook for Mobile Development

This book aims to make it easier to developapplications by describing a number ofcommon programming tasks and providingclear explanations of how to complete them.The recipes are divided by technology,including graphics, multimedia, location-basedservices, networking, telephony, connectivityand messaging.

Full sample code is available for download, soit can be used as a starting point in your ownprojects.

This book forms part of the TechnologySeries from Symbian Press. It describesthe key aspects of the mobile gamesmarketplace, with particular emphasis oncreating games for smartphones based onSymbian OS v9.x.

It also looks at C/C++ Standards supportavailable for developers porting games toSymbian OS, how to write for the N-Gageplatform, and coding for runtimes such asJava ME and Flash Lite.

Symbian Press: developer.symbian.com/books

Page 31: NET Development on S60

from

Developing Software for Symbian OS, Second Edition

Symbian OS C++ for Mobile Phones, Volume 3

This second edition of Developing Softwarefor Symbian OS helps software developersnew to Symbian OS to create smartphoneapplications. The original book has beenupdated for Symbian OS v9 and nowincludes a new chapter on applicationsigning and platform security, and updatesthroughout for Symbian OS v9 and changesto the development environment.

The latest edition of Richard Harrison’sexisting bestsellers draws on theexperience of Symbian’s own engineers tohelp you become an effective Symbian OSdeveloper.

If you’ve programmed in C++ at any leveland wish to develop software for Symbiansmartphones, this book gives you athorough grounding in writing C++applications for Symbian OS v9.

Page 32: NET Development on S60

from

For all Symbian C++ developers:Symbian OS Communications Programming, 2nd Editionby Iain Campbell

S60 Programming - A Tutorial Guideby Coulton & Edwards

Symbian OS Explainedby Jo Stichbury

Symbian OS Internalsby Jane Sales

Symbian OS Platform Securityby Craig Heath

Smartphone Operating System Concepts with Symbian OS by Mike Jipping

Accredited Symbian Developer Primerby Jo Stichbury & Mark Jacobs

Page 33: NET Development on S60

from

Published Booklets

A Guide to P.I.P.S.Carbide.c++ v1.3Coding StandardsCoding TipsCoverity Prevent on Symbian OSCreating Location-Aware ApplicationsData Sharing TipsEssential S60 - Developers’ GuideEssential UIQ - Getting StartedGetting StartedGetting to MarketJava ME on Symbian OSLocalizationPerformance TipsPlatform Security for allQuick Recipes Taster

Translated Booklets

Chinese RussianJapanese PersianKorean ItalianSpanish

Page 34: NET Development on S60

Notes:

Page 35: NET Development on S60

Notes:

Page 36: NET Development on S60

.NETDevelopmentons60

Using Symbian OS

If you like to use C# and .NET for development, and wantto get into mobile development then this booklet is for you!We explain how to use the .NET runtime on S60 devicesusing Net60 from Red Five Labs. The booklet shows how toget started, and how to extend a basic application to accessunderlying operating system APIs. Information about whereto find recommended tools, example code and furtherreference material is also included.

.NET Development on S60 is part of the Using SymbianOS series, designed to provide information in a handyformat to S60 developers.

Symbian PressSymbian Press publishes books designed tocommunicate authoritative, timely, relevant andpractical information about Symbian OS and relatedtechnologies. Information about the Symbian Pressseries can be found atdeveloper.symbian.com/books

Why? What? Where? How?