Mobile Application Development Using.NET



Similar documents
Visual Basic. murach's TRAINING & REFERENCE

Welcome to MaxMobile. Introduction. System Requirements. MaxMobile 10.5 for Windows Mobile Pocket PC

How To Develop A Mobile Application On Sybase Unwired Platform

Tutorial: Windows Mobile Application Development. Sybase Unwired Platform 2.1 ESD #2

Considerations for Mobile Application Development

USER GUIDE Appointment Manager

Welcome to MaxMobile. Introduction. System Requirements

Search help. More on Office.com: images templates

Creating Form Rendering ASP.NET Applications

VB.NET - WEB PROGRAMMING

Hands-On Lab. Building a Data-Driven Master/Detail Business Form using Visual Studio Lab version: Last updated: 12/10/2010.

PORTAL ADMINISTRATION

Simply Accounting Intelligence Tips and Tricks Booklet Vol. 1

Legal Notes. Regarding Trademarks KYOCERA Document Solutions Inc.

MAS 500 Intelligence Tips and Tricks Booklet Vol. 1

Getting Started with Telerik Data Access. Contents

Expanded contents. Section 1. Chapter 2. The essence off ASP.NET web programming. An introduction to ASP.NET web programming

Creating XML Report Web Services

Content Management System User Guide

13 Managing Devices. Your computer is an assembly of many components from different manufacturers. LESSON OBJECTIVES

Contents. Introduction. Chapter 1 Some Hot Tips to Get You Started. Chapter 2 Tips on Working with Strings and Arrays..

Raptor K30 Gaming Software

TestManager Administration Guide

14.1. bs^ir^qfkd=obcib`qflk= Ñçê=emI=rkfuI=~åÇ=léÉåsjp=eçëíë

Introduction to Windows Mobile Development. Daniel Moth Developer and Platform Group Microsoft UK

A SharePoint Developer Introduction. Hands-On Lab. Lab Manual SPCHOL306 Using Silverlight with the Client Object Model VB

Teradata SQL Assistant Version 13.0 (.Net) Enhancements and Differences. Mike Dempsey

Dynamic Web Programming BUILDING WEB APPLICATIONS USING ASP.NET, AJAX AND JAVASCRIPT

Quickstart Tutorial. Bradford Technologies, Inc. 302 Piercy Road, San Jose, California fax

Create a New Database in Access 2010

CHAPTER 10: WEB SERVICES

ADOBE READER AND ACROBAT

Table Of Contents. iii

INTEGRATING MICROSOFT DYNAMICS CRM WITH SIMEGO DS3

Getting Started with the LabVIEW Mobile Module Version 2009

Tips and Tricks SAGE ACCPAC INTELLIGENCE

Installing LearningBay Enterprise Part 2

Introduction to Microsoft Access 2003

General Product Questions Q. What is the Bell Personal Vault Vault?...4. Q. What is Bell Personal Vault Backup Manager?...4

AQA GCSE in Computer Science Computer Science Microsoft IT Academy Mapping

User Guide. DocAve Lotus Notes Migrator for Microsoft Exchange 1.1. Using the DocAve Notes Migrator for Exchange to Perform a Basic Migration

Bookstore Application: Client Tier

SelectSurvey.NET Developers Manual

Content Author's Reference and Cookbook

Call Recorder Oygo Manual. Version

Python for Series 60 Platform

Hypercosm. Studio.

Decision Support AITS University Administration. Web Intelligence Rich Client 4.1 User Guide

EMC Documentum Webtop

v1.1.0 SimpleSQL SQLite manager for Unity3D echo17.com

Working with SQL Server Integration Services

FOR WINDOWS FILE SERVERS

LDCDP GdW. L force Controls. Ä.GdWä. Software Manual. Industrial PC. WindowsR CE Thin Client. Operating system

Visual C# 2012 Programming

CRM Setup Factory Installer V 3.0 Developers Guide

Data Tool Platform SQL Development Tools

Creating Database Tables in Microsoft SQL Server

Module One: Getting Started Opening Outlook Setting Up Outlook for the First Time Understanding the Interface...

Abstract. For notes detailing the changes in each release, see the MySQL for Excel Release Notes. For legal information, see the Legal Notices.

UC Express Quick Start Guide

IriScene Remote Manager. Version 4.8 FRACTALIA Software

Walkthrough: Creating and Using an ASP.NET Web Service in Visual Web Developer

SQL Server Database Web Applications

Live Maps. for System Center Operations Manager 2007 R2 v Installation Guide

Programming in C# with Microsoft Visual Studio 2010

Building A Very Simple Web Site

Visual Basic 2010 Essentials

Microsoft Access 2010 Part 1: Introduction to Access

USER S MANUAL. AXIS Mobile Monitor

S PT-E550W ELECTRONIC E C LABELING L SYSTEM

Subscribe to RSS in Outlook Find RSS Feeds. Exchange Outlook 2007 How To s / RSS Feeds 1of 7

Microsoft Office System Tip Sheet

Desktop, Web and Mobile Testing Tutorials

BillQuick Agent 2010 Getting Started Guide

Java 7 Recipes. Freddy Guime. vk» (,\['«** g!p#« Carl Dea. Josh Juneau. John O'Conner

How To Use Query Console

Web Services API Developer Guide

Editor Manual for SharePoint Version December 2005

Visualization with Excel Tools and Microsoft Azure

Oracle SOA Suite 11g Oracle SOA Suite 11g HL7 Inbound Example

Synchronizer Installation

Oracle Beehive. Using Windows Mobile Device Release 2 ( )

DataPA OpenAnalytics End User Training

Table of Contents. Welcome Login Password Assistance Self Registration Secure Mail Compose Drafts...

Results CRM 2012 User Manual

Appointment Scheduler

Excel Reports and Macros

Using SQL Server Management Studio

Kentico CMS 5.5 User s Guide

Avalanche Remote Control User Guide. Version 4.1.3

Interworks. Interworks Cloud Platform Installation Guide

Programmabilty. Programmability in Microsoft Dynamics AX Microsoft Dynamics AX White Paper

Using the Query Analyzer

Microsoft Office Access 2007 which I refer to as Access throughout this book

Configuring, Customizing, and Troubleshooting Outlook Express

EXAM PRO:Design & Develop Windows Apps Using MS.NET Frmwk 4. Buy Full Product.

ABOUT THIS COURSE... 3 ABOUT THIS MANUAL... 4 LESSON 1: PERSONALIZING YOUR

Transcription:

Using.NET

Page 2 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 Page 3 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 Page 4 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 Page 5 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 Page 6 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 Page 7 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: Page 8 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 Page 9 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. Page 10 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. Page 11 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. Page 12 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. Page 13 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). Page 14 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). Page 15 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. Page 16 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. Page 17 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: Page 18 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. Page 19 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. Page 20 of 163

View Code will open a Source Code editor HelloWorld.cs as shown below. Page 21 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. Page 22 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 Page 23 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. Page 24 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. Page 25 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. Page 26 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 Page 27 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 Page 28 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 End Sub End Class MessageBox.Show("Hello World") Click the left button to select OK menu, you will message box as shown in the figure Page 29 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 Page 30 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) Page 31 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 Page 32 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 Page 33 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) Page 34 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; fs); lbsampletext.font = new Font(lbSampleText.Font.Name, lbsampletext.font.size, 3. Change the Startup form in the program.cs file as shown below Application.Run(new CheckBoxRadioExample()); Page 35 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 Page 36 of 163 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

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 userinstalled 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 Page 37 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 nonexistent 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. Page 38 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") Page 39 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 Page 40 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. Page 41 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: Page 42 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 typespecific 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 Page 43 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. Page 44 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 BinaryReader BinaryWriter Directory DirectoryInfo File Description Reads data from an I/O stream as binary values in a specific coding. Writes data to an I/O stream as binary values in a specific coding. Exposes static methods for directory-related operations. Cannot be inherited. Exposes instance methods for directory-related operations. Cannot be inherited. Exposes static methods for file-related operations. Cannot be inherited. Page 45 of 163

Common Classes in the System.IO Namespace Open table as spreadsheet Class FileInfo FileStream Description Exposes instance methods for file-related operations. Cannot be inherited. 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 Stream StreamReader StreamWriter StringReader StringWriter TextReader TextWriter Exposes static methods to retrieve the path information of files or directories. Provides a generic view of a sequence of bytes. This abstract class is the base class of the FileStream class and the MemoryStream class. Implements a TextReader class for reading characters from a stream in a specific coding. Implements a TextWriter class for writing characters to a stream in a specific coding. Implements a TextReader class to read from a string. Implements a TextWriter class to write to a string. Represents a generic reader that reads a sequence of characters. It is the base class of the StreamReader class and the StringReader class. Represents a generic writer that writes a sequence of characters. It Page 46 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 o o o o o o o o BufferedStream class ErrorEventArgs class FileLoadExceptions class FileSystemEventArgs class FileSystemWatcher class InternalBufferOverflowException class IODescriptionAttribute class RenamedEventArgs class WaitforChangedResult structure Notepad Application Creating simple Pocket Notepad application using StreamReader & StreamWriter classes Page 47 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(); Page 48 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) Page 49 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 Page 50 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() Page 51 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 Page 52 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 Page 53 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 Page 54 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 Page 55 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 Page 56 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() Page 57 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) Page 58 of 163

MessageBox.Show("Not found"); else c = _outlookapp.contacts.items[_contactindex]; listview1.items.clear(); 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 menuitem3_click(object sender, EventArgs e)//show all menu DisplayAll(); private void menuitem2_click(object sender, EventArgs e)//exit menu this.close(); Making Phone Call Example 3: In the previous create an option for making phone call select contact in the listview Page 59 of 163

1. Add menu option call to main menu 2. Add a Context Menu with menu option Call 3. In the ListView Control Property select this contextmenu1 from ContextMenu Property. 4. Double click the Call menu add below code 5. For Context Menu Call option in the properties Panel, in the event list you can same event handler for click event string PhoneNumber=listView1.Items[listView1.SelectedIndices[0]].SubItems[1].Text; if(phonenumber!="") Phone p = new Phone(); p.talk(phonenumber); 6. Complete code as follows using System; using System.Linq; using System.Collections.Generic; Page 60 of 163

using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Microsoft.WindowsMobile.PocketOutlook; using Microsoft.WindowsMobile.Telephony; using Microsoft.WindowsMobile.Status; namespace PocketPC_Example_CS public partial class MakingPhoneCalls : Form public MakingPhoneCalls() InitializeComponent(); 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); Page 61 of 163

if (_contactindex == -1) //Find by Last Name _contact = TypeDescriptor.GetProperties(typeof(Contact))["LastName"]; _contactindex = _outlookapp.contacts.items.find(_contact, txtname.text); if (_contactindex == -1) MessageBox.Show("Not found"); else c = _outlookapp.contacts.items[_contactindex]; listview1.items.clear(); 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 menuitem3_click(object sender, EventArgs e)//show all menu DisplayAll(); private void menuitem2_click(object sender, EventArgs e)//exit menu this.close(); private void MakingPhoneCalls_Load(object sender, EventArgs e) DisplayAll(); private void menuitem5_click(object sender, EventArgs e)//call Menu Page 62 of 163

string PhoneNumber = listview1.items[listview1.selectedindices[0]].subitems[1].text; if (PhoneNumber!= "") Phone p = new Phone(); p.talk(phonenumber); Sending SMS Example 4: Create a form for sending a SMS 1. Create the form 2 textbox & one button as shown in the figure 2. Write the following code using System; using System.Linq; using System.Collections.Generic; Page 63 of 163

using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Microsoft.WindowsMobile.PocketOutlook; namespace SmartDeviceProject1 public partial class SendSMS : Form public SendSMS() InitializeComponent(); private void button1_click(object sender, EventArgs e) try SmsMessage msg = new SmsMessage(textBox1.Text, textbox2.text); msg.send(); //MessagingApplication.DisplayComposeForm(msg); MessageBox.Show("Message sent"); catch (Exception ex) MessageBox.Show(ex.Message); Page 64 of 163

Self Test 1. What POOM stands for? a. Pocket Object Oriented Model b. Pocket Object Oriented Module c. Pocket Outlook Object Module d. Pocket Outlook Object Model 2. What is PIM Stands for? a. Pocket Information b. Personal Information c. Professional Information d. Provisional Information 3. Images can be displayed ListView items without using ImageList control? a. True b. False 4. To access outlook session which dll reference need to be added? a. System.WindowsMobile.PocketOutlook.dll b. Microsoft.WindowsMobile.PocketOutlook.dll c. Microsoft.WindowsMobile.dll d. None 5. Which of the following cannot be accessed from Outlook Session? a. Contacts b. Tasks c. Notes d. Calendar Page 65 of 163

Chapter 5: Accessing Database.NET Compact Framework Data Providers Microsoft ADO.NET is a set of classes that expose data access services. ADO.NET is an evolutionary improvement to Microsoft ActiveX Data Objects (ADO). ADO.NET is an integral part of the.net Compact Framework, providing access to relational data, XML documents, and application data. ADO.NET supports a variety of development needs, including the creation of database-client applications and middle-tier business objects used by applications, tools, languages, or Internet browsers. Core elements in the ADO.NET architecture are the.net Compact Framework Data Provider for SQL Server CE (System.Data.SqlServerCe) and the.net Compact Framework Data Provider for SQL Server (System.Data.SqlClient). These data providers are used to connect to, execute commands in, and retrieve results from databases in Microsoft SQL Server 2000 Windows CE Edition (SQL Server CE) and Microsoft SQL Server, respectively. System.Data.SqlServerCe is used for programming Windows CE.NET-based applications that are semiconnected to or disconnected from SQL Server databases. System.Data.SqlClient is used for programming Windows CE.NET-based applications that have direct connections to SQL Server databases (however, these applications must have network access). An ADO.NET data provider connects to a data source such as SQL Server, Oracle, or an OLE DB data source, and provides a way to execute commands against that data source in a consistent manner that is independent of the data source and data source-specific functionality. However, aside from a core set of similar capabilities, there is no guarantee that identical functionality will be available in each data provider. This is due to differences between data sources (for example, SQL Server provides many more capabilities than Access) and provider implementations (for example, both Microsoft and Oracle offer ADO.NET providers for Oracle's data server with slight implementation differences). A complete.net data provider includes the following classes: Page 66 of 163

Connection Connects to the data source. Command Executes commands against the data source. DataReader A forward-only, read-only connected result set. ParameterCollection Stores all parameters related to a Command and the mappings of both table and column names to the DataSet columns. Parameter Defines parameters for parameterized SQL statements and stored procedures. Transaction Groups statements modifying data into work units that are either committed in their entirety or cancelled. DataAdapter Bridges the connected components to the disconnected components, allowing a DataSet and DataTable to be filled from the data source and later reconciled with the data source. SQL Server Compact - Mobile Edition The Microsoft SQL Server 2005 Mobile Edition (or, simply, SQL Server Mobile) is a lightweight database designed specifically for smart devices such as Smartphones, Pocket PCs, and Tablet PCs. Like its predecessor SQL Server CE, SQL Server Mobile is a trimmed-down version of Microsoft's desktop database. It allows faster and easier data access while disconnected, and synchronizes the data between mobile devices and desktop SQL servers while connected. Microsoft SQL Server Compact (SQL CE) is a compact relational database produced by Microsoft for applications that run on mobile devices and desktops. Page 67 of 163

SQL Server Compact shares a common API with the other Microsoft SQL Server editions. It also includes ADO.NET providers for data access using ADO.NET APIs, and built-in synchronization capabilities, as well as support for LINQ and Entity Framework. Future releases will unify the synchronization capabilities with Microsoft Synchronization Services. Unlike other editions of Microsoft SQL Server, SQL CE runs in-process with the application which is hosting it; while having a memory footprint of less than 2 MB; however, all SQL CE instances share the same memory pool. SQL CE supports transactions, referential integrity constraints, locking as well as multiple connections to the database store, The current release does not support stored procedure or native XML data type either. It uses a subset of T-SQL for querying and due to lack of XML support, XQuery is not supported either. Queries are processed by an optimizing query processor. SQL CE databases also support indexing, as well as support remote data replication (local caching of data in remote databases) and merge replication (bidirectional synchronization with master databases). SQL CE databases can be created and managed from Microsoft Visual Studio and SQL Server Management Studio as well. SQL CE databases reside in a single.sdf file, which can be up to 4 GB in size. The.sdf file can be encrypted with 128-bit encryption for data security.[10] SQL CE runtime mediates concurrent multi-user access to the.sdf file. The.sdf file can simply be copied to the destination system for deployment, or be deployed through ClickOnce. SQL CE runtime has support for DataDirectories. Applications using an SQL CE database need not specify the entire path to an.sdf file in the ADO.NET connection string, rather it can be specified as DataDirectory \<database_name>.sdf, defining the data directory (where the.sdf database file resides) being defined in the assembly manifest for the application. SQL Server Management Studio 2005 can read and modify CE 3.0 and 3.1 database files (with the latest service pack), but SQL Server Management Studio 2008 (or later) is required to read version 3.5 files. Microsoft Visual Studio Express 2008 SP1 can create, modify and query CE 3.5 SP1 database files. Setting a password for the database file is optional. Page 68 of 163

Setting up a Project Before an application can work with ADO.NET, you must configure your projects to reference the.net Compact Framework data providers that you plan to use. To create a reference to the.net Compact Framework data provider 1. In an open Microsoft Visual Studio.NET project, on the Project menu, click Add References. 2. On the.net tab, select either System.Data.SqlServerCe for SQL Server CE or System.Data.SqlClient for SQL Server version 7.0 or later. 3. Note In some cases, you may need to reference System.Data.Common if your application uses DataAdapter or CommandBuilder classes. 4. Click Select, and then click OK. Creating a Database and Tables using Visual Studio 1. Go to Project menu new item 2. Select Data Category select Database file enter file name Add 3. Right click the database file in the solution explorer, select open Page 69 of 163

4. Database open in the server explorer expand the database right click on the Tables create table 5. Using New Table now you can create the table. Add the columns, mention the table name click OK Page 70 of 163

6. For Inserting/ Updating rows directly in the table right click the table show data Page 71 of 163

Displaying data from table into a data grid Example 1: Write a program to display the user table into data grid 1. Create a form & add a datagrid to it 2. Add reference to SqlServerCe class library, import the namespace System.Data.SqlServerCe 3. Write the below code using System; using System.Linq; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlServerCe; using System.Drawing; using System.Text; using System.Windows.Forms; namespace PocketPC_Example_CS Page 72 of 163

public partial class UserListForm : Form public UserListForm() InitializeComponent(); private void UserListForm_Load(object sender, EventArgs e) SqlCeConnection con = new SqlCeConnection("Data Source =" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().G etname().codebase) + "\\db.sdf;")); SqlCeDataAdapter da= new SqlCeDataAdapter("select * from users",con); DataSet ds=new DataSet(); con.open(); da.fill(ds,"users"); con.close(); datagrid1.datasource=ds.tables[0]; Inserting the Data in the table Example 2: Create a form to insert user details in the table Page 73 of 163

1. Create a form add controls as shown in the figure 2. Add the reference to SqlServerCe dll 3. Import the namespace System.Data.SqlServerCe 4. Write the below code using System; using System.Linq; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlServerCe; using System.Drawing; using System.Text; using System.Windows.Forms; namespace PocketPC_Example_CS public partial class UserForm : Form public UserForm() InitializeComponent(); Page 74 of 163

private void btnsave_click(object sender, EventArgs e) SqlCeConnection con = new SqlCeConnection("Data Source =" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().G etname().codebase) + "\\db.sdf;")); SqlCeCommand cmd = new SqlCeCommand("Insert into Users(username,password,isactive) values(@username,@password,@isactive)", con); cmd.parameters.addwithvalue("@username",usernametextbox.text); cmd.parameters.addwithvalue("@password", passwordtextbox.text); cmd.parameters.addwithvalue("@isactive", isactivecheckbox.checked); con.open(); cmd.executenonquery(); con.close(); MessageBox.Show("Record saved"); SQL Server CE Query Analyzer SQL Server CE Query Analyzer is a graphical tool included in Microsoft SQL Server 2000 Windows CE Edition (SQL Server CE) that you can use to: Create databases. Manage and connect to other databases on a device. Verify remote data access (RDA) and replication applications. Create and modify tables and indexes in a database. Query objects by using the SELECT statement. Insert and delete rows in a table. Modify existing data in a table. Compact and repair a database. Page 75 of 163

SQL Server Compact Edition Query Analyzer is a small application that can run directly on a Windows Mobile PDA and allows you to create and manipulate SQL Server Compact Edition databases. It is a handy tool to add to your toolbox, as it can help diagnose and correct small database errors while you are away from your development PC. First a word of warning Query Analyzer is prehaps the worst application with respect to conforming to the Designed For WIndows Mobile logo certification requirements. The application is not supported on Windows Mobile Standard (smartphone) devices, and many dialogs are unusable on small or square resolution Windows Mobile Professional (PocketPC) devices. The application appears to be more at home on devices running the standard Windows CE shell as evidenced by its heavy reliance on non fullscreen dialogs. Installing Query Analyzer If your.net Compact Framework based application makes reference to the System.Data.SqlServerCe assembly Visual Studio will automatically install the query analyser tool when you deploy your project via the IDE. If you are a native developer or want to utilise the tool without deploying via Visual Studio you will need to manually install the Query Analyzer tool which is part of SQL Server Compact Edition s developer support cab file. The SQL Server Compact Edition Books Online documentation has a How to: Install Query Analyzer (SQL Server Compact Edition) section that covers this process. Page 76 of 163

Essentially you need to install the following CAB files on your device:.net Compact Framework NETCFversion.platform.processor.cab SSCE runtime sqlce30.platform.processor.cab SSCE dev tools sqlce30.dev.enu.platform.processor.cab You should be able to find the required CAB files within the %programs%\microsoft Visual Studio 8\SmartDevices\SDK\SQL Server\Mobile\v3.0\platform\processor\ folder. One tricky bit is the fact that references to platform and processor in file and directory names above need to be replaced with values specific to the version of Windows Mobile your target device is utilising. In most cases you can use wce500\armv4i\sqlce30.ppc.wce5.armv4i.cab and wce500\armv4i\sqlce30.dev.enu.ppc.wce5.armv4i.cab for Windows Mobile 5 Pocket PC or higher devices. Further instructions can be found in the How to: Install SQL Server Compact Edition on a Device article available on MSDN. One tip to correctly determine the correct CAB files to install is to hard reset a PDA and have Visual Studio deploy your project to the PDA. After the deployment you should be able to refer to the output window to see which CAB files Visual Studio deployed and installed to configure SQL Server Compact Edition. Opening a database After installing the SQL Server Compact Edition developer tools CAB file you should be able to find a new Query Analyzer application within the start menu of your Windows Mobile device. The initial window that appears after this application is started should show a series of tabs with the one labelled Objects selected. This tab is similiar to the Object Explorer of SQL Server 2005 Management Studio on the desktop and shows each database you have connected to in the past and the database objects contained within them. Page 77 of 163

To open a connection to an existing database you need to click the toolbar button at the bottom of the screen. This will display the following Connect to SQL Server Compact Edition Database dialog. You need to enter the full path to your database (i.e. \Program Files\MyApplication\test.sdf) and a password if the database is password protected. Selecting the [...] button will display a file open dialog that allows you to graphically select a database file. This dialog unfortunately is restricted to database files located within the My Documents folder structure. If your database is not located within this hierarchy you will have to manually type it in. Once the database connection details have been entered you can select the Connect button. This will return the user to the main Query Analyzer window with the specified database added to the tree view. When you have completed your tasks with the database you should select the database within the treeview and select the toolbar button to disconnect from the database. If you do not do this it may not be possible for other applications to access the database due to Query Analyzer having a lock on the database file. Creating a database A new database can also be created directly on the PDA. To do this you follow the same process to open an existing database. However when the Connect to SQL Server Compact Edition database dialog appears you select the New Database button which will expand the connection window to include a couple of additional fields. Page 78 of 163

The details you can enter via this dialog include: Path The full path to where the *.sdf database file should be created. Password An optional password that must be provided whenever an attempt is made to connect to the new database. Sort The sort order applied to indexes on tables within the database. Encrypt If encryption is enabled data within the database file will be encrypted. Enabling this feature will make a password mandatory since the password is the key used to decrypt the database. After the new database has been configured clicking the Create button will return the user to the main Query Analyzer window with the newly created database added to the treeview. Creating Tables There are two ways to create a table within Query Analyzer. The first is to select the toolbar button while the Tables node of a database is selected. This will bring up the following Table Definition dialog that enables the user to specify a table name and define the columns within the table. These dialogs in particular are difficult to utilise on devices with small square screens. Page 79 of 163

An alternative to the GUI dialogs is to switch to the SQL tab of the main Query Analyzer window and enter a T-SQL data definition language (DDL) statement to create the table programatically, as shown in the screenshot below: Once you have entered the CREATE TABLE statement you can select the toolbar button to execute the query. Query Analyzer will automatically switch to the Notes tab and inform you of the duration and outcome of the operation. Self Test 1. Which of the following are not core elements in ADO.NET for.net Compact Framework? a. Data Provider for SQL Server CE b. Data Provider for SQL Server Page 80 of 163

c. Data Provider for Oracle d. All 2. Which of the following gives connect data source? a. DataAdapter b. DataReader c. Command d. None 3. SQL Server CE is does not provide a relational database? a. True b. False 4. Which version of SQL Server CE does n t support LINQ? a. SQL Server CE 2.0 b. SQL Server CE 3.5 c. SQL Server CE 3.0 d. SQL Server CE 3.1 5. SQL Server CE supports XML? a. True b. False 6. What is the extension of the SQL Server CE database? a..ldf b..mdf c..sdf d..mdb 7. Can SQL Server Management Studio be used to open SQL Server CE database? a. Yes b. No 8. To connect to SQL Server CE database which namespace is used for data providers? a. System.Data.SqlClient b. System.Data.SqlCe c. System.Data.SqlServerCe d. System.Data.SqlClientCe Page 81 of 163

9. Which tool can be used to open SQL Server CE database on the device? a. Query Analyzer b. Management Studio c. SQL Lite d. No such tool available 10. SQL Server CE Query Analyzer doesn t support graphical interface for creating table? a. True b. False Page 82 of 163

Chapter 6: Using LINQ What is LINQ? Language-Integrated Query (LINQ) adds general-purpose query facilities to the.net Compact Framework that apply to various sources of information such as relational databases, XML data, and in-memory objects. These features enable the.net Compact Framework to query on different sources of information without adding relational or XML-specific features to the programming language. LINQ is supported in the.net Compact Framework version 3.5 and later. LINQ defines a set of general-purpose standard query operators that enable you to perform language-integrated query, set, and transform operations on internal or external data. The standard query operators let you apply queries to any IEnumerable<T>-based information source. LINQ in the.net Compact Framework includes a subset of the desktop LINQ features. The differences between LINQ in the.net Framework and LINQ in the.net Compact Framework are as follows: On the.net Compact Framework, only standard query operators are supported. LINQ to DataSet is supported, which provides LINQ support for DataSet and DataTable. On the.net Compact Framework, LINQ to XML is supported except for XPath extensions. On the.net Compact Framework, VB query syntax for LINQ to DataSet does not support the Select Clause (Visual Basic) clause where the operator is optional. That is, if the Select clause does not include parameters that change the default result of the query, you must remove the Select clause. Page 83 of 163

LINQ Architecture on.netcf Example 1: Create a program to query on the string array having cities names and display cities with string length 6 in upper case in the ListBox 1. Create a form with a button (run) & ListBox as shown in the figure 2. Write the below code & run the program Page 84 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; namespace PocketPC_Example_CS public partial class LINQExample : Form public LINQExample() InitializeComponent(); private void button1_click(object sender, EventArgs e) string[] cities = "Delhi","Mumbai", "Pune","Nagpur", "Chennai", "Bangalore","Jaipur"; var query = from c in cities where c.length == 6 orderby c select c.toupper(); foreach (string city in query) listbox1.items.add(city); Example 2: Create form which displays and searches countries' information in a grid. For an illustration of how to work with LINQ and Dataset, the application will Page 85 of 163

retrieve data from the SQL Server Compact Edition file demo.sdf. The application uses Typed Data Adapter as the Data Access Layer and DataTable as the data type. LINQ to DataSet In the code below, data retrieved from a database and filling in the Countries DataTable. After that, just for illustration, I am using LINQ to sort and display the data in a grid through the BindingSource object. ///Loading data from demo.sdf to Countries table private void LoadData() ///Get Data Countries = dal.getdata(); ///Building LINQ Query var query = from r in Countries.AsEnumerable() orderby r.field<string>("name") ascending select new Code = r.field<string>("code"), Name = r.field<string>("name") ; ///Binding data bindingsource1.datasource = query; In the code below, LINQ used to search data in DataTable. ///Building LINQ Query var query = from r in Countries.AsEnumerable() where r.field<string>("name").tolower().contains(txtsearch.text.tolower()) orderby r.field<string>("name") ascending Page 86 of 163

select new Code = r.field<string>("code"), Name = r.field<string>("name") ; ///Binding data bindingsource1.datasource = query; Complete code as follows 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; namespace PocketPC_Example_CS public partial class LinqtoDataSet : Form dbdataset.countriesdatatable Countries = new dbdataset.countriesdatatable(); dbdatasettableadapters.countriestableadapter dal = new dbdatasettableadapters.countriestableadapter(); public LinqtoDataSet() InitializeComponent(); private void LoadData() ///Get Data Countries = dal.getdata(); ///Building Linq Query var query = from r in Countries.AsEnumerable() orderby r.field<string>("country") ascending select new Code = r.field<string>("code"), Country = r.field<string>("country") ; Page 87 of 163

///Binding data bindingsource1.datasource = query; private void btnsearch_click(object sender, EventArgs e) ///Building LINQ Query var query = from r in Countries.AsEnumerable() where r.field<string>("country").tolower().contains(txtsearch.text.tolower()) orderby r.field<string>("country") ascending select new Code = r.field<string>("code"), Country = r.field<string>("country") ; ///Binding data bindingsource1.datasource = query; private void LinqtoDataSet_Load(object sender, EventArgs e) LoadData(); Page 88 of 163

Self Test 1. What LINQ stands for? a. Language Integrated Query b. Language Interoperation Query c. Language Independent Query d. Language Independent Native Query 2. Which of the following not supported by LINQ in Compact Framework? a. LINQ to Objects b. LINQ to DataSet c. LINQ to SQL d. LINQ to Entities e. LINQ to XML 3. In VB which of the following clause is not supported by LINQ for Compact Framework? a. Select b. Where c. From d. OrderBy 4. LINQ to DataTable is supported in Compact Framework? a. True b. False 5. Which of the following is not correct about LINQ a. LINQ defines a set of general-purpose standard query operators that enable you to perform language-integrated query b. LINQ is supported in the.net Compact Framework version 3.5 and later. c. Includes a subset of the desktop LINQ features. d. LINQ to XML is supported e. All f. None Page 89 of 163

Chapter 7: Working with Bluetooth Bluetooth Bluetooth is a wireless communication technology that allows devices, within a 10- meter proximity, to communicate with each other. The discovery process enables devices to query other devices about the services they offer. If a device offers more than one service, the user can select the service they want to use from that particular device. This technology enables devices to communicate without physical cables. Wireless headsets, modems, and printers are prime examples of devices using Bluetooth technology. The range varies depending on the signal strength of the device. Bluetooth has adopted a common data and object specification that enables devices to communicate over a wireless connection in a standard way. This allows applications to use typical interfaces when exchanging data, business cards, and calendar entries. The Bluetooth stack implementation is modular. It is a general-purpose software stack, and is linked by default, or modularized to meet specific usage scenarios and OEM needs. In Windows Embedded CE, the primary way an application can use Bluetooth is through the Winsock interface, which exposes RFCOMM protocol. Virtual COM ports are also exposed, but this interface is designed to be enabled under existing OS services such as UNIMODEM or terminal emulators. By using various protocols and profiles, Bluetooth can be implemented to perform the following tasks: Connect to a modem through a cellular phone. Connect to a local area network (LAN) access point. Enable object exchange and synchronization using the Object Exchange Protocol (OBEX). Unlike Infrared, there is no built-in support for Bluetooth transmission in the.net Compact Framework. Bluetooth, however, supports the serial port profile, which allows the data to be exchanged over serial communications. Fortunately, the latest version of the.net Compact Framework provides the SerialPort class in the Page 90 of 163

System.IO.Ports namespace, which allows you to easily do this. Let's take a look at what is needed in the server-side code for Bluetooth communications. using System.Diagnostics; using System; using System.Data; using System.IO; using System.IO.Ports; namespace CRMLive public class BluetoothService public delegate void DataReceiveEndedEventHandler(); private byte[] _ReceivedData; private SerialPort _port; private DataReceiveEndedEventHandler DataReceiveEndedEvent; public event DataReceiveEndedEventHandler DataReceiveEnded add DataReceiveEndedEvent = (DataReceiveEndedEventHandler) System.Delegate.Combine(DataReceiveEndedEvent, value); remove DataReceiveEndedEvent = (DataReceiveEndedEventHandler) System.Delegate.Remove(DataReceiveEndedEvent, value); At the server side, we only need to create a new SerialPort object and assign an event handler for the DataReceived event. Whenever data is received through the port, your event handler is called. public void StartServer() _port = new SerialPort(); Page 91 of 163

_port.datareceived += new SerialDataReceivedEventHandler(DataReceived); private void DataReceived(object sender, SerialDataReceivedEventArgs e) int _counter; int _bytesread; byte[] Buffer = new byte[1048577]; _bytesread = 0; try _counter = 0; do _bytesread = _port.read(buffer, _counter, 8192); _counter += _bytesread; while (!(_bytesread == 0)); catch (Exception ex) throw (ex); _ReceivedData = Buffer; if (DataReceiveEndedEvent!= null) DataReceiveEndedEvent(); public byte[] GetReceivedData() return _ReceivedData; On the client side, you can just as easily send data to the server. You must first create a SerialPort object, set up its connection parameters, and then use the Write() function to write binary data to the port. public bool SendData(byte[] Data) try Page 92 of 163

_port = new SerialPort(); _port.portname = "COM1"; _port.baudrate = 9600; _port.parity = Parity.None; _port.databits = 8; _port.stopbits = StopBits.One; _port.open(); _port.write(data, 0, Data.Length); _port.close(); catch (Exception ex) throw (ex); To use this class, you could call the following code on the client side: BluetoothService client = new BluetoothService(); client.senddata(generic.serializedataset(mydataset)); As for the server side, you can use the following code. Once the dataset is received, the DataReceiveEnded event is raised. You can then obtain the received byte array using the GetReceivedData() function. BluetoothService server = new BluetoothService(); server.startserver(); As the preceding code allows you to transfer binary data across devices, you can reuse the same code to send any type of object (including files) with a little extra work. 32feet.NET Library 32feet.NET is project to make personal area networking technologies such as Bluetooth, Infrared (IrDA) and more, easily accessible from.net code. Supports desktop, mobile or embedded systems. The project currently consists of the following libraries:- Page 93 of 163

Bluetooth IrDA ObjectExchange Bluetooth support requires a device with the Microsoft Bluetooth stack. Requires.NET Compact Framework v1.0 or above and Windows CE.NET 4.2 or above, or.net Framework v1.1 for desktop Windows XP. In the next example we will be using the third party library InTheHand.dll can be downloaded from inthehand.net website, this library provides lot of functionality for interacting with Bluetooth devices Example 1: Creating a program for power on/off the Bluetooth and finding the current status using InTheHand library. 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 InTheHand.Net; using InTheHand.Net.Sockets; using InTheHand.Net.Bluetooth; Page 94 of 163

namespace PocketPC_Example_CS public partial class BlueToothExample : Form public BlueToothExample() InitializeComponent(); private void btnpoweroff_click(object sender, EventArgs e) BluetoothRadio br = BluetoothRadio.PrimaryRadio; br.mode = RadioMode.PowerOff; private void btndiscoverable_click(object sender, EventArgs e) BluetoothRadio br = BluetoothRadio.PrimaryRadio; br.mode = RadioMode.Discoverable; private void btnconnectable_click(object sender, EventArgs e) BluetoothRadio br = BluetoothRadio.PrimaryRadio; br.mode = RadioMode.Connectable; private void btnstatus_click(object sender, EventArgs e) BluetoothRadio br = BluetoothRadio.PrimaryRadio; if (br!= null) if (br.mode == RadioMode.Connectable) MessageBox.Show("Connectable"); else if (br.mode == RadioMode.Discoverable) MessageBox.Show("Dicoverable"); else if (br.mode == RadioMode.PowerOff) Page 95 of 163

MessageBox.Show("Power Off"); else MessageBox.Show("Error"); Example 2: Creating a program for searching the all Bluetooth devices using System; using System.Drawing; using System.Collections; using System.Windows.Forms; using System.Data; using InTheHand.Net; using InTheHand.Net.Sockets; using InTheHand.Net.Bluetooth; namespace PocketPC_Example_CS public partial class BlueToothExample2 : Form Page 96 of 163

private Guid service = InTheHand.Net.Bluetooth.BluetoothService.DialupNetworking; private BluetoothClient bluetoothclient; public BlueToothExample2() InitializeComponent(); private void button2_click(object sender, EventArgs e) if (listbox1.selectedvalue!= null) try bluetoothclient.connect(new BluetoothEndPoint((BluetoothAddress)listBox1.SelectedValue, service)); MessageBox.Show("Connected"); catch (Exception ex) MessageBox.Show(ex.Message); private void button1_click(object sender, EventArgs e) BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable; bluetoothclient = new BluetoothClient(); Cursor.Current = Cursors.WaitCursor; BluetoothDeviceInfo[] bluetoothdeviceinfo = ; bluetoothdeviceinfo = bluetoothclient.discoverdevices(10); listbox1.datasource = bluetoothdeviceinfo; listbox1.displaymember = "DeviceName"; listbox1.valuemember = "DeviceAddress"; listbox1.focus(); Cursor.Current = Cursors.Default; Page 97 of 163

Self Test 1. What is the range of Bluetooth network approximately? a. 20 m b. 10m c. 15 m d. 1 km 2. Range of Bluetooth network varies depending upon? a. Signal strength b. Firewalls c. Battery d. Interference 3. Which of the following is cannot be used for wireless communication? a. Infrared b. Bluetooth c. Wifi d. GPRS/3G e. All f. None 4. Infrared supports serial communication? a. True b. False 5. Which of the following cannot be implemented using Bluetooth? a. Connect to a GPRS b. Connect to a local area network c. Enable object exchange and synchronization d. Connect to WiFi Page 98 of 163

Chapter 8: Accessing Web Services & WCF Services Introduction A primary feature of the Microsoft.NET Compact Framework is its ability to consume Web services. The.NET Compact Framework supports the use of Web services in two distinct ways: synchronously and asynchronously. Both have their advantages and disadvantages. Synchronous Web service calls are simple to code while asynchronous calls require some slightly more complex coding. Synchronous calls will cause the application to freeze if the Web service is unresponsive for a long period, whereas asynchronous calls allow the user to interact with the application while the call to the Web service is ongoing. When consuming Web services from a Smart Device project you will experience an initial delay of a few seconds. If you make asynchronous calls, this delay does not have to freeze your application's user interface. This delay occurs when the.net Compact Framework runtime is setting up the connection details for the Web service, and caching the details. This can often cause your application to appear unresponsive. Subsequent calls to the Web service will show greatly improved performance. This article demonstrates how to add a Web Reference to a Web service to your Smart Device projects, and how to call the Web service both synchronously and asynchronously. This article assumes that you have a working knowledge of creating Smart Device applications with Microsoft Visual Studio.NET 2003. Consuming a Web Service To consume a Web service in a Smart Device project, you need to add a Web Reference to your project. A Web reference enables a project to consume a Web service. When you add a Web Reference to your project, Visual Studio.NET automatically generates a proxy class with methods that serve as proxies for each exposed method of the Web service. The proxy class is hidden from view in the Solution Explorer by default. Your application uses an automatically generated class to access Web services, and not one you would modify with your own code. Page 99 of 163

To add a Web Reference to a project: 1. In Solution Explorer, select the project that will consume the Web service. 2. On the Project menu, select Add Web Reference. 3. Enter the URL for the Web service you wish to consume and click the Go button. The Add Web Reference dialog box 1. In the Web reference name field, enter a name that you will use in your code to access the selected Web service programmatically. 2. Click the Add Reference button to create a reference to the Web service in your application. The new reference will appear in the Solution Explorer under the Web References node for the selected project. The proxy class that Visual Studio.NET generates when you add a Web Reference also includes methods for accessing the Web Service synchronously or asynchronously. We will now look at how you do this. Making Synchronous Web service Calls When making synchronous calls to Web services, the calling thread is blocked until the Web service returns the result of the method call. Synchronous calls are useful if the method you are calling on the server does not require much processing time and will return quickly. In addition, synchronous Web service calls are simpler to implement than their asynchronous counter-part. However, you will notice a significant delay in calling Web services from a.net Compact Framework application, which cause your application to lock and your user interface to freeze until the method call has returned. To make a synchronous call to a Web service, you create an instance of the proxy class and then call the methods within the proxy class as you would with any other class. The code sample below shows you how to make a synchronous call to a Web method of a Web service that returns information about the books in the pubs example database shipped with SQL Server. The code then walks through the DataSet to load the data into a ListView control on a Windows Form. This example assumes that when you added a Web Reference, (as explained in the first part of this paper) you named the Web reference BookCatalog. The Page 100 of 163

BookCatalog Web service has the GetItems Web method, which returns a DataSet object. The code is taken from the button1_click() event handler in the download that accompanies this article. // ---- Call the Web service ---- // Create an instance of Web Service proxy class BookCatalog.Service1 bookcatalog = new BookCatalog.Service1(); // Create a new instance of a DataSet object and call the Web Service // method, GetItems, to retrieve the list of books DataSet ds = bookcatalog.getitems(); // ------------------------------ // ---- Process the DataSet ---- // Loop through the DataSet and add each row's Title_ID and Title // field to the ListView foreach(datarow drbook in ds.tables[0].rows) // Create a new ListViewItem to add to the ListView ListViewItem book = new ListViewItem(); // Assign the Title_ID field to the Text property book.text = drbook["title_id"].tostring(); // Assign the Title field to the first SubItem book.subitem[0].text = drbook["title"].tostring(); // Add the book ListViewItem to the ListView listview1.items.add(book); Making Asynchronous Web Service Calls By making an asynchronous call to a Web service, you can continue to use the calling thread while you wait for the Web service to respond. This means users can continue to interact with your application without it locking up while the Web service access proceeds. This is a better design pattern and a more effective use of threads within the Smart Device application by making use of the multithreading support. When making asynchronous calls, the call is made on a different thread to the one that is running the user interface. The Web services application does not require any special configuration to support asynchronous access nor do they need to know whether you are calling it synchronously or asynchronously. For every synchronous method in the proxy class, there is a corresponding Begin and End Page 101 of 163

method. For example, if the name of the Web service method is GetItems, the asynchronous methods are BeginGetItems and EndGetItems. Calling Web services asynchronously is a two-step operation. Firstly, call the Begin method to initiate the call to the Web method. Secondly, call the End method to complete the Web service call and retrieve the response from the Web service. The Begin method returns a System.Web.Services.Protocol.WebClientAsyncResult object, which implements the System.IAsyncResult interface. This object provides status information about the pending asynchronous call. By passing this object to the End method, the proxy class can identify which request you would like to complete, especially when making multiple asynchronous calls simultaneously. There are several ways to determine when the asynchronous Web service call has completed: Pass a callback delegate to the Begin method. The callback delegate executes when the Web service call completes. Force the application to wait using one of the WaitHandle methods of the IAsyncResult.AsyncWaitHandle object. When using the methods of the WaitHandle class, the client can also specify a timeout after which it will abandon waiting for results from the Web services it called. Poll the value of the IAsyncResult.IsCompleted property in your main thread code for a value of true. When this property is true, call the End method to retrieve the response from the Web service. Call the End method directly without using one of the other techniques for determining if the asynchronous Web service call has completed. This method will block execution of the calling thread until the asynchronous call is complete. The most efficient method is passing a callback delegate to the Begin method, as callback functions do not block threads while waiting for a response. When the Web service returns its response, the callback delegate executes in a new thread. You then call the End method inside the callback. The code below shows you how to create an asynchronous Web service call; the code shows a call to BeginGetItems, which has the following syntax: Page 102 of 163

BeginGetItems(System.AsyncCallback callback, object asyncstate); BeginGetItems takes two parameters, the first of which is an AsyncCallback object, which is created by passing the address of the ServiceCallback method in its constructor. The second parameter is of type object; you can pass any object that will assist you in handling the response from the Web service. You access this same object by getting the AsyncState property of the IAsyncResult parameter to your callback method. In the example below, the object that is passed in this way is the Web service proxy object so that when the callback delegate executes, a call to EndGetItems can be made, as shown in the ServiceCallback method below. private void button2_click(object sender, System.EventArgs e) // Disable the Async button and clear the ListView of any data // Create an instance of Web service proxy class BookCatalog.Service1 ws = new BookCatalog.Service1(); // Create a reference to the callback delegate AsyncCallback cb = new AsyncCallback(ServiceCallback); // Call the Begin method, passing the callback delegate and // this proxy class instance as the AsyncState object. ws.begingetitems(cb,ws); private void ServiceCallback(IAsyncResult ar) // Cast the AsyncState object to the proxy object BookCatalog.Service1 ws = (BookCatalog.Service1)ar.AsyncState; // Call the End method and assign the response to a DataSet DataSet ds = ws.endgetitems(ar); // Loop through the DataSet and add each row's Title_ID and Title // field to the ListView foreach(datarow drbook in ds.tables[0].rows) // Create a new ListViewItem to add to the ListView ListViewItem book = new ListViewItem(); // Assign the Title_ID field to the Text property book.text = drbook["title_id"].tostring(); // Assign the Title field to the first SubItem Page 103 of 163

book.subitem[0].text = drbook["title"].tostring(); // Add the book ListViewItem to the ListView listview1.items.add(book); Making asynchronous Web service calls requires a little more code than making synchronous calls, but the end result, a more responsive application, is certainly worth the effort. Important Use multithreaded programming techniques when calling Web services asynchronously If you do not use multithreaded techniques when making asynchronous Web service calls, you will encounter problems when two or more threads try to access the same data at the same time. One such technique, shown in the code below, is to use the lock statement in C# to acquire mutually exclusive access to an object, such that any other threads are denied access. private void ServiceCallback(IAsyncResult ar) // Cast the AsyncState object to the proxy object BookCatalog.Service1 ws = (BookCatalog.Service1)ar.AsyncState; // Call the End method and assign the response to a DataSet DataSet ds = ws.endgetitems(ar); // Use the lock statement to prevent other threads from accessing // the listview until you have finished updating it lock(this.listview1) // Loop through the DataSet and add each row's Title_ID and // Title field to the ListView foreach(datarow drbook in ds.tables[0].rows) // Create a new ListViewItem to add to the ListView ListViewItem book = new ListViewItem(); // Assign the Title_ID field to the Text property book.text = drbook["title_id"].tostring(); // Assign the Title field to the first SubItem book.subitem[0].text = drbook["title"].tostring(); // Add the book ListViewItem to the ListView listview1.items.add(book); Page 104 of 163

Consuming web service Next example we will see how to consume web service, for the sake of example we will create a test web service and we will call it in our program Create a ASP.NET website in the solution, add a new item web service with InfoService, to web service class add web method GetCountryCode() [WebMethod] public string GetCountryCode(string Country) switch (Country) case "India": return "+91"; break; case "Afgansthan": return "+98"; break; case "Albania": return "+355"; break; case "Bhutan": return "+975"; break; case "Combodia": return "+855"; break; case "Faroe Island": return "+298"; break; default: return "not found"; break; Page 105 of 163

Create a Window Form for PocketPC/Smartphone project, add the reference to the above web service by right clicking the project Add Web Reference. Type url of the web service if service located on remote place or if it is inside the same solution click the option web service in the solution as shown below Page 106 of 163

Instead of localhost you can use IP 192.168.0.2 in the url if you are testing with local service. Enter the web service reference name, click add reference. For network or internet access using desktop, you have connect using device emulator manager (C:\Program Files\Microsoft Device Emulator\1.0\dvcemumanager.exe) and ActiveSync/Window Mobile Device Center. Open the device emulator manager right click your device select cradle, connect the device using active sync or windows mobile device center. Now we will call service in the program, so we will make a form with a textbox for entering country name and a button for calling the service as shown in the figure Page 107 of 163

Complete Code as follows InfoService WebService Class using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace MobileSite /// <summary> /// Summary description for InfoService /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class InfoService : System.Web.Services.WebService [WebMethod] public string GetCountryCode(string Country) switch (Country) case "India": return "+91"; break; case "Afgansthan": return "+98"; break; case "Albania": return "+355"; break; case "Bhutan": return "+975"; break; case "Combodia": return "+855"; Page 108 of 163

break; case "Faroe Island": return "+298"; break; default: return "not found"; break; Web Service Test Form 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; namespace PocketPC_Example_CS public partial class WebServiceTest : Form public WebServiceTest() InitializeComponent(); private void btnget_click(object sender, EventArgs e) InfoServices.InfoService service = new InfoServices.InfoService(); MessageBox.Show(service.GetCountryCode(textBox1.Text)); Page 109 of 163

Window Communication Foundation WCF Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying networkdistributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in.net Framework 3.0. WCF is a combined features of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all.net communication. Below figures shows the different technology combined to form WCF. Advantage 1. WCF is interoperable with other services when compared to.net Remoting, where the client and service have to be.net. 2. WCF services provide better reliability and security in compared to ASMX web services. 3. In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements. Page 110 of 163

4. WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code. Disadvantage Making right design for your requirement is little bit difficult. I will try to help you on solving these difficulties in the following article. Difference between WCF and Web service Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service, following table provides detailed difference between them. Features Web Service WCF Hosting It can be hosted in IIS It can be hosted in IIS, windows activation service, Self-hosting, Windows service Programming [WebService] attribute has to be added to the class [ServiceContraact] attribute has to be added to the class Model Operation XML Encoding [WebMethod] attribute [OperationContract] attribute represents the method exposed represents the method exposed to to client client One-way, Request- Response are the different operations supported in web service System.Xml.serialization name space is used for serialization One-Way, Request-Response, Duplex are different type of operations supported in WCF System.Runtime.Serialization namespace is used for serialization XML 1.0, MTOM(Message Transmission Optimization XML 1.0, MTOM, Binary, Custom Mechanism), DIME, Custom Page 111 of 163

Transports Can be accessed through HTTP, TCP, Custom Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom Protocols Security Security, Reliable messaging, Transactions WCF Architecture The following figure illustrates the major components of WCF. Figure 1: WCF Architecture Contracts Contracts layer are next to that of Application layer. Developer will directly use this contract to develop the service. We are also going to do the same now. Let us see briefly what these contracts will do for us and we will also know that WCF is working on message system. Page 112 of 163

Service contracts Describe about the operation that service can provide. Example, Service provided to know the temperature of the city based on the zip code, this service we call as Service contract. It will be created using Service and Operational Contract attribute. Data contract It describes the custom data type which is exposed to the client. This defines the data types, are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or datatype cannot be identified by the client e.g. Employee data type. By using DataContract we can make client aware that we are using Employee data type for returning or passing parameter to the method. Message Contract Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute. Policies and Binding Specify conditions required to communicate with a service e.g security requirement to communicate with service, protocol and encoding used for binding. Service Runtime It contains the behaviors that occur during runtime of service. Throttling Behavior- Controls how many messages are processed. Error Behavior - Specifies what occurs, when internal error occurs on the service. Metadata Behavior - Tells how and whether metadata is available to outside world. Instance Behavior - Specifies how many instance of the service has to be created while running. Transaction Behavior - Enables the rollback of transacted operations if a failure occurs. Dispatch Behavior - Controls how a message is processed by the WCF Infrastructure. Page 113 of 163

Messaging Messaging layer is composed of channels. A channel is a component that processes a message in some way, for example, by authenticating a message. A set of channels is also known as a channel stack. Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as Transport Channels Handles sending and receiving message from network. Protocols like HTTP, TCP, name pipes and MSMQ. Protocol Channels Implements SOAP based protocol by processing and possibly modifying message. E.g. WS-Security and WS-Reliability. Activation and Hosting Services can be hosted or executed, so that it will be available to everyone accessing from the client. WCF service can be hosted by following mechanism IIS Internet information Service provides number of advantages if a Service uses Http as protocol. It does not require Host code to activate the service, it automatically activates service code. Windows Activation Service (WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide messagebased activation over other protocols, such as TCP and named pipes. Self-Hosting WCF service can be self hosted as console application, Win Forms or WPF application with graphical UI. Windows Service WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM). Page 114 of 163

Consuming the WCF Service Now we will create a WCF Service and will call this service in the Smart Device Application. Create a website & add WCF Service from add new item name it as ConversionService.svc Now we will add a contract ConvertByteToKB which will convert Byte into Kilo Bytes, so declare the method in the interface as follows using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace MobileSite // NOTE: If you change the interface name "IConversionService" here, you must also update the reference to "IConversionService" in Web.config. [ServiceContract] public interface IConversionService Page 115 of 163

[OperationContract] int ConvertByteToKB(int ByteValue); Now will define the Contract method in the service class i.e ConversionService class using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace MobileSite // NOTE: If you change the class name "ConversionService" here, you must also update the reference to "ConversionService" in Web.config. public class ConversionService : IConversionService public int ConvertByteToKB(int ByteValue) return ByteValue / 1024; Now add the reference to the WCF Service by right clicking the project in the solution explorer and select add Service reference, it s similar to adding the web reference. Type the url of the service in the address bar. Page 116 of 163

Instead of localhost you can use IP 192.168.0.2 in the url if you are testing with local service. Enter the service reference name, click add reference. For network or internet access using desktop, you have connect using device emulator manager (C:\Program Files\Microsoft Device Emulator\1.0\dvcemumanager.exe) and ActiveSync/Window Mobile Device Center. Open the device emulator manager right click your device select cradle, connect the device using active sync or windows mobile device center. Page 117 of 163

Next we will make a Smart Device Application which will call this service. Create a form with a textbox to enter Byte Value for converting into KB & a button to call the service. Page 118 of 163

Self Test 1..Net Compact Framework supports only asynchronous web service calls? a. True b. False 2. To consume web service in the smart device project need to added a. Web reference b. Web Service uri c. Web method d. Web service name 3. What is proxy class with respect to web service? a. A class represents web service b. A class contains methods that serve as proxies for web methods c. A class used for implementing the call to web service method d. None 4. Asynchronous call to web service method makes application to wait for response? a. True b. False 5. Web Services uses SOAP protocols communication? a. True b. False Page 119 of 163

Background Chapter 9: Creating Mobile Sites Cell phones (mobile phones) have become part of our life style. Today mobile devices can connect to the Internet, and execute web applications. Mobile applications can now be developed to deliver any types of data, to any user, any place in the world! Different mobile devices support different programming languages. Some support WAP and WML, some support HTML or a limited version of HTML, and some support both or a different language. To support all types of mobile devices, developers must create one different application for each language. With.NET Mobile, Microsoft has introduced a new platform for developing mobile applications. This tutorial is about how to develop applications with an extension to the.net Framework, called the Microsoft Mobile Internet Toolkit (MMIT) or simply.net Mobile. What You Should Already Know Before you continue you should have a basic understanding of the following: HTML / XHTML XML namespaces ASP.NET ASP.NET Mobile is an extension to Microsoft ASP.NET and the Microsoft's.NET Framework. ASP.NET Mobile is a set of server-side Forms Controls to build applications for wireless mobile devices. These controls produce different output for different devices by generating WML, HTML, or compact HTML. How Does It Work? The following table shows how the.net Mobile works: Mobile Devices Page 120 of 163

The Internet Internet Information Services - IIS The.NET Framework ASP.NET.NET Mobile A web client requests a web page The request travels the Internet The request is received by IIS The request is handled by the.net framework The requested page is compiled by ASP.NET.NET Mobile handles any mobile device requirements The page is returned to the client Software Requirements To develop mobile applications with.net Mobile, you must have the following components: 1. Windows 2000 Professional/Server with IIS 5 2. All Windows 2000 service packs 3. The ASP.NET framework 4. Microsoft Mobile Internet Toolkit (MMIT) 5. Internet Explorer 5.5 or later 6. A WAP simulator You will need Windows 2000 to develop.net applications (IIS 5 (Internet Information Services) is a part of Windows 2000). If you want to read more about how to install.net go to our ASP.NET tutorial. You also have to install MMIT (.NET Mobile). Internet Explorer and MMIT can be downloaded from Microsoft MSDN. How to Start Developing a mobile web application with ASP.NET is very easy: 1. Create an ASP.NET page 2. Include System.Mobile.UI 3. Add Mobile Controls to the page Page 121 of 163

See the details in the next chapters. The Mobile ASP.NET Page Mobile Controls are the main building blocks of mobile applications. Mobile Controls are similar to Web Controls in ASP.NET. The following ASP.NET page displays "Hello World" as a WML card in a WML enabled cell phone: <%@ Page Inherits="System.Web.UI.MobileControls.MobilePage" %> <%@ Register TagPrefix="mob" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <mob:form runat="server"> <mob:label runat="server">hello World</mob:Label> </mob:form> The Page directive tells ASP to use (inherit) mobile page handling instead of regular page handling (like the one used for traditional browsers). The Register directive defines the prefix that will be used for mobile controls. We have used "mob", but you can use any prefix you like. The <mob:form> element tells the server to create a mobile form control. The <mob:label> element tells the server to create a mobile label control with the text "Hello World". When the ASP.NET page executes, it will produce the following output to a WAP enabled mobile phone: <?xml version='1.0'?> <!DOCTYPE wml PUBLIC '-//WAPFORUM//DTD WML 1.1//EN' 'http://www.wapforum.org/dtd/wml_1.1.xml'> <wml> <card> <p>hello World</p> </card> </wml> and this output will be produced for a Pocket PC: Page 122 of 163

<html> <body> <form id="ctrl1" name="ctrl1" method="post" action="example.aspx"> <div>hello World</div> </form> </body> </html> Conclusion.NET Mobile will generate WML code for WAP enabled cell phones and HTML code for devices like the Pocket PC. By detecting the browser,.net Mobile will output correct content, providing developers with a powerful tool to develop single applications that will serve many different mobile devices..net Mobile Emulators Mobile applications can be tested and viewed with different emulators. Using your Browser Since mobile web pages detect your browser, you can test your mobile applications with a standard browser. When a mobile web page detects a web browser it will produce HTML output. Openwave Simulators The Openwave mobile browser is the most common browser used in Internetenabled cellphones. The Nokia Mobile Internet Toolkit This toolkit contains emulators for most of the different Nokia devices. ASP.NET Mobile Web Forms ASP.NET Mobile Forms are specialized web forms designed to work on different mobile devices. Page 123 of 163

Mobile Pages A mobile page is much the same as an ordinary.net web page. It is a text file with an aspx extension, and it can contain a variety of web controls. The difference is the page directive that identifies the page as a mobile page, and the controls used on the page, which are mobile controls. The mobile controls can be programmed device-independently, and the page will produce an output that suits the device that access it. Mobile Forms Each mobile page must have at least one mobile form, and each mobile form can have a number of mobile controls. Note that mobile pages can have multiple mobile forms. This is due to the nature of mobile devices. Mobile devices have small screens and it is very normal to navigate between screens with a simple link. Automatic Paging ASP.NET Mobile supports automatic paging for different mobile devices. The paging is handled differently for each control. For example when paging takes place the controls included in a panel control will stay together. Creating a Mobile Web Application with Visual Studio Page 124 of 163

Figure 4 Creating an empty ASP.NET project. Although Mobile Web applications are built using the same underlying infrastructure as any ASP.NET applications technically they are a unique Web form and set of controls. To create a Mobile Web application start by selecting an empty ASP.NET project within Visual Studio as shown in Figure4. This creates an ASP.NET application project that contains only the solution root as shown in Figure5. Figure 5 The empty ASP.NET solution. Due to the range of device specific settings and unique markups Mobile Web applications often contain unique application settings. Visual Studio 2005 provides a default Mobile Web Configuration file that can be added as shown in Figure6. This file contains both a default set of ASP.NET Web configuration settings and Mobile Web configuration information. However, as we will see later depending on the application functionality and devices accessing the application further customization of this file may be required. Page 125 of 163

Figure 6 Adding a default Mobile Web.Config file. The Web.config file is a required component of any ASP.NET application and is designed to separate configuration and application code. The application level Web.Config is inherited from the ASP.NET root configuration file which by default is located in systemroot\microsoft.net\framework\versionnumber\config\web.config. This system wide configuration includes settings that apply to any ASP.NET application running under a specific.net framework version. Application level files are used to override these system wide defaults. The application level Web.config file stores the configuration settings for the current directory and any subdirectories applying the same inheritance model as the root configuration file. Configuration settings in the Web.Config file can also be optionally applied to individual files or subdirectories by specifying the path in the Web.Config <location> element. At run time ASP.NET uses the web.config files to hierarchically compute a unique collection of configuration settings for each incoming URL request. These settings Page 126 of 163

are initially created with the application domain and then cached on the server. At runtime ASP.NET automatically detects and applies any changes to the configuration files. The Mobile Web Page Figure7 Adding a Mobile Form to an application. Like the ASP.NET Web Form the Mobile Web form page acts as the visual design surface for Mobile Web applications. The page is added through the Add New Items menu as shown in Figure7. It s the Mobile Web Form Page as shown in Figure8 that is directly associated with the application URL. Page 127 of 163

All ASP.NET pages are represented by the Page class specified by the @ Page directive. This class is used to define page-specific attributes used by the ASP.NET page parser and compiler. At run time these files are compiled as Page objects and cached into server memory. Inheriting from the base Page class is the MobilePage class. By default, when a new Mobile Web page is added it contains the declarations shown below <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> Within any ASP.NET page, the page directive appears as the first set of attributes. The Page directive sets attributes on the global page object like the programming language and code behind file. The next page level directive registers a TagPrefix for the mobile namespace. This is used to declare a unique namespace for any mobile controls on the page. The Mobile Web page contains one or more Mobile Web Form controls that serve as the container for the individual rendered screens. One Mobile Web Form Page or card deck is considered an entire Mobile Web application. The combination of the Mobile Web Form Page and Mobile Web Form control change the design paradigm of Web sites from multi-page ASP.NET Web Forms to a single page with discrete groups of Mobile Web Forms. With this approach each Mobile Web Form page contains smaller Web Form control sections that like a single index card represent one screen of rendered data. Designing applications this way makes it easier to view and understand data with potentially lower resolution devices and smaller screens. With this design it is important to keep all the data in one card deck to reduce the amount of server round tripping. By default all headers within the same deck are transferred and made available locally on the mobile device. It is also important to keep in mind that putting too much detail in one deck may exceed the rendering mobile device limitations which varies but is generally about 2k of compiled data. Page 128 of 163

The Basics of Browser Identification The architecture pattern of an ASP.NET Web Site that contains mobile pages is to segregate these into different application folders. This separation between the mobile pages and ASP.NET helps to ease the deployment and maintenance of the Web site. However, to provide a consistent end user experience both types of applications are usually made available from a common URL. As HTTP Web requests are received they are interrogated and redirected to application paths based on the properties of the incoming request. Inside the HTTP headers request made by any browser is the user agent string. This string describes the browser making the request. The System.Web namespace contains the HTTPRequest class that provides information about the current request, the HTTPResponse class which manages HTTP output to the client and the HTTPServerUtility class which provides access to server side utilities and processes. Also, within the System.Web namespace is the HTTPBrowserCapabilities class that gathers information on the capabilities of the browser that is running on the client. For example, Listing 1 retrieves the requesting browser capabilities. Listing 1: Determining a browser s features. Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim bc As HttpBrowserCapabilities = Request.Browser Response.Write("<p>Browser Capabilities:</p>") Response.Write("Type = " & bc.type & "<br>") Response.Write("Name = " & bc.browser & "<br>") Response.Write("Version = " & bc.version & "<br>") Response.Write("Major Version = " & bc.majorversion & "<br>") Response.Write("Minor Version = " & bc.minorversion & "<br>") Response.Write("Is a Mobile Browser = " & bc.ismobiledevice & "<br>") Response.Write("Mobile Device Manufacturer = " & bc.mobiledevicemanufacturer & "<br>") Response.Write("Mobile Device Model = " & bc.mobiledevicemodel & "<br>") Response.Write("Is a Mobile Browser = " & bc.ismobiledevice & "<br>") Response.Write("Number of soft keys = " & bc.numberofsoftkeys & "<br>") Page 129 of 163

Response.Write("Platform = " & bc.platform & "<br>") Response.Write("Is Beta = " & bc.beta & "<br>") Response.Write("Is Crawler = " & bc.crawler & "<br>") Response.Write("Is AOL = " & bc.aol & "<br>") Response.Write("Is Win16 = " & bc.win16 & "<br>") Response.Write("Is Win32 = " & bc.win32 & "<br>") Response.Write("Supports Frames = " & bc.frames & "<br>") Response.Write("Supports Tables = " & bc.tables & "<br>") Response.Write("Supports Cookies = " & bc.cookies & "<br>") Response.Write("Supports VB Script = " & bc.vbscript & "<br>") Response.Write("Supports JavaScript = " & bc.ecmascriptversion.tostring & "<br>") Response.Write("Supports Java Applets = " & bc.javaapplets & "<br>") Response.Write("Supports ActiveX Controls = " & bc.activexcontrols & "<br>") Response.Write("CDF = " & bc.cdf & "<br>") End Sub Page 130 of 163

Figure 2 Browser features exposed by Internet Explorer. When accessing this page from various browsers there are definite differences between the desktop Internet Explorer client as shown in Figure2 and the Openwave mobile emulator shown in Figure3. Figure 3 Browser features exposed by a cellular phone. There are a variety of mobile emulators available on the market. For this article we are using the Openwave emulator (available from http://www.openwave.com) for non Windows based mobile phones. For Windows based devices like Pocket PC s and Smart Phones we are using the Windows Mobile 5 emulators available within Visual Studio 2005. Page 131 of 163

Using the exposed properties of the HTTPBrowserCapabilities you can discover and then redirect requests. For example, using the code in Listing 2 you can redirect an incoming browser request to an ASP.NET Mobile Web site based on the ismobiledevice property. Listing 2: Redirecting a mobile browser request. Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim bc As HttpBrowserCapabilities = Request.Browser If bc.ismobiledevice = True Then Response.Redirect("http://localhost/mobileapplication/default.aspx") End If End Sub Mobile Page Processing The life cycle of a.net Mobile Web Forms page and its controls are very similar to a regular ASP.NET page. However there are some differences as shown in Table 2. Comparison of an ASP.NET and Mobile Web Page. ASP.NET Page Life Cycle Stages Initialize Mobile Page Life Cycle Device adapters are chosen by using the <mobilecontrols> section of web.config. Load view state Process postback data Device-specific customizations are applied. Same as ASP.NET Same as ASP.NET Load The MobileControl base class implementation calls the OnLoad method of the control to perform device adapter specific loading of information. Send postback change notifications Handle postback events Pre-render Same as ASP.NET Same as ASP.NET Pagination is performed. Page 132 of 163

Save state Render Unload (Dispose) Unload (Dispose) Same as ASP.NET The adapter is responsible for accessing and rendering child controls in the appropriate order. The ASP.NET page framework renders each control by calling the Render method of its adapter. Performs device adapter-specific cleanup and unloading. Performs device adapter-specific cleanup and unloading. Self Test 1. HTML is supported by all the mobile browsers? a. True b. False 2. WAP/WML is supported by all the mobile browsers? a. True b. False 3. ASP.NET generates which of the following output? a. XHTML b. Compact HTML c. DHTML d. JavaScript 4. Which of the following browser is not available for mobile? a. Internet Explorer b. Opera c. Chrome d. Safari 5. Which of the namespace is required for using ASP.NET mobile controls? a. System.Web.UI b. System.Web.Forms.UI c. System.Mobile.UI Page 133 of 163

d. System.Mobile.UI.MobileControls 6. What is base class for Mobile Web Page? a. System.Mobile.WebForm b. System.Web.UI.MobileControls.MobilePage c. System.Web.UI.MobileControls.MobileWebForm d. System.Web.UI.MobileControls.MobileForm 7. Which of the following is not supported by ASP.NET mobile? a. Automatic Paging b. Generate WML code for WAP enabled cell phones and HTML code for HTML enabled devices. c. Using CSS d. Configuration settings in the Web.Config file for subdirectories 8. Which of the following class is used for identifying the browser capabilities? a. HTTPBrowserUtility b. HTTPClientBrowser c. HTTPServerUtility d. HTTPBrowserCapabilities 9. Which of the following property of HTTPBrowserCapabilities is used to detect the client is whether mobile device? a. ismobiledevice b. isdesktopdevice c. ismobilebrowser d. ismobileclient 10. Which of the following is not a part of ASP.NET Page Life Cycle? a. Load view State b. Process Post back c. Pre Load d. Pre Render Page 134 of 163

Chapter 10: Using ASP.NET Mobile controls ASP.NET Mobile Input Input Controls are used to collect input from the mobile user. Input Controls There are number of mobile controls that support user input. The most common input control is perhaps the TextBox control, which was demonstrated in the previous chapter. The TextBox control is perfect for simple user input like names, numbers, identifications and keywords. For larger amount of input a TextView control is a better choice. The TextView control allows long multi-line input like the one you need for SMS or other messages. Numeric Input The numeric attribute of the textbox control can be set to true or false to specify whether the textbox should accept only numeric input. Note: This behavior will normally work on cell phones by changing the input mode from letters to numbers. For HTML browsers however, this behavior is normally not supported. Password Input The password attribute of the textbox control can be set to true or false to specify whether the textbox should be treated as a password field. A password field will hide the input by displaying * (stars) instead of ordinary text. List Controls TextBox and TextView controls are well suited for entering input, but sometimes you want the user to select from a list of predefined values. The SelectionList Control supports drop down lists, check boxes and radio buttons. This topic is covered in another chapter. The List Control supports selection from menus and lists. The List Control is covered in another chapter. Page 135 of 163

User Interface Controls User Interface Controls are controls which display the user interface: Name Command Form Image Label Link List MobilePage ObjectList Panel SelectionList StyleSheet TextBox TextView Function Performs an action Defines a container for mobile controls Defines an image Defines a text Defines a hyperlink Defines a list Defines a container for mobile controls Defines a list of data objects Defines a container for other controls Defines a list to select from Defines styles to be applied to other controls Defines a single line input box Defines a multi-line input box For a full control reference, including properties methods, events, and more examples, please look at the "Mobile Reference" page. Displaying Text This mobile page uses a TextView control to display a large amount of text: <%@ Page Inherits= "System.Web.UI.MobileControls.MobilePage"%> <%@ Register TagPrefix="Mobile" Page 136 of 163

Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <Mobile:Form runat="server"> <Mobile:TextView runat="server"> This is a very long text to demonstrate how text can be displayed over several screens. This is a very long text to demonstrate how text can be displayed over several screens. This is a very long text to demonstrate how text can be displayed over several screens. This is a very long text to demonstrate how text can be displayed over several screens. </Mobile:TextView> </Mobile:Form> When this page is displayed on a mobile device, the navigation and display functions of the page will be compiled differently for different devices with different display characteristics. Page 137 of 163

When the text is displayed on a pocket PC with a small display, the user will be able to scroll the text with a scroll bar, but on a cell phone the text will be displayed over several screens with proper navigation tools added. Note that all mobile controls must have the runat attribute set to "server", in order to secure proper rendering of the page for different devices. Single Forms This mobile page has one form: <%@ Page Inherits= "System.Web.UI.MobileControls.MobilePage"%> <%@ Register TagPrefix="Mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <Mobile:Form runat="server"> <Mobile:Label runat="server">hello World </Mobile:Label> </Mobile:Form> Multiple Forms This mobile page has two forms: <%@ Page Inherits= "System.Web.UI.MobileControls.MobilePage"%> <%@ Register TagPrefix="Mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <Mobile:Form id="f1" runat="server"> <Mobile:Label runat="server">hello World </Mobile:Label> <Mobile:Link runat="server" NavigateURL="#f2">2 </Mobile:Link> </Mobile:Form> Page 138 of 163

<Mobile:Form id="f2" runat="server"> <Mobile:Label runat="server">hello Again </Mobile:Label> <Mobile:Link runat="server" NavigateURL="#f1">1 </Mobile:Link> </Mobile:Form> Links Note the <Mobile:Link> element in the example above. The link control lets the user navigate between the two mobile forms. ASP.NET Mobile Events Mobile Controls exposes device independent programmable events. Programming Events Mobile controls have an object model with programmable properties, methods and events. For a complete overview please refer to the reference section. Submitting Text This page has two forms: <%@ Page Inherits="System.Web.UI.MobileControls.MobilePage"%> <%@ Register TagPrefix="Mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <script runat="server"> Dim age Sub AgeClick(sender As Object, e As EventArgs) age=text1.text ActiveForm=Form2 End Sub Sub Form2_Activate(sender As Object,e As EventArgs) message.text="you are " & age & " years old" End Sub </script> Page 139 of 163

<Mobile:Form id="form1" runat="server"> <Mobile:Label runat="server">age?</mobile:label> <Mobile:TextBox runat="server" id="text1" /> <Mobile:Command runat="server" OnClick="AgeClick" Text="Submit" /> </Mobile:Form> <Mobile:Form id="form2" runat="server" OnActivate="Form2_Activate"> <Mobile:Label runat="server" id="message" /> </Mobile:Form> When a page has two forms, the first form is always opened by default. The first form has a label with the text "Age?", an input box to input the age, and a submit button. The second page is activated by the submit button on the first page, and displays a response. When the application runs on a mobile device, the two pages will display like this: Form 1: Age? 11 Submit Form 2: You are 11 years old Validation Controls Validation controls are used to validate the data entered by a user. Page 140 of 163

Validation controls allow you to validate an input control (like a TextBox), and display a message when validation fails. Each validation control performs a specific type of validation (like validating against a specific value or a range of values). By default, page validation is performed when a command control is clicked. You can prevent validation when a control is clicked by setting the CausesValidation property to false. Validating Input This page has two forms: <%@ Page Inherits= "System.Web.UI.MobileControls.MobilePage"%> <%@ Register TagPrefix="Mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <script runat="server"> Sub Page2(Sender as Object,E as EventArgs) If Page.IsValid Then ActiveForm=f2 text2.text="you are " & age.text & " years old" end if End Sub </script> <Mobile:Form id="f1" runat="server"> <Mobile:CompareValidator runat="server" ControlToValidate="age" Type="Integer" ValueToCompare="18" Operator="GreaterThanEqual"> You must be at least 18 </Mobile:CompareValidator> <Mobile:Label runat="server">age?</mobile:label> <Mobile:TextBox id="age" runat="server" /> Page 141 of 163

<Mobile:Command OnClick="Page2" runat="server"> Submit</Mobile:Command> </Mobile:Form> <Mobile:Form id="f2" runat="server"> <Mobile:Label id="text2" runat="server" /> </Mobile:Form> The first form has a label with the text "Age?", an input box to input the age, and a submit button. The second page is activated by the submit button on the first page, and displays a response. If the input validates as error, an error message is displayed. When the application runs on a mobile device, the two pages will display like this: Form 1 Age? Submit Form 2 You are 21 years old The ValidationSummary Control The previous example used a CompareValidator control to validate an input field. The field to validate was defined by the attribute ContolToValidate. You can also use a ValidationSummary control with the attribute FormToValidate, to validate all the input of a form. This way you can display a summary of errors instead of one error at the time. Page 142 of 163

Validation Controls Reference Name Function CompareValidator CustomValidator RangeValidator RegularExpressionValidator RequiredFieldValidator ValidationSummary Compares two values Provides custom validation Validates a range Validates an expression Validates required data Displays a validation summary ASP.NET Mobile Lists The Mobile List Control supports different input and display properties. Selecting from a List This page has two forms: <%@ Page Inherits= "System.Web.UI.MobileControls.MobilePage"%> <%@ Register TagPrefix="Mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <script runat="server"> Sub Show_Price(sender As Object,e As ListCommandEventArgs) text1.text=e.listitem.text & "=" & e.listitem.value ActiveForm=f2 End Sub </script> <Mobile:Form id="f1" runat="server"> <Mobile:List runat="server" OnItemCommand="Show_Price"> <Item text="volvo" value="$30,000" /> Page 143 of 163

<Item text="bmw" value="$32,000" /> <Item text="audi" value="$34,000" /> </Mobile:List> </Mobile:Form> <Mobile:Form id="f2" runat="server"> <Mobile:Label runat="server" id="text1" /> </Mobile:Form> The first form has a list of cars. The second page displays a price. This page is activated when a car is selected on the first page. When the application runs on a mobile device the two pages will display like this: Form 1: Volvo BMW Audi Form 2: Volvo=$30,000 ASP.NET Mobile Selections The SelectionList Control supports drop down lists, check boxes and radio buttons. The SelectionList This mobile page uses a SelectionList to let the user select a car: <%@ Page Inherits= "System.Web.UI.MobileControls.MobilePage"%> <%@ Register Page 144 of 163

TagPrefix="Mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <script runat="server"> Sub Car_Click(sender as Object, e as EventArgs) ActiveForm=f2 t1.text=cars.selection.value End Sub </script> <Mobile:Form id="f1" runat="server"> <Mobile:SelectionList runat="server" id="cars" > <Item Text="Volvo" Value="$30,000" /> <Item Text="BMW" Value="$32,000" /> <Item Text="Audi" Value="$34,000" /> </Mobile:SelectionList> <Mobile:Command runat="server" OnClick="Car_Click" Text="Submit" /> </Mobile:Form> <Mobile:Form id="f2" runat="server"> <Mobile:Label id="t1" runat="server" /> </Mobile:Form> When this page is displayed on a mobile device, the navigation and display functions of the page will be compiled differently for different devices with different display characteristics. For some devices, like a handheld PC, it might display a dropdown list to choose from. For a cell phone it might display a list of options to select from. ASP.NET Mobile Images ASP.NET Mobile displays different types of images for different types of devices. The Image Control Different mobile devices have different display capabilities. The Image Control allows the developer to specify different types of images for different types of devices. Page 145 of 163

Image Types Some mobile devices will display GIF images. Other mobile devices will display BMP images or WBMP images. The Image Control allows you to specify different images for each preferred image type. This mobile page displays an image: <%@ Page Inherits= "System.Web.UI.MobileControls.MobilePage"%> <%@ Register TagPrefix="Mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <Mobile:Form runat="server"> <Mobile:Image runat="server"> <DeviceSpecific> <Choice ImageURL="image.gif" /> <Choice ImageURL="image.bmp" /> <Choice ImageURL="image.wbmp" /> </DeviceSpecific> </Mobile:Image> </Mobile:Form> When this page is displayed on pocket PC, a GIF image will be displayed. On a cell phone a WBMP image or a BMP image will be displayed, according to the characteristics of the cell phone. ASP.NET Mobile Utilities Utility controls support complicated user interfaces with minimum of code. The AdRotator Control This mobile page displays different advertisements: <%@ Page Inherits= "System.Web.UI.MobileControls.MobilePage"%> <%@ Register TagPrefix="Mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> Page 146 of 163

<Mobile:Form runat="server"> <Mobile:AdRotator runat="server" AdvertisementFile="advertisements.xml"> </Mobile:AdRotator> </Mobile:Form> This is the ad file called "advertisements.xml": <?xml version="1.0"?> <Advertisements> <Ad> <ImageUrl>image1.gif</ImageUrl> <BmpImageUrl>image1.bmp</BmpImageUrl> <WBmpImageUrl>image1.wbmp</WBmpImageUrl> <NavigateUrl>http://www.1.com</NavigateUrl> <AlternateText>Visit 1</AlternateText> </Ad> <Ad> <ImageUrl>image2.gif</ImageUrl> <BmpImageUrl>image2.bmp</BmpImageUrl> <WBmpImageUrl>image2.wbmp</WBmpImageUrl> <NavigateUrl>http://www.2.com</NavigateUrl> <AlternateText>Visit 2</AlternateText> </Ad> <Ad> <ImageUrl>image3.gif</ImageUrl> <BmpImageUrl>image3.bmp</BmpImageUrl> <WBmpImageUrl>image3.wbmp</WBmpImageUrl> <NavigateUrl>http://www.3.com</NavigateUrl> <AlternateText>Visit 3</AlternateText> </Ad> </Advertisements> Page 147 of 163

Calendar Control This mobile page displays a calendar: <%@ Page Inherits= "System.Web.UI.MobileControls.MobilePage"%> <%@ Register TagPrefix="Mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <Mobile:Form runat="server"> <Mobile:AdRotator runat="server" AdvertisementFile="advertisements.xml"> </Mobile:AdRotator> </Mobile:Form> <%@ Page Inherits= "System.Web.UI.MobileControls.MobilePage"%> <%@ Register TagPrefix="Mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <script runat="server"> Sub CalChanged(sender as Object,e as EventArgs) lab1.text="you selected " & c1.selecteddate ActiveForm=f2 End Sub Page 148 of 163

</script> <Mobile:Form id="f1" runat="server"> <Mobile:Calendar id="c1" OnSelectionChanged="CalChanged" runat="server" /> </Mobile:Form> <Mobile:Form id="f2" runat="server"> <Mobile:Label id="lab1" runat="server" /> </Mobile:Form> In this example a calendar is displayed in the first form. When the user select a date from the calendar, the selected date is displayed in a new form. PhoneCall Control This mobile page will display the text "Tove's number" and dial the number (555) 555-5555 when the user selects the text: <%@ Page Inherits= "System.Web.UI.MobileControls.MobilePage"%> <%@ Register TagPrefix="Mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <Mobile:Form runat="server"> <Mobile:PhoneCall runat="server" PhoneNumber="(555) 555-5555" Text="Tove's number" AlternateFormat="0" /> </Mobile:Form> The attribute "AlternateFormat" has the value "0". This displays the text from the attribute "Text". If you use the value "1" it will display the text from the attribute "PhoneNumber". You can also use a construct like this: AlternateFormat="0 is 1". This will display the text "Tove's number is (555) 555-5555". Page 149 of 163

Utility Controls Name Function AdRotator Calendar PhoneCall Displays advertisements Displays a calendar Calls a telephone number For a full control reference, including properties methods, events, and more examples, please refer to the "Mobile Reference" page. Page 150 of 163

Self Test 1. Which of the following is not supported by WAP enabled browsers? a) Table b) Ordered List c) Hyper Link d) Frames 2. For using mobile controls which assembly is need to be registered? a) System.Web.Mobile b) System.Web.Mobile.UI c) System.Web.Mobile.UI.MobileControls d) None 3. runat attribute is not required for mobile controls? a) True b) False 4. When a page has two forms, the first form is always opened by default, the second form is activated by the submit button on the first page? a) True b) False 5. Mobile Prefix in the tags in ASP.NET mobile forms cannot be changed? a) True b) False 6. Which of the following statement is not true a) The Image Control allows the developer to specify different types of images for different types of devices. b) PhoneCall Controls allows the user to make a phone call through internet c) AdRotator Control will display BMP or WBMP image if mobile device doesn t support displaying images in gif format d) None Page 151 of 163

Chapter 11: Accessing Database in Mobile Sites Procedure for accessing the database in mobile ASP.NET will be same as ASP.NET for desktop, only difference lies between the browser mobile capabilities. For example for desktop browser html table is supported so you can use the DataGrid control, form mobile html table is not supported by all browsers. For mobile you can use alternative controls like object list for display the data list ObjectList Control Figure 1 The ObjectList Control The ObjectList control is used to display multiple views of data collections. Each item or object contains data groupings that in turn contain individual data elements. The HTML to render this control is shown below. <mobile:form id="form1" runat="server"> <mobile:objectlist ID="ObjectList1" Runat="server" CommandStyle- StyleReference="subcommand" LabelStyle-StyleReference="title"> </mobile:objectlist> </mobile:form> The ObjectList control is a data bound control. When data bound the control contains a row of data for each object. The individual columns show the field values and the control displays a detailed view for each object. Applications bind to this control using the Data View, Dataset or any object that implements the IEnumerable Page 152 of 163

interface. When an objectlist control performs databinding it can automatically generate the fields displayed for each publicly available list item. Data Binding with the Object List Figure 2 Adding a Dataset designer. The DataSet object represents a complete set of data. It includes the tables that define order and constraints, as well as the relationships between the tables. Applications bind to a specific field in a DataTable object contained in the DataSet object. Visual Studio provides a DataSet designer that can be added to a project as shown in Figure 2 Once added to the project the TableAdapter wizard connects and binds to the data source using the following steps to create the typed DataSet. Page 153 of 163

Figure3 Connecting to the datasource 1. Connect to the database Figure 4 Saving the connection string Page 154 of 163

2. Define the connection string that is stored in the web.config file. Figure 5 Specifying the Command Type 3. Define the command type that is used to retrieve the data. Figure 6 Binding the commands to the TableAdapter Page 155 of 163

4. Define the parameters and methods for retrieving data Figure 7 Defining the TableAdapter fill methods 5. Define the methods that are used to both fill and retrieve data from the TableAdapter. Figure 8 The system generated schema definition Page 156 of 163

Once the wizard is completed it generates a schema definition within the project as shown in Figure 8 Accessing the TableAdapter TableAdapters objects aren t actually part of the.net Framework. They are entirely generated by Visual Studio using the Configuration Wizard or the DataSet designer. TableAdapaters are designed to abstract the database away from application code. The abstraction is created in two parts. The first part is the common language runtime (CLR) to database type conversion that happens inside the TableAdapter. Since the.net programming languages do not natively contain data types for database access, a mapping is created between the type of the database column and a CLR type. By creating this mapping, a TableAdapter can expose methods and properties associated with columns in the database that can be accessed directly by your code. The second part of the abstraction is encapsulation of the database objects. Encapsulated within the TableAdapter are a DataAdapter, a connection object, and an array of command objects. The command objects are exposed publicly through method calls for each command object, there is a public method on the TableAdapter. These command objects are exposed as TableAdapter queries in the dataset schema. Within the Page Load event you can leverage this object with the ObjectList using the below code If Not IsPostBack Then Dim ta As New DataSet1TableAdapters.EmployeesTableAdapter Dim dt As New DataSet1.EmployeesDataTable ta.fill(dt) With ObjectList1.DataSource = dt.databind() End With End If Page 157 of 163

Figure 9 the ObjectList lookup screen Figure 10 The ObjectList detail screen When the application is run it provides two views of the data as shown in Figure 9 and Figure 10. Accessing data through code Page 158 of 163

using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; public partial class Mobile_ProductList : System.Web.UI.MobileControls.MobilePage protected void Page_Load(object sender, EventArgs e) if (!IsPostBack) SqlConnection con = new SqlConnection("Data Source=.\\SqlExpress;Integrated Security=True;Initial Catalog=Northwind;"); SqlDataAdapter da = new SqlDataAdapter("select ProductName, ProductID, UnitPrice from Products", con); DataSet ds = new DataSet(); con.open(); da.fill(ds, "Products"); con.close(); ObjectList1.DataSource = ds.tables[0]; ObjectList1.DataBind(); Page 159 of 163

Data Binding with SelectionList & List controls 1. Create a mobile form add selection list, list control to it 2. Write below code Page 160 of 163

using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.SqlClient ; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; public partial class Mobile_DataBinding : System.Web.UI.MobileControls.MobilePage protected void Page_Load(object sender, EventArgs e) if (!IsPostBack) SqlConnection con = new SqlConnection("Data Source=.\\SqlExpress;Integrated Security=True;Initial Catalog=Northwind;"); SqlDataAdapter da = new SqlDataAdapter("select CategoryID, CategoryName from Categories", con); DataSet ds = new DataSet(); con.open(); da.fill(ds, "Products"); con.close(); SelectionList1.DataSource = ds.tables[0]; SelectionList1.DataTextField = "CategoryName"; SelectionList1.DataValueField ="CategoryID"; SelectionList1.DataBind(); protected void SelectionList1_SelectedIndexChanged(object sender, EventArgs e) SqlConnection con = new SqlConnection("Data Source=.\\SqlExpress;Integrated Security=True;Initial Catalog=Northwind;"); Page 161 of 163

SqlDataAdapter da = new SqlDataAdapter("select ProductName,ProductID from Products where CategoryID=@CategoryID", con); da.selectcommand.parameters.addwithvalue("@categoryid", SelectionList1.Selection.Value); DataSet ds = new DataSet(); con.open(); da.fill(ds, "Products"); con.close(); List1.DataSource = ds.tables[0]; List1.DataTextField = "ProductName"; List1.DataValueField = "ProductID"; List1.DataBind(); Page 162 of 163

Self Test 1. How to expose the methods and properties associated with columns in the TableAdapter a) By creating the mapping between type of the database column & CLR type b) By using configuration wizards c) By using DataAdapter d) None of the above 2. As GridView controls is not supported in ASP.NET mobile, which of the following can be a suitable replacement? a) Selection List b) Object List c) List d) TextBox 3. Which of the following is not a part of DataSet a) DataTable b) DataRelation c) TableAdapter d) Schema 4. To bind the data in control you don t need to call explicitly DataBind() method in the ASP.NET Mobile a) True b) False 5. Auto post back is supported by Selection List control? a) True b) False Page 163 of 163