Programmer to ProgrammerTM  
Wrox Press Ltd  
   
  Search ASPToday Living Book ASPToday Living Book
Index Full Text
 
ASPToday Home
 
 
Home HOME
Site Map SITE MAP
Index INDEX
Full-text search SEARCH
Forum FORUM
Feedback FEEDBACK
Advertise with us ADVERTISE
Subscribe SUBSCRIBE
Bullet LOG OFF
                         
      The ASPToday Article
January 30, 2002
      Previous article -
January 29, 2002
   
 
   
   
   
Using the Smart Device Extensions for Visual Studio to create Mobile applications   Fabio Claudio  
by Fabio Claudio
 
CATEGORIES:  .NET Framework, XML/Data Transfer  
ARTICLE TYPE: Overview Reader Comments
   
    ABSTRACT  
 

The release of Microsoft's .NET Framework brings the ability to easily create Web Services. Previously, DCOM was the unique solution to execute remote functions in the Windows operating system. DCOM is not the easiest protocol to implement in Windows applications; moreover, it can be used only when the remote computer has the Windows operating system. With the introduction of SOAP and the standardization of XML, Microsoft has realized a mechanism that substitutes DCOM – Web Services. Every personal computer connected to the Internet will be able to use Web Services using HTTP, SMTP, FTP, and other protocols. Based on text files (XML files) every operating system will be able to consume Web Services by simply creating SOAP consumer applications. A new programming era has just begun!



Microsoft is active on the Mobile front as well. It has just released the Pocket PC 2002 operating system for Mobile devices. Microsoft is convinced that Pocket PC, Handheld PC and Mobile Phones are the future of the personal communication and Compaq, Hewlett Packard and other companies are going to release their new mobile devices using the new operating system. Using these new devices will allow you to easily read e-mails, write documents and navigate through Internet sites. Users using Mobile devices can also consume Web Services using the Smart Device Extensions for Microsoft Visual Studio .NET that allows developers to create and deploy .NET Compact Framework applications for mobile devices.



In this article Fabio Claudio will show how to use these extensions to create a Pocket PC application that queries records from a remote Microsoft SQL Server 2000 database and consume a Web Service.

   
                   
    Article Discussion   Rate this article   Related Links   Index Entries  
   
 
    ARTICLE

This article is part of the ASPToday Mobile Theme Week, 28th Jan - 1st Feb 2002.

Introduction

With the release of Microsoft's .NET Framework comes the ability to create Web Services. Previously, DCOM was the unique solution to execute remote functions in the Windows operating system. DCOM is not the easiest protocol to implement in Windows applications; moreover, it can be used only when the remote computer has the Windows operating system. With the introduction of SOAP and the standardization of XML, Microsoft has realized a mechanism that substitutes DCOM - Web Services. Every personal computer connected to the Internet will be able to use Web Services using HTTP, SMTP, FTP, and other protocols. Based on text files (XML files) every operating system will be able to consume Web Services by simply creating SOAP consumer applications. A new programming era has just begun!

Microsoft is active on the Mobile front as well. It has just released the Pocket PC 2002 operating system for Mobile devices. Microsoft is convinced that Pocket PC, Handheld PC and Mobile Phones are the future of the personal communication and Compaq, Hewlett Packard and other companies are going to release their new mobile devices using the new operating system. Using these new devices will allow you to easily read e-mails, write documents and navigate through Internet sites. What about Web Services with mobile devices? Users using Mobile devices can consume Web Services? Yes, Microsoft has released the Smart Device Extensions for Microsoft Visual Studio .NET that allows developers to create and deploy .NET Compact Framework applications for mobile devices. Note: the SDE toolkit is not yet available for VS.NET final release so currently this application will only work on the RC1 release, but will be updated if necessary upon final release of SDE.

In this article we will see how to use these extensions to create a Pocket PC application that queries records from a remote Microsoft SQL Server 2000 database and consume a Web Service.

Microsoft .NET Compact Framework

The .NET Compact Framework was created with the idea to become a hardware-independent environment that could run on different Mobile devices such as Pocket PC, Handheld PC and Mobile Phones. It is a subset of .NET Framework classes that have been adapted in order to run on Mobile devices. Moreover, the Common Language Runtime engine has been rewritten in order to use and consume less system resources and every process has been isolated in order to not "disturb" the native applications running on the Mobile devices. Here follows a table summarizing the .NET Compact Framework features and some of the most important differences to the "parent" framework:

Feature Description
Assembly The .NET Compact Framework uses assemblies and portable executable files which contain intermediate language and metadata defining a .NET framework application.
Common Language Runtime (CLR) The .NET Compact Framework uses managed code through the CLR and the Common Language Specification just like the parent framework does.
Multiple language support Currently the .NET Compact Framework supports C#, J# and Visual Basic .NET, but more languages support is to come.
Threading model The .NET Compact Framework supports the same multithreaded programming model of the parent framework.
Networking The .NET Compact Framework supports TPC/IP protocol providing full access to HTTP and Web functionalities. Moreover, it has been provided for Infrared Data Association and socket support.
Memory management The .NET Compact Framework has been optimized to use minimal quantity of RAM and in particular cases ROM and hard disks (if present) to cache application's data.
Security The .NET Compact Framework uses a security model accessing to the code similar to the .NET Framework ones.
Difference Description
Classes The .NET Compact Framework uses a subset of classes respect to the .NET Framework. These classes are even less whether we develop application for Mobile Phones rather than Pocket PC.
I/O management Mobile devices manage files in different ways so the .NET Compact Framework has substantially differences with respect to the parent framework. For example, it is not possible retrieve a file change notification from the framework.

Naturally, there are two great features provided by the .NET Compact Framework that I haven't listed yet to give them a greater importance: the full support of Web Services and ADO.NET. After a brief analysis of the Smart Device Extensions for Visual Studio .NET we will see how to use these features to realize a Euro game application.

Installing the Smart Device Extensions

At the time of writing, Microsoft has released the .NET Compact Framework v. 1.0.3300 and the Smart Device Extensions Beta 1. Microsoft is going to improve hardly the framework and the extensions as well but using this release is sufficient to examine and study the news introduced by the .NET architecture.

The Smart Device Extensions are a set of templates and add-ins that provide all the necessary tools to create Pocket PC, Windows CE and Mobile Phones Windows application. Once installed in Visual Studio .NET it adds some templates to the New Project dialog box:

Image 1

Let's examine these templates in detail:

Once the project has been created you can start writing your code in the file source just like you would do with a Windows project. The big difference with standard applications is that you can't run them in the Windows operating system - the .NET Compact Framework applications have to be deployed on the target Mobile device. To save having to buy a range of different mobile devices we can use the Pocket PC and Mobile Phone emulators provided by the Smart Device Extensions. They are fully integrated with Visual Studio .NET allowing developers to test and debug their applications before deploying the application on physical devices. Also, Visual Studio .NET provides an automatic mechanism that initially deploys all the necessary files on the device and in the following installations just the files that are changed.

So before running the Mobile application we have to inform Visual Studio .NET about the device we want use to test our application on. This is accomplished by selecting the target device from the Device Extensions toolbar as shown in the next screenshot:

Image 2

The picture is taken from the Mobile Phone Application template that automatically inserts the .NET Device Emulator as the unique possibility to test and deploy the application, but you can also use other templates that allow developers to use either the emulator or the physical device as shown in the next screenshot:

Image 3

Perhaps the greatest feature provided by Visual Studio .NET is the possibility to remotely debug the application once it has been deployed on the device. Just like a Windows application, press the F5 key after having set a breakpoint and you will go through the code lines analyzing variables and data structures. Note that, unlike standard applications, the variable's content of the Mobile projects cannot be changed during the debug phase. In the following screenshot we can see the debugger ready to be used in the Pocket PC emulator:

Image 4

Note that sometimes Visual Studio .NET displays the following dialog box when you try to launch or debug the application:

Image 5

This could be a bug in the Beta 1 version because without changing the project settings and retrying to launch the application the application will be executed.

By default, Visual Studio .NET tries to connect to physical Mobile devices through the Microsoft Active Sync program. Using the Device Options you can customize this Visual Studio .NET behavior:

Image 6

Let's examine the dialog box fields:

The EuroGame Mobile device application

Twelve countries located in Europe are going to abandon their currencies replacing them with a unique currency: the Euro. The first months will be really puzzling for many people. Everybody will be trying to mentally convert every price with the old currency in order to have a tangible idea about it. What's better than a game on our Mobile device in order to training the mind? The rules are very easy; five questions with three possible answers. After having answered every question, a message box will be displayed with the final result. Moreover, the application will even provide a Euro converting utility - which will be useful in the early months of the this year.

User Interface

Once the application has been launched the main form will be displayed informing the user about the two possible choices:

Image 7

The main form is composed as follows:

As briefly mentioned in the previous section of the article, Visual Studio .NET doesn't implement the Designer tool so it is useful to place the windows controls over the form. We have to add the code for each control manually in the code source. So, let's see the code that creates the main form:

public class EuroGame : System.Windows.Forms.Form
{ 
      private Button btnOK;
      private Button btnEuroConverter;
      private Label lbRules;
      private RadioButton rbLira;
      private RadioButton rbMark;
      private RadioButton rbFranc;

      public EuroGame()
      {
             this.BackgroundImage = Image.FromFile(@"\Windows\back.jpg");

The main form uses a class derived from the System.Windows.Forms.Form namespace that has every method and property useful to create a Windows form in a Mobile device operating system. The constructor is the best place to initialize our components. The code starts by setting the background image with the back.jpg image file. You have to know that the Visual Studio .NET default settings will deploy the executable and resources files under the Windows Mobile device path. That's why the FromFile() method points to that directory.

            // Add a button to confirm the user choice
            btnOK = new Button();
            this.btnOK.Location = new System.Drawing.Point(25, 252);
            this.btnOK.Name = "btnOK";
            this.btnOK.TabIndex = 0;
            this.btnOK.BackColor = System.Drawing.Color.DarkGray;
            this.btnOK.Text = "Start game!";
            this.btnOK.Size = new System.Drawing.Size(80, 23);
            this.btnOK.Click += new System.EventHandler(this.btnOK_Click);

            this.Controls.Add(this.btnOK);

            // Add a button to launch the Euro Converter
            // Nothing different here.
            . . .

In the code snippet two buttons have been created. As you can see we have to specify the button size and position using the X and Y screen coordinates.

            // Add a label to inform the user about the game rules.
            lbRules = new Label();
            this.lbRules.Location = new System.Drawing.Point(40,25);
            this.lbRules.TabIndex = 1;
            this.lbRules.Size = new System.Drawing.Size(180, 100);
            this.lbRules.Text = "Select your currency and \npress the" + 
                                "Start Game button.\nTry to answer" + 
                                "correctly\nto the questions!!!\n\tGood" + "luck!";
            this.lbRules.BackColor = System.Drawing.Color.Transparent;

            this.Controls.Add(this.lbRules);

Then the code goes through the creation of the label used to inform the user about the game rules.

      // Add three currency options
      rbLira = new RadioButton();
      this.rbLira.BackColor = System.Drawing.Color.Transparent;
      this.rbLira.Checked = true;
      this.rbLira.Location = new System.Drawing.Point(72, 144);
      this.rbLira.Name = "rbLira";
      this.rbLira.Size = new System.Drawing.Size(112, 24);
      this.rbLira.TabIndex = 2;
      this.rbLira.TabStop = true;
      this.rbLira.Text = "Italian Lira";

      this.Controls.Add(this.rbLira);

      // The same for the other two radio buttons
      . . .
      }
}

Finally, the code creates three radio buttons placing them in the middle of the form.

Tip: if you don't want to manually calculate the control's size and position you can create a Windows application project, resize the main form to the standard Mobile windows dimensions (width=240 pixels, height=300 pixels) and place the controls over that form. You can then simply copy the generated code from the Windows source code into the Mobile device application project.

Accessing the SQL Server 2000 database

In order to show you how easy querying data from a remote database is, I've implemented a method that retrieves a DataSet filled with the five questions. The RetrieveQuestions() method contacts SQL Server 2000 using its new XML features through the HTTP protocol. Simply adding the FOR XML AUTO instruction to the standard SQL query, Microsoft SQL Server 2000 will produce an XML file filled with the query results. We can use the XML capabilities inserted in the DataSet to manage this data.

The EuroGame database comprises of two tables: tabCurrency and tabQuestion. The former contains the information about the currencies while the latter contains five questions for each currency, the three possible answers and the right answer.

Image 8

Let's see the code that retrieves data from the database:

private void RetrieveQuestions()
{
string strSQL = "http://192.168.254.1/EuroGameDB?SQL=SELECT * FROM tabQuestion WHERE
 ID_Currency=" +	this.iCurrency.ToString() + " FOR XML AUTO, ELEMENTS," +
 "BINARY BASE64&root=root";

The code starts creating the SQL instruction to retrieve the questions from the database. The string will contain the URL to contact the remote SQL Server database passing through the Internet Information Services service. Using the Configure SQL XML Support in IIS application provided by Microsoft SQL Server 2000 you will be able to create a virtual directory ( EuroGameDB) pointing to the data source. Please, read the readme.txt file provided with the code example to learn more on installing that virtual site.

      StreamReader sXMLReader = null;
      Stream sDB = null;

      try
      {
            Uri uriDB = new Uri(strSQL);

A Uri object is used to transform the string in a valid URL.

            HttpWebRequest reqDB = (HttpWebRequest)WebRequest.Create(uriDB);
            WebResponse resp = reqDB.GetResponse();

An HttpWebRequest object is then used to get the response from the Web server. Using the GetResponse() method provided by the HttpWebRequest you will be able to retrieve a WebResponse object to retrieve the XML file.

            sDB = resp.GetResponseStream();
            sXMLReader = new StreamReader (sDB, System.Text.Encoding.UTF8);

            this.dsQuestions.ReadXml(sXMLReader);

The GetResponseStream() method provided by the WebResponse class retrieves a Stream class object filled with the XML text. We have just to read it using the ReadXml() method of the DataSet class in order to consume the database records.

      }
     catch
     {
              MessageBox.Show ("Error in reading data from the server.", "EuroGame");
     }
     finally
     {
              if (sXMLReader != null)
                    sXMLReader.Close();
              if (sDB != null)
                    sDB.Close();
     }
}

The code ends closing the streaming objects. As you can see, the catch instruction doesn't use any Exception class object. In fact, the .NET Compact Framework doesn't provide a full implementation of exception messages.

Consuming the Euro Converter Web Service

The available Web Services on Internet are growing every day so it's even easier finding just the service we were looking for. Consulting the UDDI directory at the http://uddi.microsoft.com/visualstudio/?WROXEMPTOKEN=312162ZoxbYrFkkMwEjUzxKd5k site you can find a lot of available services that you can insert in your code. Another good site, where I found the Euro Converter service, is the Xmethods site (http://www.xmethods.net/?WROXEMPTOKEN=312162ZoxbYrFkkMwEjUzxKd5k) that displays a list of different Web services.

In order to use a Web Service in our Mobile device project we have to select Add Web References. from the Project menu. In the following screenshot is displayed the dialog box where we have to specify the URL of the web service we want use in our project:

Image 9

The URL specified in the Address: combo box points to the Dr.Bob site offering the Euro Converter Web Service. By pressing the Add Reference button a new class will be added to the project: uk.co.drbob42.www.IEuroservice. The class will provide two methods to convert from Euro to the specified currency, FromEuro() , and vice versa, ToEuro(). Let's see the implementation in the example code:

protected void btnConvert_Click (object sender, System.EventArgs e)
{
      if (Convert.ToDouble(this.txtAmount.Text) > 0)
      {
            uk.co.drbob42.www.IEuroservice EUService = new uk.co.drbob42.www.IEuroservice();
            double dResult = 
            EUService.ToEuro(this.cmbCurrency.SelectedItem.ToString(),
            Convert.ToDouble(this.txtAmount.Text));

            MessageBox.Show(Decimal.Round(Convert.ToDecimal(dResult),2).ToString(), "Result");
      }
      else
            MessageBox.Show("Please, insert a valid value in the amount" + "field", "Error");
      }
}

The code checks for a valid value in the Amount text field and then create a new object from the referenced class. Finally, the ToEuro() method is called providing the currency string name and the currency double value. The returned value is rounded to the first two decimal digits and displayed into a message box.

Summary

In this article we have had a look at Smart Device Extensions for Microsoft Visual Studio .NET and seen how theycan be used to create a Pocket PC application that queries records from a remote Microsoft SQL Server 2000 database and consume a Web Service.

You can find a lot of information and post your questions on the mobile lists available at http://p2p.wrox.com/mobile/?WROXEMPTOKEN=312162ZoxbYrFkkMwEjUzxKd5k and for further reading please also check out the Wrox publication ASP.NET Mobile Controls.

Article Information
Author Fabio Claudio Ferracchiati
Technical Editors John R. Chapman, Vickie Pring
Author Agent Charlotte Smith
Project Manager Helen Cuthill
Reviewers Brady Gaster, Vikram S

If you have any questions or comments about this article, please contact the technical editor.

 
 
   
  RATE THIS ARTICLE
  Please rate this article (1-5). Was this article...
 
 
Useful? No Yes, Very
 
Innovative? No Yes, Very
 
Informative? No Yes, Very
 
Brief Reader Comments?
Your Name:
(Optional)
 
  USEFUL LINKS
  Related Tasks:
 
 
   
  Related ASPToday Articles
   
  • Creating Mobile applications with Microsoft Mobile Internet Toolkit and Visual Studio .NET (February 1, 2002)
  • Adding .NET Mobile Controls Capability to an Existing ASP 3.0 Website (January 31, 2002)
  • Web Page Display on Pocket PC Devices (January 29, 2002)
  • Using Web Services to Create a Personal Mobile Site (January 28, 2002)
  • Returning XML from SQL Server 2000 using ADO (November 29, 2000)
  •  
           
     
     
      Related Sources
     
  • Smart Device Extensions: http://msdn.microsoft.com/vstudio/device/smartdev.asp
  • UDDI Directory: http://uddi.microsoft.com/visualstudio/
  • XMethods Web Services : http://www.xmethods.net/
  •  
     
           
      Search the ASPToday Living Book   ASPToday Living Book
     
      Index Full Text Advanced 
     
     
           
      Index Entries in this Article
     
  • .NET Compact Framework
  •  
  • .NET Framework
  •  
  • accessing database
  •  
  • Add Web Reference option
  •  
  • ADO.NET
  •  
  • AUTO mode
  •  
  • consuming web service from mobile devices
  •  
  • Dataset object
  •  
  • DCOM
  •  
  • debugging mobile applications using Visual Studio .NET
  •  
  • description
  •  
  • device extensions
  •  
  • Euro Converter web service
  •  
  • EuroGame mobile application
  •  
  • FOR XML clause
  •  
  • form class
  •  
  • GetResponse method
  •  
  • GetResponseStream method
  •  
  • HTTPWebRequest object
  •  
  • HTTPWebResponse object
  •  
  • installing
  •  
  • mobile applications
  •  
  • Mobile Devices
  •  
  • mobile web application project
  •  
  • Pocket PC devices
  •  
  • ReadXML method
  •  
  • smart device extensions
  •  
  • SQL Server
  •  
  • System.Windows.Forms namespace
  •  
  • templates
  •  
  • user interface
  •  
  • Visual Studio .Net
  •  
  • web service
  •  
  • WinForms
  •  
     
     
    HOME | SITE MAP | INDEX | SEARCH | REFERENCE | FEEDBACK | ADVERTISE | SUBSCRIBE
    .NET Framework Components Data Access DNA 2000 E-commerce Performance
    Security Admin Site Design Scripting XML/Data Transfer Other Technologies

     
    ASPToday is brought to you by Wrox Press (http://www.asptoday.com/OffSiteRedirect.asp?Advertiser=www.wrox.com/&WROXEMPTOKEN=312162ZoxbYrFkkMwEjUzxKd5k). Please see our terms and conditions and privacy policy.
    ASPToday is optimised for Microsoft Internet Explorer 5 browsers.
    Please report any website problems to webmaster@asptoday.com. Copyright © 2002 Wrox Press. All Rights Reserved.