Quantcast
Channel: Envato Tuts+ Code - Mobile Development
Viewing all articles
Browse latest Browse all 1836

Connecting to an External Database With NuSOAP

$
0
0

Many mobile applications use external databases that are located remotely on the Internet. In the following tutorial, we will create a simple database, connect to it, and receive or send data from this source. To do this we will use a Windows Phone 7 Silverlight based application and a NuSOAP web service. Let’s begin!


1. Install the Software

Before we start we need to install the following programs:

Obviously, we will also need some sort of web hosting where we can create a database. Most of the free hosting options will be enough for us, but they may have some limitations which I will discuss later on in this tutorial.

We also need an FTP client. In this tutorial I will use a FireFTP add-on to Mozilla Firefox. But you can use anything you want.

When all the programs are installed, we can continue.


2. Creating an External Database

Step 1

To begin, check that the hosting uses phpMyAdmin because I use it in the examples. But if you choose to use something else all the commands should be similar.

First we need to create a simple database, in our case it will contain only one table and three attributes:

  • ID– this value identifies the record. It must be set as an autoincrement field.
  • FirstName
  • LastName

The table name is MyUsers.

To do this just click “create table”:

Step 2

After that, fill in the cells as shown in this screenshot:

The table structure should now look like this:

Step 3

At this step we must note a few important points:

  • Host address

As I wrote earlier, free hostings have limits, one of these is to possibly connect only from localhost, remember that!

  • Database user

Our username to log into the database:

  • Database password
  • Database name

3. NuSOAP Server – Starting Web Service

Step 1

Starting our web service is very simple:

First, we must copy some files to the ftp server. I recommend a ftp server because it is directly connected to our hosting because of the localhost issue.

Once we’re connected, we need to copy the nusoap.php file which was downloaded earlier. We also require a file that will contain specific functions written by us that is necessary for our application; I called it MyService.php.

Step 2

After we copy the files, our FTP root directory should look like the image below:

Now open the MyService.php file and write into it:

<?php
// Pull in the NuSOAP
code require_once('nusoap.php');
// Create the server instance
$server = new soap_server();
// Initialize WSDL support
(MyService is name of our service)
$server----->configureWSDL('MyService', 'urn:MyService');
        // Character encoding
        $server->soap_defencoding = 'utf-8';
        //-------------------------------------------------
        //Registrations of our functions
        //-------------------------------------------------
        //Our web service functions will be here.
        //-------------------------------------------------
        $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
        $server->service($HTTP_RAW_POST_DATA);
?>

The most important points are explained in the upper comments to code.

Step 3

From now on our service should work. We can check this by typing in the web browser:

http://www.ourdomain.com/MyService.php

If all went well you should see something like this:

After we successfully started the web service, we can go to the next step.


4. Writing Web Service Functions

In our service we need two functions:

  • The first function adds data to the online database.
  • The second function receives data from it.

Step 1

Let’s open MyService.php. We need to register the new function, to do this we should type:

    $server->register(
        'InsertData',   //Name of function
      	array('FirstName' => 'xsd:string', 'LastName' => 'xsd:string'), //Input Values
      	array('return' =>'xsd:boolean'), //Output Values
    	  'urn:MyServicewsdl',  //Namespace
        'urn:MyServicewsdl#InsertData',  //SoapAction
        'rpc',       //style
        'literal',   //can be encoded but it doesn't work with silverlight
        'Some_comments_about_function'
    );

Remember that it needs to be placed before the body function and after the server directives.

Here is some code explanation:

      'FirstName' => 'xsd:string'

“FirstName” is the name of variable, “string” is the type of variable (i.e. it can be int, longint, boolean, etc.).

When the function registers, we need to write the body of it. Below is the code and explanation:

    function InsertData($FirstName, $LastName) {
    	$connect = mysql_pconnect("Host","UserName","UserPassword"));
    	if ($connect) {
    		if(mysql_select_db("DatabaseName", $connect)) {
          mysql_query("INSERT INTO MyUser SET FirstName='$FirstName', LastName='$LastName'");
    			return true;
    		}
    	}
    	return false;
    }
          InsertData($FirstName, $LastName)

Here’s the name of the function and its attributes. They must be the same as in the registration section.

          $connect = mysql_pconnect("Host","UserName","UserPassword");

Here we can insert the data we noticed when we created the database.

          if(mysql_select_db("DatabaseName", $connect)) {

And also here.

After that it is a simple MySQL query that adds data to our database:

          mysql_query("INSERT INTO MyUser SET FistName='$FirstName', LastName='$LastName'");

Step 2

Now it’s time to write the second function. The structure will be similar to the first.

Here is the code of method registration:

      $server->register(
          'GetData',
        	array('ID' => 'xsd:int'),
        	array('return' =>'xsd:string'),
      	  'urn:MyServicewsdl',
          'urn:MyServicewsdl#GetData',
          'rpc',
          'literal',
          'Some comments about function 2'
      );

The main differences are in the Input/Output values section (changed types of variables).

Here’s the body function code:

       function GetData($ID) {
      	$connect = mysql_pconnect("Host","UserName","UserPassword");
      	if ($connect) {
      		if(mysql_select_db("DatabaseName", $connect)) {
            $sql = "SELECT FirstName, LastName FROM MyUser WHERE ID = '$ID'";
      			$result = mysql_fetch_array(mysql_query($sql));
      			return $result['FirstName']."-".$result['LastName'];
      		}
      	}
      	return false;
      }

Here is a little code explanation:

         return $result['FirstName']."-".$result['LastName'];

This line states what must return to the Windows Phone application.

Step 3

After writing all the functions the MyService.php file should look like this:

<?php
// Pull in the NuSOAP code
require_once('nusoap.php');
// Create the server instance
$server = new soap_server();
// Initialize WSDL support
configureWSDL('MyService', 'urn:MyService');
                // Character encoding
                $server->soap_defencoding = 'utf-8';
                //-------------------------------------------------
                //Register InsertData function
                $server->register(
                        'InsertData',
                      	array('FirstName' => 'xsd:string', 'LastName' => 'xsd:string'),
                      	array('return' =>'xsd:boolean'),
                    	  'urn:MyServicewsdl',
                        'urn:MyServicewsdl#InsertData',
                        'rpc',
                        'literal',
                        'Some comments about function'
                    );
                //Register GetData function
                $server->register(
                        'GetData',
                      	array('ID' => 'xsd:int'),
                      	array('return' =>'xsd:string'),
                    	  'urn:MyServicewsdl',
                        'urn:MyServicewsdl#GetData',
                        'rpc',
                        'literal',
                        'Some comments about function 2'
                    );
                //-------------------------------------------------
                //Body InsterData function
                function InsertData($FirstName, $LastName) {
                	$connect = mysql_pconnect("Host","UserName","UserPassword");
                	if ($connect) {
                		if(mysql_select_db("DatabaseName", $connect)) {
                      mysql_query("INSERT INTO MyUser SET FirstName='$FirstName', LastName='$LastName'");
                			return true;
                		}
                	}
                	return false;
                }
                //Body GetData function
                function GetData($ID) {
                	$connect = mysql_pconnect("Host","UserName","UserPassword");
                	if ($connect) {
                		if(mysql_select_db("DatabaseName", $connect)) {
                      $sql = "SELECT FirstName, LastName FROM MyUser WHERE ID = '$ID'";
                			$result = mysql_fetch_array(mysql_query($sql));
                			return $result['FirstName']."-".$result['LastName'];
                		}
                	}
                	return false;
                }
                //-------------------------------------------------
                $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
                $server->service($HTTP_RAW_POST_DATA);
        ?>

To validate the functions we can again type http://www.ourdomain.com/MyService.php in the browser. Now the site should look a little bit different, but similar to this:

Now we’re ready to go to next step.


5. Creating a Simple Layout for a Windows Phone Application

Step 1

Firstly, we must create a Windows Phone app. Let’s run Microsoft Visual Studio for Windows Phone 2010. After Visual Studio starts, click “File” then “New Project”. You should see a dialog window like in the screenshot below:

Our app will use Silverlight, so we must check this template. We can also change the project name, like localisations, etc. In my case, the project name is “MyApplication”. After you have done this, click the OK button.

Step 2

At this point we must note what we need in our app. We need:

  • Two text boxes for sending data to the database (First Name, Last Name)
  • One text box to receive the data (ID)
  • Two buttons to approve our actions

Adding objects (such as buttons) to our application is easy, just drag it from “ToolBox” and drop it onto preview of the app. Keep in mind that you have a free hand in setting your own layout.

This is how it looks on my app:

Another important aspect is the names of the elements used in Visual Studio (they’re used later in code).

To change it, just click on element. Then in properties you can see text like “Textbox1″, click on it, and change it to something that you can remember, that is crucial. I used these names for my elements:

  • “FirstNameBox”, “LastNameBox”, and “IdBox” for text boxes
  • “SendBTN” and “ReadBTN” for buttons

That’s all we need to do in this step, we can move on.


6. Connecting to Service

To connect to the web service we must right click on “Reference” in “Solution Explorer” dialog and select “Add Service Reference…”

Here how this looks:

After that a new window will appear. In it we must write the address of our web service and the name of namespace.

In our case an address will be created, like on this scheme: http://www.ourdomain.com/MyService.php?wsdl.

After entering an address and clicking “Go” you should see something like this:

If you see the operations called “GetData” and “InsertData” that means the connection was successfully created! Remember to type namespace, in my case it is “MyService”. Now click OK.


7. Writing Windows Phone Functions

We’re almost at the end of this tutorial; we only need to write two simple functions.

Step 1

The first function will be behind the “Send” button, so double click it. Now we must add at the top of the file a “using” directive of our service:

      using MyApplication.MyService;

Let’s look at the send function behind the “Send” button, now it is empty:

        private void SendBTN_Click(object sender, RoutedEventArgs e)
        {
        }

Our complete function should look like this:

        private void SendBTN_Click(object sender, RoutedEventArgs e)
        {
            //Creating new proxy object of our service
            MyServicePortTypeClient send = new MyServicePortTypeClient();
            send.InsertDataCompleted += new EventHandler<InsertDataCompletedEventArgs>(send_InsertDataCompleted);
            //Calling method, as a parameters we type text contained in FirstNameBox and LastNameBox
            //This data will be sent to web service and later to database
            send.InsertDataAsync(FirstNameBox.Text, LastNameBox.Text);
        }
        void send_InsertDataCompleted(object sender, InsertDataCompletedEventArgs e)
        {
            //If our server return true, that means we're added data to database...
            if (e.Result)
                MessageBox.Show("Successfully added!");
            //...if return false we aren't.
            else
                MessageBox.Show("Some problems occured!");
        }

The most important points are explained in the code comments, but we must be aware of the following:

Method “send_InsertDataCompleted” executes when we get an answer from the server. Also this function is not in the “SendBTN” object, it is outside.

Now it’s time to test our work! Start to debug and fill out the boxes with some data. Here I have entered John as a first name and Doe as a last name, then I clicked Send:

Let’s see how the database looks now:

Yes, the new record with ID = 1 has appeared and everything is going well.

Step 2

Now we’ve reached the final function for receiving. It is similar to the previous method. Double click on the “Read” button and copy the code:

      private void ReadBTN_Click(object sender, RoutedEventArgs e)
        {
            //Creating new proxy object of our service
            MyServicePortTypeClient read = new MyServicePortTypeClient();
            read.GetDataCompleted += new EventHandler<GetDataCompletedEventArgs>(read_GetDataCompleted);
            //Calling method, as a parameters we type text contained in IdTextBox
            //but we must change text type of string to integer (ID in web service have integer type)
            read.GetDataAsync(Convert.ToInt32(IdBox.Text));
        }
        void read_GetDataCompleted(object sender, GetDataCompletedEventArgs e)
        {
            MessageBox.Show(e.Result);
        }

This is the same process as before, “read_GetDataCompleted” executes after getting data from the database. In this method we’ll use a message box to show our result, i.e. first and last name. There is one more step to do; we need to change the type of text in IdBox from string to integer because the variable called ID in the web service has an integer type. To do this I used a function called “Convert.ToIn32()”


8. Testing

Now we can see if this works. Enter ID into “IdTextBox”. I entered “1″, then clicked the “Read” button.

Everything is working! Our application is now complete!


Conclusion

In this tutorial we created a database using a Windows Phone 7 Silverlight based application and NuSOAP web service. This database is helpful to receive or send data. External databases are important because they are used by many mobile applications.


Viewing all articles
Browse latest Browse all 1836

Trending Articles