Getting Started with Windows Mobile Development

n today’s world of fast food, fast cars, and instant gratification, people expect to be in touch at all times. We have become conditioned to staying in touch with businesses, friends, and families. Because of this desire for instant data, we have the Internet, cell phones, Wi-Fi, MP3 players, and DVD players. As the equipment needed to drive this thirst has become smaller and smaller, we find ourselves looking for portable replacements for our bulky desktop computers.

This article guides you into the exciting world of Windows mobile development so you can take advantage of an expanding opportunity to supply software to this burgeoning market.

Getting Started
There are currently two choices for producing mobile software using a Windows operating system: ActiveSync on XP, and?for Vista?a new interface built upon ActiveSync technology, called the Windows Mobile Device Center (WMDC).

In the recent CoDe Focus issue on Mobile PC Development (2007, Volume 4, Issue 2), Nick Landry’s article entitled “Windows Vista Mobility: Why Should You Care?” provides a good review and tutorial on using WMDC with Vista. If you’re going to use WMDC, you’ll definitely want to read this article.

If you are using Vista, download the WMDC from Microsoft’s site; if you’re using XP, download ActiveSync. The remaining software requirements are not operating system dependent. When you install Visual Studio 2008, the .NET Compact Framework and SQL Server Mobile Edition are also installed. Visual Studio 2008 is required to use the latest version of the different frameworks. If you plan to develop for earlier versions of the Compact Framework, you can use either Visual Studio 2008 or 2005.

The Compact Framework
The Compact Framework is the vehicle for mobile development. How does the Compact Framework differ from the full version? For starters, Microsoft removed most of the nice-to-have method overloads and non-essential functionality, giving the Compact Framework a much smaller footprint. Distilling the regular framework to a size that can be installed onto a device with limited memory and disk capacity must have been no easy task. However, the Compact Framework provides nearly everything you need to develop for smart phones and Pocket PCs. It does not provide support for:

  • Click-once deployment
  • Remoting
  • Printing
  • Web Forms
  • Configuration files
  • Binary serialization

You can easily replace most of the missing functionality with custom code or solutions available from third-party providers.

SQL Server Mobile Edition (SQLme)
SQLme is a subset of regular SQL Server that works with both SQL Server 2005/2008 and the Express versions of each product. The majority of necessary functionality is there. You can use the SQL Server Management console to manage your SQL Server mobile database on the desktop or on the PPC through a direct connection.

There are a few limitations to using SQLme:

  • No stored procedures
  • No batch queries
  • Limited table design

The lack of stored procedures is not a big problem to overcome. It is easy to simulate stored procedures using TableAdapters, because you can create as many methods on the TableAdapter as you need. Then, when you need to make a data call, you can refer to the method name instead of a stored procedure. If you choose not to use TableAdapters, you can simply add methods to your data layer to accomplish the same task.

Missing batch query capability is again not much of a hassle with disconnected data. You probably won’t be performing massive amounts of data munging or extraction on the mobile platform. Most basic data operations on a mobile platform involve simple data retrieval and update. Because you make these retrieval requests through a data layer, it makes no difference if the commands are processed together or one at a time.

Limited table design is not a real problem either. The most frustrating thing about using the table editor in the management studio is that you cannot move columns around in your design without deleting them and recreating them in the desired order. The workaround is to make sure your design is what you want before you create a number of tables. Otherwise, the table design process is like the regular SQL Server version; you have a wide range of data types to support your requirements.

Editor’s Note: This article was first published in the July/August 2008 issue of CoDe Magazine, and is reprinted here by permission.

Mobile Data
Mobile data differs from desktop applications mainly by:

  • Form factor
  • Memory restrictions
  • Processor speed
  • Bandwidth
  • Disconnected nature

Form factor is probably the most serious restriction in the world of mobile development. Mobile screen sizes run the gamut, from 2 x 3 inches up to 5 x 7 inches, resolutions from 240 x 320 pixels up to 640 x 480 pixels, and shapes from square to vertical or horizontal rectangles.

When designing a UI for a mobile application, you must consider the restrictions on space and plan accordingly. There are a number of issues that you face when designing forms for the mobile device. I will tackle these at length in the section dealing with compact controls later in this article.

Memory restrictions are another design factor. On mobile devices, memory is measured in megabytes, not gigabytes. While you can use mini plug-in cards to increase storage space, those don’t increase the amount of memory available to programs. Because of the limited resources, you don’t want to hold lots of data in memory, because that leaves little for system use. Mobile operating systems will shut down programs running in the background to provide resources to the foreground application.

Processor speed requires you to be cognizant of the time operations and database queries take. Device manufacturers are aware of the need for speed, and are pushing chip manufacturers to release faster and faster processors. PPCs being released later this year will use the newest 700 MHz processors.

Bandwidth is smaller than cabled systems or internal networks, so data access, in today’s world, is slower than desktops and laptops. While great strides are being made, the technology is still on the cutting edge, and you will have to wait until the infrastructure catches up to the technology.

The disconnected nature of the data also presents some challenges. SQLme provides a number of ways to manage data on the mobile device: Remote Data Access, Merge Replication, and a new service called Microsoft Access Database Synchronizer. These capabilities let you move data to/from the mobile device; however, these services are not compatible with SQL Server Express editions.

All in all, it is fairly simple to work around these limitations by using good simple design and efficient data retrieval mechanisms.

Visual Studio Integration
Compact Framework development is integrated directly into Visual Studio. With this coupling, you can develop your application, control emulators, test SQL replication, write unit tests, and cradle a real device to test synchronization using WMDC or ActiveSync.

You have two options when writing/testing your mobile application:

  1. The actual device
  2. An emulator

Developing with the actual device is a common practice when you want to test program speed, ease of physical use, etc. However, it can be an expensive proposition if you want to test many devices.

Emulators are virtual devices built on the same hardware platform as the original device. Emulators make it much easier to develop for many different devices with varying form factors and capabilities. Microsoft provides a number of emulators, with both the Windows Mobile 5.0 SDK and Windows Mobile 6 SDK, giving you the capability to test multiple form factors and device requirements.

Most mobile technology manufacturers today also provide emulators for their devices to aid in your development effort. So if you need a specific emulator, the Treo 750 for example, you can usually download it from the manufacturer’s web site.

Mobile Development in Visual Studio
You create your mobile application projects in the same way that you create regular desktop applications: From the File menu choose “New” and then choose “Project.” Next, select a Smart Device Project (see Figure 1). You indicate the project name at the bottom and set the target Compact Framework edition using the dropdown list in the upper portion of the screen. Clicking OK on this screen leads to a subsequent form where you choose the target project type (see Figure 2). Visual Studio will then create your solution and add a default program and form.

Figure 1. Selecting a Device: The figure illustrates smart device project selection in Visual Studio 2008.
Figure 2. Select Project Type: Visual Studio gives you a number of options when selecting the type of project for mobile development.

Rename the form and program to give them meaningful names. Now you can build your solution in the same way you normally would with a desktop application. As you need class libraries or other forms, you simply right-click the solution or project and add the desired item.

The best practice for normal application design is to use a three-tier approach: a UI layer, a business layer, and a data layer. It is common practice in application development to separate these specific application functionalities into individual classes. Even if you intend to use the mobile application as a web services consumer, or use the same back-end classes as existing web or desktop/laptop applications, the three-tier approach still applies.

However, the mobile orders application described in this article uses only two tiers. Because the application uses strongly-typed datasets and the table adapters included with them, it doesn’t make sense to have another data layer with duplicate method calls just to separate the functionality. The mobile orders program will have a UI layer and a business layer.

Creating the Database
You can create your compact database using either Visual Studio or SQL Server. For this example, you will create the tables you need using the built-in functionality of Visual Studio:

  1. Open your Server Explorer.
  2. Right-click the Data Connections item.
  3. Choose “Add Connection.”
  4. Fill in the fields in the Add Connection dialog box (see Figure 3).
  5. Click the Create button.
  6. Fill in the fields in the “Create New SQL Server Compact Database” dialog box (see Figure 4) and click OK.
  7. Test your connection, and then click OK.
Figure 3. Creating a New Data Connection: Using the Add Connection dialog, specify the data source and connection properties.
Figure 4. Creating a New SQL Server Compact Database: Use the dialog shown in this figure to create a new SQL Server compact database.

With the database created, you can start creating the tables you need for the application by right-clicking the new data connection and choosing “Create table.” For the mobile orders application, I created these tables: customer, order, orderitem, inventory, supplier, and manufacturer.

With the database structure in place, you can create strongly typed datasets by dragging each table from the server explorer to the dataset designer. The designer will create all the necessary code for you when you close it.

Windows Forms vs. Mobile Forms
Much of the mobile forms development is the same as Windows Forms; however, there are some distinct differences. These differences include:

  • Data binding
  • Data grid/custom controls
  • Events
  • Data entry

With Windows Forms, data binding is the accepted best practice; with mobile forms, manual binding is sometimes better. Manual binding is faster than the built-in data binding. Because you are typically dealing with only a handful of controls on any given form, the effort necessary to bind the controls to the data is more trouble than it is worth. However, standard data binding makes sense when you need:

  • Master/detail binding
  • Navigation
  • Currency Manager/BindingSource

Here’s a sample of how the mobile orders project uses manual binding to populate the controls:

   private void FillOrderHeaderControls(      OrderDataSet.OrderRow dr)   {      this.txtCustomer.Text = dr.CustomerName;      this.dtgOrderDate.Value = dr.OrderDate;   }   private void FillOrderItemControls(      OrderItemDataSet.OrderItemRow dr)   {      this.txtManPartNo = _dr.ManPartNo;      this.cboInventory.SelectedValue =_dr.fkInventory;      this.txtQuantity.Text = (string)dr.quantity;      this.txtPrice.Text = _dr.price;          _dtItem.AddOrderItemRow(_dr);   }

To gather control values to fill a row:

   private void FillOrderHeaderRow()    {      _drOrder = _dtOrder.NewOrderRow();      _drOrder.fkCustomer = _cBiz.GetCustomerKey(         this.txtCustomer.Text);      _drOrder.OrderDate = this.dtgOrderDate.Value;      _dtOrder.AddOrderRow(_drOrder);   }   private void FillOrderItemsRow()   {      _drItem = _dtItem.NewOrderItemRow();      _drItem.ManPartNo = _iBiz.GetManPartNo(value);      _drItem.fkOrder = 0;      _drItem.fkInventory = this.GetInventoryKey         (this.cboInventory.Text);      _drItem.Description = this.cboInventory.Text.Trim();      _drItem.quantity = (int)this.txtQuantity.Text;      _drItem.price = (decimal)this.txtPrice.Text        _dtItem.AddOrderItemRow(_drItem);   }

One common question on the Compact Framework forum deals with adding custom controls to grid columns. Out of the box, the DataGrid control does not support custom columns without some extra work?unlike the regular framework DataGrid control.

With the release of .NET CF 2.0 SP1, the team exposed the DataGrid column’s Paint method, which opens the opportunity for custom control creation. Due to the number of requests for help with this feature, they created a downloadable package that includes a number of useful controls, including the ComboBox, the CheckBbox, and a DateTimePicker. After you reference that library in your project, you can include custom columns with ease:

   //TextBox Column   DataGridCustomTextBoxColumn colOrdNo = new          DataGridCustomTextBoxColumn();   colOrdNo.Owner = this.grdSearch;   colOrdNo.HeaderText = "No";   colOrdNo.MappingName = "OrderNo";   colOrdNo.Alignment = HorizontalAlignment.Left;      //CheckBox Colum   DataGridCustomCheckBoxColumn colTaxable = new       DataGridCustomCheckBoxColumn();   colTaxable.Owner = this.grdSearch;   colTaxable.HeaderText = "Taxable";   colTaxable.MappingName = "Taxable";   colTaxable.Alignment = HorizontalAlignment.Center;

Mobile devices don’t support easy data entry into form controls. For the most part, users have to enter text via a built-in hardware mini QWERTY keyboard or using a pop-up software keyboard called a SIP (software input panel). On older smart phones without the hardware keyboard, users must press the number keys on the keypad to enter text. Using any of these options, text entry is difficult, time consuming, and tedious. Therefore, a mobile forms designer must limit the amount of data entry required through the use of judiciously planned controls. Use drop-down lists pre-populated with the most common choices, check boxes, and lists to limit the amount of typing necessary.

Events are another place where mobile development is distinctly different from desktop applications. A typical Windows Form has more than 75 events; a mobile form has 23. A regular button has 60 events; a CF button has 11.

Because of this event disparity, you will need to put more thought into program flow and into creating and designing your mobile forms and projects than your Windows Forms applications.

Creating the Order Form
The order form example shows the primary techniques you’ll use when creating mobile application forms. Remember that form real estate is minimal, and that form factor changes (differing devices) can affect your layout and data entry. You solve this problem by using a TabControl or panel on each form as a container for the objects within it. With a TabControl, you effectively extend screen space by adding tab pages and more controls as needed.

The order form in the next example will let users:

  • Search for an order
  • View a specific order
  • Edit a selected order
  • Delete a selected order
  • Add a new order

To create the form design, I dragged a TabControl from the ToolBox, and then added controls to the TabPages to display what I wanted. New forms added to the project initially have an empty MainMenu control. To create your menu actions, simply click the menu bar (see Figure 5) and type. You can add as many menu items horizontally and vertically as you need. Figure 6 and Figure 7 show the completed order form with its TabControl in place and the MainMenu items added.

Figure 5. Creating Menus: New forms have an empty MainMenu control to which you add items by clicking the menu bar and typing the item names.
Figure 6. Search Tab: When users click the Search tab, they can select a customer and a date range for which to search.
Figure 7. The View Order Tab: Selecting an order in the main grid and clicking the View Order tab displays the selected order in detail mode.

To search for a given order, you will use the customer key and a date range. I’ve set the default date range to the hundred year period from 1950-2050. The code for the search is as follows (in this example, _rowNumber is set in a method that determines the row number of the selected DataGrid row in a grid hit method):

   private void SearchMenuItem_Click(      object sender, EventArgs e)   {      OrderBiz biz = new OrderBiz();      _dtOrder = biz.Find(         this.cboCustomer.Text.Trim(),         this.dtgStartDate.Value,          this.dtgEndDate.Value);      this.grdSearch.Select(_rowNumber);      if (_dtOrder.Rows.Count > 0)      {         this.ViewMenuItem.Enabled = true;         this.DeleteMenuItem.Enabled = true;      }   }

In this code sample, you make a call to the order business object to perform the search and return a strongly typed dataset containing the matching orders. The business object’s Find() method is shown here:

   public OrderDataSet.OrderDataTable Find(      string customerName, DateTime startDate,       DateTime endDate)   {      OrderDataSet.OrderDataTable dt = new          OrderDataSet.OrderDataTable();      OrderTableAdapter ta = new OrderTableAdapter();      if (customerName.Equals("ANY"))      {         customerName = string.Empty;      }      ta.FillBy(dt, startDate,         endDate, "%"+customerName+"%");      return dt;   }

The main form’s grid then displays the orders returned by the search. By selecting an item in this grid and pressing the View menu item, the selected order and its order items will be displayed in the view mode (on the View Order tab). The view mode displays the order’s subtotal, tax, and total, which requires an instance of the inventory business object in addition to the order and order item business objects (see Listing 1 and Listing 2 respectively).

Another item to consider is data entry in your forms. If your target device supports both a hardware QWERTY keyboard and a SIP, you need to worry about the SIP, because when users display the SIP, it might cover up the entry-field text boxes when users enable it, preventing users from being able to see the text they’re entering. When that’s a possibility, you need to trap an event and resize your TabControl so no fields get covered.

The SIP includes a property called VisibleDesktop, which lets you know how much real estate is visible after the SIP is open. If necessary, the device will add scroll bars to the TabControl so that you can enter text into all available fields. Here’s the code:

   private void inputPanel_EnabledChanged(      object sender, EventArgs e)   {      if (inputPanel.Enabled)      {         //get the height of the TabControl         _originalHeight = this.tcTab.Height;         //adjust the TabControl for the SIP's space         this.tcTab.Height = inputPanel.VisibleDesktop.Height;      }      else      {         this.tcTab.Height = _originalHeight;         this.tcTab.Dock = DockStyle.Fill;      }   }

Running and Debugging the Code
Using Visual Studio, you have two choices for setting the target device for deployment. The first is to set the active Target Device field in the Properties page for your main Project and the second option is to use the Device Toolbar’s drop-down list to select the target device or emulator.

If your code compiles, deployment to the emulator/target device begins. Visual Studio transfers the requisite CABs to the target and runs them to install the DLLs your application needs. If you are using an emulator, deploying these CABs is a slow process. To prevent having to wait each time you compile and deploy your application, you can save the state of the emulator by either choosing “Save State” from the File menu or by closing the form and answering “Yes” to the resulting dialog box.

If you set breakpoints in your code, you can stop program execution on the emulator/target device and step through the code, just as you would when developing a desktop application. However, there are a few limitations: Edit and Continue is not supported, and there are no DataSet visualizers, so you can’t look at the state of the data at any given point. You can use QuickWatch to display the object and drill down into the object hierarchy to look at the column and row collections.

Packaging the Code for Distribution
After you finish your code and are satisfied with its functionality, you are ready to create a distribution CAB. You’ll find a special project available from the “Other Projects/Setup and Deployment” page in the New Projects wizard. You need to take a couple of steps to package your application as a CAB file for deployment:

  1. Add the Smart Device CAB project to your solution.
  2. Right-click the project and choose Add Project Output.
  3. Choose Primary Output from the list of file types.

When you add the primary output to the CAB project, Visual Studio determines the required dependencies for you and adds them to your project automatically. If your project requires any additional files, you can add them manually. You also need to add a reference to the compact database you created. After adding the dependencies, you can finish the deployment project:

  1. Right-click the file system portion (left pane) of the project screen and choose Add Special Folder.
  2. Choose Windows Folder from the list presented.
  3. Click the application folder.
  4. Select all your application DLLs from the middle pane and move them to the Windows folder you just created.

This completes the creation of the deployment project. Build the project just like any other project and the output will be your package application CAB.

You can also add program icons and registry entries using the CAB project?you can find a more detailed explanation here.

One typical deployment requirement is to package multiple CABs into one package that includes your application CAB, the .NET Compact Framework CAB, the SQLme CAB, and any others your program requires. That way, because all the requisite CABs are included, your program installation can proceed without error. Any necessary programs get installed automatically prior to your application’s installation. Unfortunately, doing that requires a great deal of effort to package correctly; however, there is a relatively painless solution: Pocket PC Installer.

Figure 8. Pocket PC Installer: You can drag and drop additional files to be installed with your application to your deployment project.

This inexpensive, wizard-driven program is well worth the investment. It includes options for most installer features, including license agreements and background images. You create the install by simply dragging and dropping files on the file listing screen (see Figure 8).

The major benefit of this program is that after compiling your installation files, you create two executable files: a PC executable that you can copy to your PC and from there to a connected device and a second PPC executable to copy directly to the device.

Unlimited Potential
Compact Framework development has the potential for explosive growth. Conservative estimates indicate that there are over two billion cell phones worldwide. Many citizens of third-world countries can’t afford and will never own a desktop computer, but will use their cell phones to access the Internet. By employing the ideas and techniques in this article you can become proficient in developing for mobile markets and take advantage of this growth opportunity.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: