• No results found

Mobile Application Development Using.NET

N/A
N/A
Protected

Academic year: 2021

Share "Mobile Application Development Using.NET"

Copied!
163
0
0

Loading.... (view fulltext now)

Full text

(1)

Mobile Application Development

Using .NET

(2)

Page 2 of 163

(3)

Page 3 of 163

TABLE OF CONTENT

Chapter 1: Introduction & Creating First Mobile Application ... 8

.NET Compact Framework ... 8

Design Considerations for Microsoft Smartphone Applications ... 10

UI aspects of a Smartphone/Pocket PC ... 11

Navigational Controls ... 11

Screen Estate ... 12

Dropdown Menus ... 13

User Inputs ... 14

Context Menus ... 15

Text Input ... 15

ComboBox ... 16

Developing your first Application for windows mobile ... 17

What is required to develop Mobile Applications ... 17

Controls Supported in the Smartphone SDK ... 17

Self Test ... 30

Chapter 2: Working with Controls ... 31

Labels, TextBox, Button Controls ... 31

CheckBox, Radio Button Example ... 33

Self Test ... 36

Chapter 3: File Handling ... 37

Data Storage ... 37

The System.IO Namespace ... 39

File-Manipulation Classes ... 39

Byte-Level I/O Classes ... 40

Higher-Level I/O Classes ... 43

A Summary of I/O Classes ... 45

Notepad Application ... 47

(4)

Page 4 of 163

Creating Directory Browser ... 50

Self Test ... 54

Chapter 4: Working with SMS, Emails, PIM data ... 55

Pocket Outlook Object Model (POOM)... 55

Creating Contact List Form ... 55

Adding Find Option ... 56

Making Phone Call ... 59

Sending SMS ... 63

Self Test ... 65

Chapter 5: Accessing Database ... 66

.NET Compact Framework Data Providers ... 66

Connection ... 67

Command ... 67

DataReader ... 67

ParameterCollection ... 67

Parameter ... 67

Transaction ... 67

DataAdapter ... 67

SQL Server Compact - Mobile Edition ... 67

Setting up a Project ... 69

Creating a Database and Tables using Visual Studio ... 69

Displaying data from table into a data grid ... 72

Inserting the Data in the table ... 73

SQL Server CE Query Analyzer ... 75

Installing Query Analyzer ... 76

Opening a database ... 77

Creating a database ... 78

Creating Tables ... 79

Self Test ... 80

(5)

Page 5 of 163

Chapter 6: Using LINQ ... 83

What is LINQ? ... 83

LINQ Architecture on .NETCF ... 84

LINQ to DataSet ... 86

Self Test ... 89

Chapter 7: Working with Bluetooth ... 90

Bluetooth ... 90

Self Test ... 98

Chapter 8: Accessing Web Services & WCF Services ... 99

Introduction ... 99

Consuming a Web Service... 99

Making Synchronous Web service Calls ... 100

Making Asynchronous Web Service Calls ... 101

Consuming web service ... 105

Window Communication Foundation – WCF... 110

Advantage ... 110

Disadvantage ... 111

Difference between WCF and Web service ... 111

WCF Architecture ... 112

Contracts ... 112

Service contracts ... 113

Data contract ... 113

Message Contract ... 113

Policies and Binding ... 113

Service Runtime ... 113

Messaging ... 114

Activation and Hosting ... 114

Consuming the WCF Service ... 115

Self Test ... 119

(6)

Page 6 of 163

Chapter 9: Creating Mobile Sites ... 120

How Does It Work? ... 120

Software Requirements ... 121

How to Start ... 121

The Mobile ASP.NET Page ... 122

.NET Mobile Emulators ... 123

Using your Browser ... 123

Openwave Simulators ... 123

The Nokia Mobile Internet Toolkit ... 123

ASP.NET Mobile Web Forms ... 123

Mobile Pages ... 124

Mobile Forms ... 124

Automatic Paging ... 124

Creating a Mobile Web Application with Visual Studio ... 124

The Mobile Web Page ... 127

The Basics of Browser Identification ... 129

Mobile Page Processing ... 132

Self Test ... 133

Chapter 10: Using ASP.NET Mobile controls ... 135

ASP.NET Mobile Input ... 135

Input Controls ... 135

Numeric Input ... 135

Password Input ... 135

List Controls ... 135

User Interface Controls ... 136

Displaying Text ... 136

Single Forms ... 138

Multiple Forms ... 138

Links ... 139

(7)

Page 7 of 163

ASP.NET Mobile Events ... 139

Programming Events ... 139

Submitting Text ... 139

Validation Controls ... 140

Validating Input ... 141

The ValidationSummary Control ... 142

Validation Controls Reference ... 143

ASP.NET Mobile Lists ... 143

Selecting from a List ... 143

ASP.NET Mobile Selections ... 144

The SelectionList ... 144

ASP.NET Mobile Images ... 145

The Image Control ... 145

Image Types ... 146

ASP.NET Mobile Utilities ... 146

The AdRotator Control ... 146

Calendar Control ... 148

PhoneCall Control ... 149

Utility Controls ... 150

Self Test ... 151

Chapter 11: Accessing Database in Mobile Sites ... 152

ObjectList Control ... 152

Data Binding with the Object List ... 153

Accessing the TableAdapter ... 157

Accessing data through code ... 158

Data Binding with SelectionList & List controls ... 160

Self Test ... 163

(8)

Page 8 of 163

Chapter 1: Introduction & Creating First Mobile

Application

Mobile Computing is now everywhere today. The number of cell phones, PDA and other hand held mobile devices has exceeded the number of computers in the world. The world moving from traditional, voice based cellular phone services to be combined voice and data services as a result of increasing demand for mobile data access and deployment of high speed wireless data services utilizing a variety of wireless technologies. 2.5G/3G wireless services are being rolled out and used by rapidly growing number of subscribers. The mobile handsets that is available in market are also having very close configuration of software & hardware compared to Desktops & laptops, so all the computing we were doing on desktops & laptops now expected to be done on mobile phones.

.NET Compact Framework

The Microsoft .NET Compact Framework (.NET CF) is a version of the .NET Framework that is designed to run on resource constrained mobile/embedded devices such as personal digital assistants (PDAs), mobile phones, factory controllers, set-top boxes, etc. The .NET Compact Framework uses some of the same class libraries as the full .NET Framework and also a few libraries designed specifically for mobile devices such as .NET Compact Framework controls. However, the libraries are not exact copies of the .NET Framework. The ones in the .NET Compact Framework are scaled down to use less space.

The .NET Compact Framework is a subset of the .NET Framework. It consists of the base class libraries and has a few additional libraries that are specific to mobility and device development. The .NET Compact Framework runs on a high performance JIT Compiler. The Common Language Runtime (CLR) is built from the ground up to be specific to the .NET Compact Framework so that it runs more efficiently on small targeted devices that are limited in memory, resources, and must conserve battery power. To be able to run .NET Compact Framework applications, the targeted platforms must support the .NET Compact Framework runtime. .NET Compact Framework requires a minimum of Windows CE.NET (Windows CE version 4.1 for the released version of the .NET Compact Framework) with two exceptions:

(9)

Page 9 of 163

Microsoft Pocket PC, Microsoft Pocket PC, and Microsoft Pocket PC Phone Edition, Smartphone support the .NET Compact Framework.

Features of .NET Compact Framework

Support for LINQ (XML, Objects and Dataset)

Windows Communication Foundation

CLR Profiler / Performance Monitor

BCL enhancements: Compression support, Client-side certificates, Sound APIs

Shared code and increased efficiency

Robust code

Secure execution

Automatic deployment

Rapid application development that requires fast time-to-market

Single binary deployment that runs on various CPUs on the same platform without recompilation

Because recompilation is not necessary across .NET Compact Framework, controls, applications, and services can be easily moved from one device to another

Ability to call Win32 DLLs without having to rewrite them

Portable subset of .NET Framework

Debugging and development can be done by Visual Studio.NET

(10)

Page 10 of 163

Code is not prone to fail due to uninitialized variables

JIT compilation is not interpreted. JIT Compilation ultimately runs the code as processor native code

Garbage collection greatly minimizes memory leaks by cleaning up objects no longer in use

Uses the same naming conventions as in the .NET Framework

Simple Object Access Protocol (SOAP)

Design Considerations for Microsoft Smartphone Applications

If you're a .NET Compact Framework developer, you should be delighted that Microsoft recently announced support for the .NET CF in the new Smartphone 2003.

To start developing .NET CF Smartphone applications, you simply need to download and install the Smartphone 5/6 SDK. Visual Studio .NET 2008 will then automatically include the template for developing Smartphone applications.

Despite the same development environment and the familiarity of the .NET Compact Framework class libraries, developing for the Smartphone is not entirely the same thing as developing for the Pocket PC. New Smartphone developers need to understand and appreciate the design constraints of the new platform.

The main difference between a Smartphone and a device running the Pocket PC platform is its form-factor. Pocket PC devices use a stylus and a touch-sensitive screen for user input. In contrast, Smartphones do not have touch-sensitive screens;

instead they have to depend on softkeys mapped to fixed buttons on the keypad.

Figure 1 shows the three different versions of Windows Mobile 2003 deployed on different devices – Pocket PC, Pocket PC Phone Edition, and the Smartphone.

The form-factor for Pocket PC and the Pocket PC Phone Edition are almost identical (the real difference is the added phone functionality in the Pocket PC Phone Edition), but differs substantially from the Smartphone.

We will focus the discussion on the UI differences between a Pocket PC and a Smartphone.

(11)

Page 11 of 163 UI aspects of a Smartphone/Pocket PC

Navigational Controls

Since a Smartphone does not come with a touch-sensitive screen, familiarizing yourself with all the navigational buttons in a Smartphone is very important, if not essential. Figure 3 shows the typical layout of the navigational buttons in a Smartphone:

Figure 3. The navigational buttons of a Smartphone.

(12)

Page 12 of 163

Your application mainly interacts with the user through the two softkeys. So instead of using Buttons control to let a user tap on in a Pocket PC application, they are now replaced by these two softkeys.

You scroll through the various controls on the screen using the Up/Down arrows.

The Left/Right arrows are usually used for selecting options in controls such as the ComboBox. The Action key is used to select a control, somewhat equivalent to a

"tap" in the Pocket PC.

Because there are only two softkeys, if you have more than two options to let a user select, they need to be grouped together (see Figure 4). In this case, it would be better to name one of the two softkeys as "Menu" to let the user know that there are more than two options available:

Figure 4. Grouping options together and assigning to a softkey.

Screen Estate

A Pocket PC has a much larger screen estate as compared to a Smartphone. A Pocket PC screen size is typically 240 by 320 pixels whereas a Smartphone screen size is 176 x 180 pixels (minus the title and menubar). Figure 5 shows a comparison in screen size between the two platforms.

(13)

Page 13 of 163

Figure 5. The Start screen of a Pocket PC device versus that of Smartphone 2003.

Dropdown Menus

Because you can tap on the screen in a Pocket PC, the items in a dropdown menu

"drop" downwards when clicked (as its name correctly implies). In a Smartphone, however, there is no such control. To achieve the same effect, you need to customize the ListView control (see Figure 6). To select the item in a dropdown menu, you can use the Up/Down buttons or press the shortcut key. For example, pressing "7" is equivalent to navigating to the MSN Messenger item and pressing the Action key.

Figure 6. Implementation of dropdown menu in Pocket PC versus Smartphone 2003.

(14)

Page 14 of 163

User Inputs

Correct handling of text inputs in a Smartphone application can make a difference between success and failure for your application. Unlike the Pocket PC, which has a built-in SIP (Software-based Input Panel), the Smartphone does not have one.

Instead, the user has to rely on the numeric keypad to enter both text and numbers (see Figure 7).

When designing applications that require user input, be sure to minimize the number of keys the user has to press. Also, be sure to turn on numeric mode for fields that expect numbers (such as telephone numbers) and T9 input for alphanumeric fields.

Figure 7. User input on the Pocket PC versus user input in Smartphone.

Note that if you turn on numeric mode for text input, the title bar actually displays a

"123" symbol to provide visual cues (see Figure 8).

(15)

Page 15 of 163

Figure 8. Providing visual cues to indicate the input mode.

Context Menus

Context menus are useful for displaying options related to a particular piece of information. However, context menus are not supported in the Smartphone.

Instead, you have to make use of the softkeys to display menus related to a particular item (see Figure 9).

Figure 9. Context menus are not supported in Smartphone 2003.

Text Input

For a single line of text input, the TextBox control in Smartphone looks similar to that of the Pocket PC (see Figure 10).

Figure 10. Single line text input.

For multiple lines of text-input, you will see a right arrow at the right-end of the textbox. Press the Action key to bring you to a full screen (see Figure 11).

(16)

Page 16 of 163

Figure 11. Multiple line text input.

ComboBox

For ComboBoxes, you will not see a dropdown list of items (as in the Pocket PC);

instead you can see two arrows at the right-end of the textbox. To scroll through the list of items, use the Left/Right arrow keys. Alternately, you can also press the Action key to view the list of items available for selection (see Figure 12).

Figure 12. Selecting an item from a ComboBox control.

(17)

Page 17 of 163

Developing your first Application for windows mobile

What is required to develop Mobile Applications

 Visual Studio 2005/2008

 SQL Server 2008 Compact Edition

 .NET Compact Framework 3.5

 Windows Mobile SDK 5/6/6.5

 Active Sync / Windows Mobile Device Center

Controls Supported in the Smartphone SDK

The Smartphone 2003 SDK has further shrunk the number of controls you can use in a Smartphone application. In the current version of the Smartphone SDK, only 14 controls are supported (the DataGrid control is listed in the ToolBox but not supported in the Smartphone SDK). Figure 2 shows the list of controls supported in Pocket PC development versus Smartphone development.

(18)

Page 18 of 163

Launch Visual Studio 2008 and Create a new Project (File -> New). While creating a new Project, Visual Studio 2008 IDE provides an option to select an installed template, which will create Project with all the basic requirements/structure for development. For Windows Mobile, we will select option Smart Device and template Smart Device Project as shown below. You can also provide:

 Name: Name for Project. We will call it as MyFirstApp.

 Location: Location where this project will be created. Browse and set the desired location. We will use default location for now.

 Solution Name: Name for referring the Solution. Usually we keep it same as Project Name.

Select the .NET Framework 3.5 from the dropdown on the top right. Click OK.

Next step is to select the Target platform, .NET Compact Framework Version and Template. For our application we will select:

(19)

Page 19 of 163

 Target platform: Windows Mobile 6 Professional SDK

 .NET Compact Framework Version: .NET Compact Framework Version 2.0.

 Template: Device Application

Project MyFirstApp is successfully created and IDE will open a Form as shown.

By default Form is named as Form1. Let us first change the Name of the form. To do so select the form and the properties related to form will be listed in properties window.

(20)

Page 20 of 163

The entire properties list is in the form of Key Value pair. For changing Name of form, change value of property Name. For this example we will change it to HelloWorldForm. Now this form will be referred as HelloWorldForm throughout the application.

Changing form name doesn’t change form caption (title) it is still showing Form1. To change caption change the value of property name Text. For this example we will change the Text to Hello World.

Also the file representing this form in Solution Explorer will still be referred as Form1.cs, again you can either keep the name of the file as it is or can rename it. We will rename it to HelloWorld.cs.

Looking at the top of development section you will find HelloWorld.cs [Design], this represents design of the form. In order to write a code, you need to have a class representation of the designed form. To switch to class representation, right click on development section and select option View Code to view code written for the Form.

(21)

Page 21 of 163

View Code will open a Source Code editor HelloWorld.cs as shown below.

(22)

Page 22 of 163

To toggle back to design either you can select HelloWorld.cs [Design] from the tab above or again right click and select option View Designer.

We will now place a button on the form and on the click of that button will display a message. To place button on form, select Button from Toolbox and drag it on to the form.

By default button will be referred as button1, we can either change it or leave it as it is. For now we will change it and will provide a meaningful name btnShowMessage for reference.

(23)

Page 23 of 163

Now this button will be referred as btnShowMessage. But label on button is still referred as button1. And you are right, to change label on the button change the value of the property Text.

For showing message on button click we need to register a click event on button. To register click event, double click on the button. Double clicking on button will automatically register click event on the button and will create an abstract method to handle the same. Also view will change from designer to code.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

namespace MyFirstApp {

public partial class HelloWorldForm : Form

(24)

Page 24 of 163

{

public HelloWorldForm() {

InitializeComponent();

}

private void btnShowMessage_Click(object sender, EventArgs e) {

}

} }

As seen system creates a method btnShowMessage_Click with 2 parameters , one of type object and another one of type EventArgs.

We saw the method that is been created by system for handling the click event, now let us see how and where this method is register for handling click Event. Click on the Properties window.

(25)

Page 25 of 163

As seen method btnShowMessage_Click is registered for Click event on button.

Apart from Click, button has various other events as shown above.

Method btnShowMessage_Click was auto generated and registered by double clicking the button in designer view. One can even write a method directly using Source Code editor, but need to make sure to have 2 parameters, object and EventArgs in method signature and should return void.

For example we will create a method as follows:

private void showMessage(object sender, EventArgs e) {

}

To register newly created method showMessage on click Event. Click on Properties windows and then click on the right of the Event for which you want to register this method. A dropdown of all the methods with signature as explained above will be listed. Select appropriate method.

(26)

Page 26 of 163

Now let us come back to our application, we have done will most of it now just need to add the code to show message.

We will display message using MessageBox, which will popup on button click. For this we need to add following line to the method btnShowMessage_Click.

MessageBox.Show("Hello World");

After adding the above line to the method, entire source code looks as follows:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

namespace MyFirstApp {

public partial class HelloWorldForm : Form {

public HelloWorldForm() {

InitializeComponent();

}

private void btnShowMessage_Click(object sender, EventArgs e) {

MessageBox.Show("Hello World");

}

} }

Now we have done with basic coding, So next step is to compile and run this code.

We will run this code in Debug mode. To execute click at the top bar. A popup as shown below will come up asking where to deploy. For now select option

"Windows Mobile 6 Classic Emulator" and click Deploy.

(27)

Page 27 of 163

Windows Mobile Emulator will come up with the default screen as shown in Figure 1. After successful deployment, we can see our HelloWorld Form as shown in Figure

Now click on ShowMessage button and we can see the message that we have written on the popup as shown above. Click ok on the top right corner of the MessageBox to close it

(28)

Page 28 of 163

For developing same above program for Smartphone procedure is almost is same.

Create New Project from File Menu->New Project-> Select Language C#/VB ->Smart Device-> Smart Device Project->Enter Project Name -> Click OK

Now in the target platform select Windows mobile 5.0 Smartphone SDK or Windows Mobile 6 Standard SDK

(29)

Page 29 of 163 On the left menu type the text ok

Double click the OK menu & type below code (written VB, you can also write in C#)

MessageBox.Show("Hello World")

Complete code

Public Class Form1

Private Sub MenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles

MenuItem1.Click

MessageBox.Show("Hello World") End Sub

End Class

Click the left button to select OK menu, you will message box as shown in the figure

(30)

Page 30 of 163 Self Test

1. What is .NET Compact Framework?

a. It is a new version of .NET Framework b. A part .NET Framework

c. Sub version of .NET Framework for mobile platform d. All of the above

2. Smartphone supports all the controls that Pocket PC platform supports?

a. True b. False

3. Is LINQ is supported in .NET Framework 3.5?

a. True b. False

4. Which of the following is not required for developing application for windows mobile?

a. Visual Studio

b. Active Sync/Window Mobile Device Center c. .NET Framework

d. SQL Compact Edition e. All

5. Debugging of mobile application can be done without windows mobile emulator?

a. True b. False

(31)

Page 31 of 163

Chapter 2: Working with Controls

Smartphone supports less no of controls compared to Pocket PC as it is non-touch.

Window controls in .NET Compact Framework doesn’t not support all properties &

events as desktop. E.g. ComboBox control does not support the Sort property Labels, TextBox, Button Controls

Example 1: Create a simple application for addition of two numbers

1. Create a form with add textboxes & labels and a button and change the text

& name of the controls as shown in the figure

2. Double click the button write below

public partial class Form1 : Form {

public Form1() {

InitializeComponent();

}

private void btnAdd_Click(object sender, EventArgs e) {

(32)

Page 32 of 163

lbAns.Text =

Convert.ToString(Convert.ToInt32(txtNo1.Text) + Convert.ToInt32(txtNo2.Text));

} }

Example 2: Create a simple application for Smartphone for addition of two numbers

(33)

Page 33 of 163

1. Create a form with add textboxes & labels and a button and change the text

& name of the controls as shown in the figure 2. Double click the add menu write below.

public partial class Form1 : Form {

public Form1() {

InitializeComponent();

}

private void menuItem2_Click(object sender, EventArgs e) {

lbAns.Text = Convert.ToString(Convert.ToInt32(txtNo1.Text) + Convert.ToInt32(txtNo2.Text));

} }

Output:

CheckBox, Radio Button Example

Example 3: Create a form having a label with Sample Text, change the font color &

Font Style using radio buttons & checkboxes as shown in the figure

(34)

Page 34 of 163

1. Create a form with name say CheckBoxRadioExample and controls & modify the label & names as shown in the figure

2. Write the below code on click apply button

public partial class CheckBoxRadioExample : Form {

public CheckBoxRadioExample() {

InitializeComponent();

}

private void btnApply_Click(object sender, EventArgs e) {

//Apply ForeColor if (rdRed.Checked) {

lbSampleText.ForeColor = Color.Red;

}

else if (rdBlue.Checked) {

lbSampleText.ForeColor = Color.Blue;

}

else if (rdGreen.Checked) {

(35)

Page 35 of 163

lbSampleText.ForeColor = Color.Green;

}

//Apply Font Style

FontStyle fs=FontStyle.Regular ; if (ckBold.Checked)

{

fs = fs | FontStyle.Bold;

}

if (ckItalic.Checked) {

fs = fs | FontStyle.Italic ; }

if (ckUnderline.Checked) {

fs = fs | FontStyle.Underline;

}

lbSampleText.Font = new Font(lbSampleText.Font.Name, lbSampleText.Font.Size, fs);

} }

3. Change the Startup form in the program.cs file as shown below

Application.Run(new CheckBoxRadioExample());

(36)

Page 36 of 163 Self Test

1. In .Net Compact Framework controls doesn’t support all the properties as desktop version of .NET Framework?

a. True b. False

2. ComboBox does n’t support which from following?

a. Items b. Font

c. SelectedItem d. Sort

3. Button controls is supported in SmartPhone device?

a. True b. False

4. Menu’s is supported in both Pocket PC & SmartPhone Device?

a. True b. False

5. Base class for mobile Form is System.Windows.Forms.Form?

a. True b. False

(37)

Page 37 of 163

Chapter 3: File Handling

Data Storage

Data storage is an area where battery-powered mobile devices differ significantly from their desktop peers. It is not suitable to save data on power-consuming, rotating media, such as hard drives. As a result, mobile devices rely primarily on ROM, RAM, and removable Flash memory to store data. The size of the data storage has to be small, and the access speed is expected to be fast.

Prior to Windows Mobile 5.0, a typical Pocket PC device put the operating system, protected file storage, some device drivers, and application updates on ROM, and split RAM in two portions: program memory and the object store. Program memory provides space for applications to load and run, which is pretty much the same way that RAM is used in desktop operating systems. The object store includes a filesystem, the system registry, and property databases. For example, a user's personal information, data (including e-mail, calendars, and contacts), and user- installed software all reside in a portion of RAM.

The advantage of a RAM-based filesystem is obvious: fast access. This is particularly true when most of the operating is handled over a network. RAM, however, is volatile in nature. Retaining the data saved on RAM requires a constant power supply, which is why a backup battery is still powering the RAM after you turn off a PDA. Normally, the more RAM you have installed on a mobile device, the more power it will consume to retain the information stored in RAM. If both the main

(38)

Page 38 of 163

battery and the backup battery are drained, you are out of luck: All the applications installed on RAM and all the data saved on RAM are gone. To avoid such a devastating situation, the industry recommends a "72-hour rule," which mandates that a Pocket PC device must be able to preserve data for at least 72 hours after the critical battery level is reached. The 72-hour rule enables users to recharge the device without losing data.

Smartphone devices, conversely, take a different approach and are designed to work with persistent storage-based filesystems. The concept of the object store is non- existent in the context of a Smartphone device. By adopting a persistent storage architecture, Smartphone devices, therefore, require less RAM, and less RAM entails a lower cost and less power consumption. Below shows how data is allocated in a persistent storage-based filesystem.

There is, of course, no free lunch. Using persistent storage filesystems results in slower access speed; it takes more than ten times longer to access Flash ROM than it does to access RAM, and the storage performance heavily affects the entire system's performance. Windows Mobile 5.0 optimized storage performance by buffering a block of data before writing it back to persistent storage. Software developers should also try to minimize any negative impacts your application may have on the entire system. The following are the best-practice guidelines:

Minimize the size of your application.

Minimize the amount of persisted data your application requires.

Minimize the frequency of altering data.

(39)

Page 39 of 163

Minimize any writing to the registry.

Minimize polling and always try to use an event-driven design, if possible.

Note that beginning with Windows Mobile 5.0, Pocket PCs a persistent storage filesystem is preferred even though a RAM-based filesystem is still supported.

Another thing worth noting is that Windows Mobile adopts a unified directory view, which eliminates the drive letter in the traditional Windows directory structure. All the files, regardless of whether they are saved in RAM, ROM, or a storage card, have a centralized logical view, with the root of the directory beginning with the backslash (\).

Although mobile devices store data differently from desktop PCs, accessing Smartphone data programmatically still has a lot in common with accessing data in a desktop environment. The following section discusses which classes are supported and how to access local files in the Windows Mobile 5.0 Smartphone platform.

The System.IO Namespace

The System.IO namespace contains classes that are essential for accessing local files.

Logically, the classes can be grouped into the following three categories:

File-manipulation

Byte-level I/O

Higher-level I/O

File-Manipulation Classes

A number of classes have been defined and implemented in the System.IO namespace to interact with the filesystem. These classes enable you to manipulate files and directories, such as creating, deleting, copying, and moving files.

In the .NET Compact Framework, two classes are available for accessing information pertaining to directories: Directory and DirectoryInfo. Likewise, the File and FileInfo classes can be used to access file-based information.

The Directory and File classes are static classes, which means you do not need to create an instance to use them. For example, if you need to create a new file called myfile1, you can simply call the Create() method of the File class, as follows:

File.Create("myfile1")

(40)

Page 40 of 163

Static classes such as Directory and File are particularly useful if you want to perform some quick directory-related operations.

The info classes FileInfo and DirectoryInfo provide similar functions to the File and Directory classes; however, they are not static classes. To create a new file named myfile1 using the FileInfo class, you must first create an instance of FileInfo and then call the Create() method:

FileInfo myFileInfo = new FileInfo ("myfile1");

myfileInfo.Create();

Another difference between the nonstatic and the static file/directory classes is the level and format of the information they return. For instance, the following examples demonstrate how to search for all the .txt files in the My Documents folder using the Directory and DirectoryInfo classes, respectively:

//Search *.txt file with Directory class

string[] fileList = Directory.GetFiles(@"\My Documents", "*.txt");

//Search *.txt file with DirectoryInfo class

DirectoryInfo myDirInfo = new DirectoryInfo(@"\My Documents");

FileInfo[] fInfoList = myDirInfo.GetFiles("*.txt");

As you can see, the Directory class needs to take both the path name and search pattern, whereas the DirectoryInfo class requires only the search pattern because the path name is already known to the myDirInfo object when you create it. When the Directory class finishes searching, it returns an array of strings, whereas the DirectoryInfo class returns an array of FileInfo objects.

Note The @ symbol indicates that the strings will be escaped. This is handy when you are dealing with path names. Without the @ symbol, you have to use a string such as "\\My documents\\subfolder" rather than @"\My Documents\subfolder".

Byte-Level I/O Classes

The Stream class is the base class of System.IO objects and is the foundation of all file access I/O classes. It provides a basic data transfer capability: moving bytes from one data unit to another, independent of data storage media. It includes methods such as Read() and Write() to perform I/O synchronously, and it includes asynchronous I/O methods, such as BeginRead() and BeginWrite(). The Stream class

(41)

Page 41 of 163

is designed as an abstract class (or interface) in the .NET Compact Framework, which means the base class only defines the functionalities, without really doing the actual work. You can perform the actual I/O tasks by using the derived FileStream class and MemoryStream class. The FileStream class supports stream access to physical files, whereas the derived MemoryStream class allows stream operations on physical memory.

The following is a typical procedure to access a physical file with the FileStream class:

1. Create a FileStream object and specify the filename and FileMode. The FileMode enumeration is a parameter to indicate whether to open a file or to create a file. The four common FileMode values are as follows:

1. FileMode.Open - Opens an existing file. If the file does not exist, a System.IO .FileNotFoundException is thrown.

2. FileMode.Create - Creates a new file. If the file already exists, it overwrites the existing file.

3. FileMode.OpenOrCreate - Opens a file if the file exists; otherwise, a new file will be created.

4. FileMode.Append - Opens or creates a file in the same way as FileMode.OpenOrCreate. Then it seeks the end of the file to read or to write.

2. Optionally, specify file access mode and file sharing mode. The FileAccess enumeration parameter has three values: Read, Write, and ReadWrite.

Specifying this optional parameter can make your program safer. For instance, if you set the FileAccess enumeration to Read, an opened file stream can avoid accidental writing operations. Note that not every combination of FileMode parameter and FileAccess parameter is valid. For example, it is not applicable to create a new file with FileMode.Create and set the FileAccess to Read. An ArgumentException will be thrown because creating a file requires either FileAccess.Write or FileAccess.ReadWrite . The FileShare enumeration denotes how others can open the file. The typical enumeration values are FileShare.Read, FileShare.Write, FileShare.ReadWrite, and FileShare.None.

(42)

Page 42 of 163

3. Read or write file with the Read(), ReadByte(), Write() or WriteByte() methods.

4. Close the file stream with the Close() method.

The following code snippet opens an existing file myfile1 in the root directory and reads the first 100 bytes into the integer array buff[]:

using System.IO;

using System.Windows.Forms;

...

try {

//Create a filestream fsRead with Open mode and Read access FileStream fsRead = new FileStream(@"\myfile1", FileMode.Open, FileAccess.Read);

//Create the integer array buff[]

int[] buff = new int[100];

//Read the first 100 bytes from the fsRead to buff[]

for (int i = 0; i < 100; i++) buff[i] = fsRead.ReadByte();

//close the filestream fsRead fsRead.Close();

}

//Error handling:

catch (IOException e) {

//Show the error information.

MessageBox.Show("I/O Error: "+ e.ToString());

}

Writing data using the FileStream class is very similar to reading data from the file stream. The following code illustrates how to write ASCII-coded data into a FileStream object fsWrite. The example writes the lowercase letters a through z to file myfile2 with the integer value of each letter's ASCII code:

(43)

Page 43 of 163

using System.IO;

using System.Windows.Forms;

...

try {

//Create a filestream fsWrite with Write access, and Share Read mode FileStream fsWrite = new FileStream (@"\myfile2",

FileMode.Create, FileAccess.Write, FileShare.Read);

// Write to the stream with ascii value of each letter for (int i = 0; i < 26; i++)

fsWrite.WriteByte((byte) ('a'+i));

//Close the filestream fsWrite fsWrite.Close();

}

//Error handling:

catch (IOException e) {

//Show the error information

MessageBox.Show("I/O Error: " + e.ToString());

}

Byte-level I/O classes provide access to data stored in various storage media in a byte-oriented fashion. If you are interested in reading or writing data in a form other than the native byte format (such as number, strings, or text with specific coding), you should familiarize yourself with the higher-level I/O classes.

Higher-Level I/O Classes

The higher-level I/O components include a variety of reader/writer objects to perform data-specific I/O operations. This is achieved by wrapping the higher-level I/O classes around the basic byte-level classes.

Two major reader/writer classes can be found in the System.IO namespace:

BinaryReader and BinaryWriter and TextReader and TextWriter.

As their names imply, the BinaryReader and BinaryWriter classes read or write data in binary format, respectively. To use them correctly, you need to call the data type- specific methods for either reading or writing. For example, if you want to read a string from a stream using a BinaryReader object, use the ReadString() method

(44)

Page 44 of 163

instead of the Read() method. The BinaryReader and BinaryWriter classes also enable you to specify how the data is encoded. This can be done by specifying the optional Encoding enumeration type in the System.Text namespace. The following example shows how to read the first string from file myfile1 using the default system encoding:

using System.IO;

using System.Windows.Forms;

using System.Text;

...

try {

//Create a filestream fsRead with Open mode and Read access FileStream fsRead = new FileStream(@"\myfile1", FileMode.Open, FileAccess.Read);

//Create a new BinaryReader bReader from fsRead //using the system default decoding

BinaryReader bReader = new BinaryReader(fsRead, Encoding.Default);

//Read the first string in the file to string str string str = bReader.ReadString();

//Close the filestream fsRead fsRead.Close();

}

//Error handling:

catch (IOException e) {

//Show the error information

MessageBox.Show("I/O Error: " + e.ToString());

}

You can see from this example that the BinaryReader class and the BinaryWriter class rely on the lower-level I/O classes to actually open or create the file. Once the file is opened or created, these two classes provide a number ways for programmers to read and write data using the desired data types, such as string, double, short, long, etc.

(45)

Page 45 of 163

The System.IO namespace also provides the TextReader and TextWriter classes, which enable you to read or write text characters from/to a stream, respectively. In the .NET Compact Framework, both TextReader and TextWriter are abstract classes.

For that reason, you should use the derived StreamReader and StreamWriter classes and the derived StringReader and StringWriter classes to access the data in Stream objects. The StreamReader and StreamWriter classes can read and write a number of data types, respectively, and support a variety of encoding methods. StringReader and StringWriter objects, conversely, support only read and write in string format, which is defined in the StringBuilder class from the System.Text namespace.

You can create a StreamReader or StreamWriter object either from an opened file stream or directly from the name of the file. The following code snippet reads the first line from file \myfile1 to a string str:

streamReader sReader = new StreamReader (@"\myfile1");

string str = sReader.ReadLine();

A Summary of I/O Classes

Below Table summarizes the commonly used the I/O class in the System.IO namespace of the .NET Compact Framework.

Common Classes in the System.IO Namespace Open table as spreadsheet

Class Description

BinaryReader Reads data from an I/O stream as binary values in a specific coding.

BinaryWriter Writes data to an I/O stream as binary values in a specific coding.

Directory Exposes static methods for directory-related operations. Cannot be inherited.

DirectoryInfo Exposes instance methods for directory-related operations. Cannot be inherited.

File Exposes static methods for file-related operations. Cannot be inherited.

(46)

Page 46 of 163

Common Classes in the System.IO Namespace Open table as spreadsheet

Class Description

FileInfo Exposes instance methods for file-related operations. Cannot be inherited.

FileStream Provides a stream around a file. Supports both synchronous and asynchronous read and write operations.

FileStreamInfo The base abstract class of FileInfo and Directory info classes.

IOException The exceptions that are raised when I/O errors occur.

MemoryStream Creates a stream around a block of memory.

Path Exposes static methods to retrieve the path information of files or directories.

Stream Provides a generic view of a sequence of bytes. This abstract class is the base class of the FileStream class and the MemoryStream class.

StreamReader Implements a TextReader class for reading characters from a stream in a specific coding.

StreamWriter Implements a TextWriter class for writing characters to a stream in a specific coding.

StringReader Implements a TextReader class to read from a string.

StringWriter Implements a TextWriter class to write to a string.

TextReader Represents a generic reader that reads a sequence of characters. It is the base class of the StreamReader class and the StringReader class.

TextWriter Represents a generic writer that writes a sequence of characters. It

(47)

Page 47 of 163

Common Classes in the System.IO Namespace Open table as spreadsheet

Class Description

is the base class of the StreamWriter class and the StringWriter class.

The System.IO namespace in the .NET Compact Framework supports a subset of the classes and structures in the full .NET Framework. The following classes and structures are currently not supported in the .NET Compact Framework. In addition, file attributes, such as Hidden, Archive, and Read-Only, are not supported in the .NET Compact Framework. Therefore, methods such as GetAttributes are also not supported.

o BufferedStream class

o ErrorEventArgs class

o FileLoadExceptions class

o FileSystemEventArgs class

o FileSystemWatcher class

o InternalBufferOverflowException class

o IODescriptionAttribute class

o RenamedEventArgs class

o WaitforChangedResult structure

Notepad Application

Creating simple Pocket Notepad application using StreamReader & StreamWriter classes

(48)

Page 48 of 163

1. Create the form, add a textbox set multiline property true

2. Create the menu as shown in the figure

3. Add Open file dialog & save file dialog to it

4. On click of new add below code.

txtFile.Text = "";

5. On click of save add below code

if (saveFileDialog1.ShowDialog() == DialogResult.OK) {

StreamWriter objWriter = new StreamWriter(saveFileDialog1.FileName);

objWriter.Write(txtFile.Text);

objWriter.Close();

MessageBox.Show("File Saved");

}

6. On click of open menu add below code

if (openFileDialog1.ShowDialog() == DialogResult.OK) {

StreamReader objReader = new StreamReader(openFileDialog1.FileName);

txtFile.Text = objReader.ReadToEnd();

objReader.Close();

(49)

Page 49 of 163

}

Here is the complete code

using System;

using System.Linq;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.IO;

namespace SmartDeviceProject1 {

public partial class NotePad : Form {

public NotePad() {

InitializeComponent();

}

private void menuItem3_Click(object sender, EventArgs e) {

txtFile.Text = "";

}

private void menuItem4_Click(object sender, EventArgs e) {

if (saveFileDialog1.ShowDialog() == DialogResult.OK) {

StreamWriter objWriter = new StreamWriter(saveFileDialog1.FileName);

objWriter.Write(txtFile.Text);

objWriter.Close();

MessageBox.Show("File Saved");

} }

private void menuItem2_Click(object sender, EventArgs e) {

(50)

Page 50 of 163

if (openFileDialog1.ShowDialog() == DialogResult.OK) {

StreamReader objReader = new StreamReader(openFileDialog1.FileName);

txtFile.Text = objReader.ReadToEnd();

objReader.Close();

} } } }

Creating Directory Browser

Objective

Create a Directory Browser for browsing files & folders

Procedure

1. Create a form with a TreeView control

2. Add a ImageList control to it, add icons

(51)

Page 51 of 163

3. Complete code is as follows

using System;

using System.IO;

using System.Linq;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

namespace PocketPC_Example_CS {

public partial class DirectoryBrowser : Form {

static FileAttributes attrStorageCard =

FileAttributes.Directory | FileAttributes.Temporary;

public DirectoryBrowser()

(52)

Page 52 of 163

{

InitializeComponent();

}

private void DirectoryBrowser_Load(object sender, EventArgs e) {

//Create the root node of the TreeView treeView1.ImageList = this.imageList1;

TreeNode rootNode = new TreeNode();

rootNode.ImageIndex = 0;

rootNode.SelectedImageIndex = 0;

treeView1.Nodes.Add(rootNode);

//Retrieve all the directories and files GetAllDirs(@"\", treeView1.Nodes[0]);

treeView1.Nodes[0].Expand(); //Expand first layer

}

private void GetAllFiles(DirectoryInfo curDir, TreeNode curNodes) {

//Get all the files in current directory try

{

foreach (FileInfo fi in curDir.GetFiles()) {

TreeNode tnFile = new TreeNode(fi.Name);

//Set icons for executable files

if (fi.Name.EndsWith("exe") || fi.Name.EndsWith("dll")) {

tnFile.ImageIndex = 4;

tnFile.SelectedImageIndex = 4;

}

//Set icons for non-executable files else

{

tnFile.ImageIndex = 5;

tnFile.SelectedImageIndex = 5;

}

//Add the file to current treenode

(53)

Page 53 of 163

curNodes.Nodes.Add(tnFile);

} } catch {

//Do nothing if there are no files return;

}

}

private void GetAllDirs(string DirName, TreeNode curNodes) {

DirectoryInfo curDir = new DirectoryInfo(DirName);

try {

foreach (DirectoryInfo di in curDir.GetDirectories()) {

TreeNode tnDir = new TreeNode(di.Name);

//Not a storage card

if ((di.Attributes & attrStorageCard) != attrStorageCard) {

tnDir.ImageIndex = 2;

tnDir.SelectedImageIndex = 3;

}

else //Storage Card {

tnDir.ImageIndex = 1;

tnDir.SelectedImageIndex = 1;

}

//Add current directory to curNodes.Nodes.Add(tnDir);

//Recursively retrieving directories

//String fullPath = di.Parent + @"\" + di.Name;

//GetAllDirs(fullPath, tnDir);

GetAllDirs(di.FullName, tnDir);

}

//Get files in current directories

(54)

Page 54 of 163

GetAllFiles(curDir, curNodes);

} catch {

//Do nothing if there are no more directories return;

} } }

}

Self Test

1. Which are best practices for minimizing the negative impacts of application on entire system?

a. Minimize the size of your application.

b. Minimize the amount of persisted data your application doesn’t requires.

c. Minimize the frequency of altering data.

d. Minimize any writing to the registry.

2. Which namespace is used for creating FileStream object?

a. System b. System.IO

c. System.IO.File d. All

3. Directory and File classes are static classes?

a. True b. False

4. Which of the following FileMode will not throw error if file does not exists?

a. FileMode.Open b. FileMode.Create

c. File.OpenOrCreate d. FileMode.Append 5. Which of the following can be good option to read a image file?

a. StreamReader b. TextReader

c. BinaryReader d. ImageReader

(55)

Page 55 of 163

Chapter 4: Working with SMS, Emails, PIM data

Windows mobile consists of pocket outlook, which is lighter version of Desktop outlook which is used normally for accessing mail, managing contacts, tasks, and calendar. Pocket outlook SMS option additionally. Atomizing pocket outlook is very useful and required for business purpose. E.g. you have received an SMS you may want it to be converted into a task. You may want to send SMS to your customer automatically saying “thank you for contacting us” when you disconnect a call.

Pocket Outlook Object Model (POOM)

Microsoft provides a series of APIs for developers to access Microsoft Outlook from Windows CE-based devices. The classes of those APIs are termed Pocket Outlook Object Model (POOM). The goal of POOM is to provide a means for developers to manipulate e-mail and PIM data, such as contacts, calendars, and tasks data.

The steps to access data in Outlook Mobile are as follows:

1. Establish a POOM session.

2. Create a reference to PIM item folders.

3. Retrieve the PIM item from the Pocket Outlook database.

4. Close the POOM session.

Creating Contact List Form

Example 1: Create a simple form for display all contacts from phonebook

1. Create a Form, add ListView to it

2. Add three columns to ListView i.e. Name, Mobile, Email

3. Change the View property of the ListView to Details

4. Add a image list, add a icon to it

5. Write below code

(56)

Page 56 of 163

using System;

using System.Linq;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using Microsoft.WindowsMobile.PocketOutlook;

namespace PocketPC_Example_CS {

public partial class ContactList : Form {

public ContactList() {

InitializeComponent();

}

private void ContactList_Load(object sender, EventArgs e) {

OutlookSession _outlookapp = new OutlookSession();

foreach (Contact c in _outlookapp.Contacts.Items) {

ListViewItem itm = new ListViewItem();

itm.ImageIndex = 0;

itm.Text=c.FirstName + " " + c.LastName;

itm.SubItems.Add(c.MobileTelephoneNumber);

itm.SubItems.Add(c.Email1Address);

listView1.Items.Add(itm);

} } } }

Adding Find Option

Example 2: Adding Find Option in above program for filtering the contacts by name

(57)

Page 57 of 163

1. In the previous form add textbox for entering the name and find button

2. Add menu options like show all & edit and exit as shown above

3. Make the changes in the code as below

using System;

using System.Linq;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using Microsoft.WindowsMobile.PocketOutlook;

namespace PocketPC_Example_CS {

public partial class ContactList : Form {

public ContactList() {

(58)

Page 58 of 163

InitializeComponent();

}

private void ContactList_Load(object sender, EventArgs e) {

DisplayAll();

}

private void DisplayAll() {

OutlookSession _outlookapp = new OutlookSession();

listView1.Items.Clear();

foreach (Contact c in _outlookapp.Contacts.Items) {

ListViewItem itm = new ListViewItem();

itm.ImageIndex = 0;

itm.Text = c.FirstName + " " + c.LastName;

itm.SubItems.Add(c.MobileTelephoneNumber);

itm.SubItems.Add(c.Email1Address);

listView1.Items.Add(itm);

} }

private void btnFind_Click(object sender, EventArgs e) {

OutlookSession _outlookapp = new OutlookSession();

PropertyDescriptor _contact;

int _contactIndex;

Contact c;

_contact = TypeDescriptor.GetProperties(typeof(Contact))["FirstName"];

_contactIndex = _outlookapp.Contacts.Items.Find(_contact, txtName.Text);

if (_contactIndex == -1) //Find by Last Name {

_contact = TypeDescriptor.GetProperties(typeof(Contact))["LastName"];

_contactIndex = _outlookapp.Contacts.Items.Find(_contact, txtName.Text);

}

if (_contactIndex == -1)

References

Related documents

Specifically, the risk is considered as the area of the distribution of the arrival time fell after the latest time of the time window, and the mean of the arrival time is

We have shown in Section 2.1 that for the DI model and the SP models, in so far as we assume a homogeneous susceptible population such that there is one group of

At the end of '99, the standards for reservist training statewide jumped to 650 hours but Blanas could have grandfathered Jack Sellers and other major cronies the way Sheriff

e ff ects of FSH on early follicle populations in the absence of luteinizing hormone (LH) activity, we examined mature hypogonadal ( hpg ), gonadotrophin-deficient mice

Echolocation: paired fm-echolocation clicks between 7-60 kHz (recordings from Sinai). Distribution in Egypt: The Egyptian fruit bat is widely distributed in the Nile valley,

You can choose which categories will display on the News Archive page format through the News List Properties on the Page Manager view of the archive page..  News List: This

The expression model of this type of multiple relationship is “the head- word relationship some (concept A and (happening before. some concept B)).” Taking the timeline of symptom

Private motor boat round transfer to Hvar Island with guided walking tour of Hvar and Stari Grad Town, with visit to wineries and private lunch in the olive grove. Guided tour