RSS

Monthly Archives: September 2009

Building Web Services Using NuSOAP Toolkit

Introduction
SOAP or “Simple Object Access Protocol” has built his concept on XML-RPC, but provides much richer features sets. In this article we are going to build a simple SOAP server and client which will use our new service.
You should know what SOAP is (SOAP packet structure), but purpose of this article is to show programmers how easy is to build web services (SOAP). Even if you don’t know XML, SOAP, WSDL, the only requirement is basic XML knowledge. But if you’re interested, you can find some nice tutorials on http://www.w3schools.com (XML,SOAP), http://www.xml.com, http://www.w3.org/TR/SOAP.
PHP and SOAP
PHP (for now) doesn’t have a SOAP extension, but there are some nice PHP SOAP toolkits. You can even use XML-RPC PHP extension, where you can, by using optional argument (“version”), specify which protocol to use (“soap 1.1.”. However, you need to take care of data transmitting across the network, where PHP toolkit takes care of that.
NuSOAP Toolkit
NuSOAP (formerly SOAPx4) is a toolkit which provides simple API for building web services using SOAP. There are also some other toolkits like PEAR:SOAP (also stable). NuSOAP current version is 0.6.4, which provides simple API for making SOAP server/client applications and also supports features like WSDL generation, building proxy class, using SSL, using HTTP proxy, HTTP authentication. So download current NuSOAP toolkit from cvs.sourceforge.net/viewcvs.py/nusoap/lib/ and lets get started.
The Story
Let’s assume the existence of a government department which performs weather measurements. They want their data to be publicly accessible. So basically let’s assume that they have for each city (worldwide) a current degrees measurements and a basic weather forecast.
First we create a simple MySQL table (current_data):
 CREATE TABLE current_data (
    id int(10) unsigned NOT NULL auto_increment,
    city varchar(20) default NULL,
    degrees float NOT NULL default '0',
    forecast varchar(255) default NULL,
    PRIMARY KEY  (id),
    UNIQUE KEY city (city),
    KEY city_2 (city)
  ) TYPE=MyISAM;
 
And let’s fill it with some test data:
 INSERT INTO current_data VALUES (1, 'Chicago', '5',  'Partly cloudy.');
 INSERT INTO current_data VALUES (2, 'London',  '15',
 'Sun along with patchy clouds.');
 
Our server is going to create the web service. We will register one method (getWeather) which will accept a string (city) and return an array with degrees measurement and weather forecast.
First we need NuSOAP toolkit (nusoap.php), which we’ll be in our “inc” directory so that we can easily include it. So let’s look at the actually needed code:
<?php
 /**************************************************************
 *  Description:
 *  Creates a simple SOAP Server (server.php).
 **************************************************************/

 // includes nusoap classes
 require('inc/nusoap.php');

 // create server
 $l_oServer = new soap_server();

 // wsdl generation
 $l_oServer->debug_flag=false;
 $l_oServer->configureWSDL('Weather', 'http://weather.org/Weather');
 $l_oServer->wsdl->schemaTargetNamespace = 'http://weather.org/Weather';

 // add complex type
 $l_oServer->wsdl->addComplexType(
 'WeatherData',
 'complexType',
 'struct',
 'all',
 '',
 array(
 'degrees' => array('name'=>'degrees', 'type'=>'xsd:string'),
 'forecast' => array('name'=>'forecast', 'type'=>'xsd:string'))
 );

 // register method
 $l_oServer->register('getWeather', array(
 'city' => 'xsd:string'),
 array('return'=>'tns:WeatherData'),
 'http://weather.org/Weather');

 // method code (get DB result)
 function getWeather ($a_stInput) {
 if (is_string($a_stInput)) {
 $l_oDBlink   = @mysql_connect(
 'localhost', 'someone', 'something');
 $l_oDBresult = @mysql_db_query(
 'weather',
 'SELECT degrees, forecast FROM current_data WHERE city = LCASE("' . mysql_escape_string((string)$a_stInput) . '") LIMIT 1');

 // simple error checking
 if (!$l_oDBresult) {
 return new soap_fault('Server', '', 'Internal server error.');
 }

 // no data avaible for x city
 if (!mysql_num_rows($l_oDBresult)) {
 return new soap_fault('Server', '',
 'Service contains data only for a few cities.');
 }
 mysql_close($l_oDBlink);

 // return data
 return mysql_fetch_array($l_oDBresult, MYSQL_ASSOC);
 }
 // we accept only a string
 else {
 return new soap_fault('Client', '', 'Service requires a string parameter.');
 }
 }

 // pass incoming (posted) data
 $l_oServer->service($HTTP_RAW_POST_DATA);
?>
So let’s go line by line. First, we obviously include NuSOAP toolkit. For a server we need to create “soap_server” object. We don’t need debug messages, so we turn them off.
At line 15 we start to generate WSDL file. WSDL is “Web Services Description Language”, which is a XML-based language. This file basically describe web service and let us know how to use web service (access it). For a simple example we don’t need to generate WSDL file, but I’m also going to show you how you can use WSDL file to create “proxy class”. We configure target namespace and create (simple) complex type, which is our returned data. It’s a struct with two data rows, degree and forecast.
And finally we register “getWeather” method, so it can be called by a client, and we also define our complexType (WeatherData) for return value. What follows is the actual “getWeather” function (line 32). First we check if argument is a string and return “soap_fault” if it’s not (line 53). Our string parameter (city) is used in SQL query, where we hopefully get some data. In case of error, or if there is no data accessible, we also return “soap_fault”. If we got some data from the database, we return it like associated array (our complexType).
And on line 58 we pass to our service incoming data ($HTTP_RAW_POST_DATA). By the way, $HTTP_RAW_POST_DATA is only set if type of the data is unknown. So that’s our web service, ready to be used. There are some WSDL stuffs that I also want to mention, but we will cover that at the end.
<?php
 /**************************************************************
 *  Description:
 *  Creates a simple SOAP Client (client.php).
 **************************************************************/

 // use form data
 if ((string)$_GET['action'] == 'get_data') {
 // includes nusoap classes
 require('inc/nusoap.php');

 // set parameters and create client
 $l_aParam   = array((string)$_POST['city']);
 $l_oClient  = new soapclient('http://somewhere.org/soap/server.php');

 // call a webmethod (getWeather)
 $l_stResult = $l_oClient->call('getWeather', $l_aParam);

 // check for errors
 if (!$l_oClient->getError()) {
 // print results
 print '<h1>Current data for: '    . $l_aParam[0]
 . ':</h1><ul><li>DEGREES: '   . $l_stResult['degrees']
 . '&deg;C</li><li>FORECAST: ' . $l_stResult['forecast']
 . '</li></ul>';
 }
 // print error description
 else {
 echo '<h1>Error: ' . $l_oClient->getError() . '</h1>';
 }
 }

 // output search form
 print '
 <form name="input" action="'.$_SERVER['PHP_SELF'].'?action=get_data"  method="POST">
 Your city: <input type="text" name="city">
 <input type="submit" value="Search">
 </form>
 ';
?>
Building Web Services Using NuSOAP Toolkit
For getting input parameter we output a simple form (city is a text input). If some data was sent, we then include NuSOAP toolkit. First we put string parameter into array, so that we can use it for calling webmethod. For a client we create object “soapclient” (argument is URL to the server) at line 14. With created client we can call our webmetod “getWeather” and we pass the parameter (form data in array).
And that’s all. Finally we only need to check for errors (line 20) and if there’re no errors we simple output data (lines 22-25). We have just created a simple SOAP client, with just a few line of code.
SOAP Client Using WSDL
With the above example we have created a simple SOAP client. We can also use WSDL to create proxy class, which will hold method (getWeather) of our web service. So basically the programmer only needs to know webmethods name and required parameters, and all this can be retrieved from WSDL. We can save WSDL file localy and use it. So let�s make a SOAP client using WSDL (look at server code to see how we generated WSDL).
<?php
 /**************************************************************
 *  Description:
 *  Creates a simple SOAP Client using WSDL (client_wsdl.php).
 **************************************************************/

 // use form data
 if ((string)$_GET['action'] == 'get_data') {

 // includes nusoap classes
 require('inc/nusoap.php');

 // set parameters and create client
 $l_oClient = new soapclient(
 'http://somewhere.org/soap/weather.wsdl', 'wsdl');
 $l_oProxy  = $l_oClient->getProxy();

 // call a webmethod (getWeather)
 $l_stResult = $l_oProxy->getWeather((string)$_POST['city']);

 // check for errors
 if (!$l_oClient->getError()) {
 // print results
 print '<h1>>Current data for: '  . (string)$_POST['city']
 . ':</h1><ul><li>DEGREES: '   . $l_stResult['degrees']
 . '&deg;C</li><li>FORECAST: ' . $l_stResult['forecast']
 . '</li></ul>';

 }
 // print error description
 else {
 echo '<h1>Napaka: ' . $l_oClient->getError() . '</h1>';
 }
 }

 // output search fclientorm
 print '
 <form name="input" action="'.$_SERVER['PHP_SELF'].'?action=get_data"  method="POST">
 Your city: <input type="text" name="city">
 <input type="submit" value="Search">
 </form>
 ';
?>
So where’s the difference? When we’re creating “soapclient” object we now pass URL to the WSDL file (second argument tells the client that we are using WSDL). Next we generate proxy class (line 15); we simply call “getProxy” method and that’s all.
Now we have in our proxy class all the methods that our web service has. So we can “locally” access “getWeather” method, which sends and returns data from web service. Lastly, we do the same error checking just like in previous client.
I have told you that you can get all the needed data from WSDL (webmethod name and required parameter). You can take a look at WSDL file, which is accessed from http://somewhere.org/soap/server.php?wsdl (use parameter wsdl), but if you go to http://somewhere.org/soap/server.php you will get nice GUI which tells us accessible methods and required parameters. This GUI and WSDL is created by NuSOAP toolkit, it’s accessible because we generated WSDL in the server.
Conclusion
This was just a simple example of using SOAP with NuSOAP toolkit. You could build the same system using XML-RPC or WDDX but SOAP has some other “goodies” like advance error checking, XSD validation and other cool stuff. You can also just use web service (there are some good web services resources like http://www.xmethods.com). So dig into SOAP and NuSOAP API documentation.
You can download the full source code here.

Advertisements
 
Leave a comment

Posted by on September 29, 2009 in PHP

 

Web Services Implementation using PHP and SOAP

Introduction to Web Services
Web Services is a system which enables and supports interoperability. It enables applications written in different languages, located in different places, running on different operating systems, to talk to each other, exchange information and perform different operations. The building blocks of Web Services are a set of XML based standards namely SOAP (Simple Object Access Protocol), WSDL (Web Services Description Language) and UDDI (Universal Description, Discovery, and Integration).
The above diagram is the simplest diagram which can help you visualize web services, and shows how two remote applications can interact with each other using web services. The protocol used for this remote interaction is SOAP.
Simple Object Access Protocol (SOAP)
SOAP is a lightweight protocol for the exchange of information in a distributed environment. It is an XML-based protocol. The most important aspect of SOAP is its simplicity and extensibility. A SOAP message contains data in the form of XML. SOAP consists of three parts:

  1. It is a framework for describing what is in a message and how to process the message
  2. It is a set of Encoding rules
  3. It is a convention for representing remote procedure calls (request and response)
PHP and web Services
PHP is a widely used general purpose scripting language. It is basically a procedural language, but it has the capabilities of an object oriented language also. Its syntax is similar to Perl, C, Java, etc. It can be very easily embedded in the HTML which makes web developement using PHP very easy. Some of the features of PHP which enhanced its capability for Web services development are discussed below.
Object Oriented Programming Capabilities
  • PHP supports XML
  • The CURL Extension of PHP (Client URL Library) allows us to communicate via different protocols such as HTTP, HTTPS, FTP, Telnet, LDAP).
  • The most important feature of PHP is it enables the open source web services implementation.
PHP Web Services using NuSoap
NuSoap is a group of PHP classes that allow us to send and receive SOAP messages over HTTP. You can download this nusoap.php library from http://www.nusphere.com. It is open source, licensed under the GNU LGPL. Once you have downloaded nusoap.php, you simply need to place it anywhere you like on your machine, but don’t forget to include the path of this file while including this file in your php code. I will suggest that you to keep it in the same work folder in which your code is located. To include NuSoap classes in our code:
include ("nusoap.php");

If the path of the nusoap.php file (which can be absolute or relative) is incorrect, the above-mentioned code will generate a warning but will continue the processing of the rest of the code. We can also use below-mentioned function as required.

  • require() :-it is similar to the include function but it will make the program halt in case of failure.
  • require_once() :- it is similar to require(), it won’t include the file if it has already been included.
  • include_once() :- similar to include(), it wont include if the file is already included.
Simple PHP SOAP Client Example

Below is the sample code for the client which sends the request to the remote server for validating the string, which is passed as a parameter to the server.

<?PHP
 require('nusoap.php');

 $str = 'Hello World';
 $strAr = array($str);

 $s = new soapclient('http://localhost/work_dir/validateStr.php');

 $result = $s->call('validateStr', $strAr);

 if(!$error = $s->getError())
 {
   echo 'String:' . $result;
 }
 else
 {
   echo 'Error:' . $error;
 }
?>

Code walk through

include ("nusoap.php");

Now we will see how the above code is processed. The above code shows how the client sends data to the server to validate it if it’s a valid string.

$string =’Hello World’;

This includes the NuSoap classes to the code:

$stringArray = array($string);

Create a variable for the string which you want to send to server. The parameter must be passed as an array to the SOAP client.

$s= new
soapclient(‘http://localhost/working_directory/validateString.php’);

The above code instantiate the SOAP client. Local host is used since the client and server code both are present on the same machine. If the server code is on a remote machine then the correct path of the validateString.php needs to be provided in the soap client.

$result =$s->call (‘validateString’,$stringArray);

This call method tells the soap client which service we want to access and passes the string array to the server and the method. The resulting variable stores the response from the server.

if(!$error = $s->getError()) {
echo ‘String : ‘ .$result;
}
else {
echo ‘Error:’ .$error;
}

We will be checking the error using getErrror() method. If an error occurs this method returns the string description of the error, otherwise it returns false. In the above code we are printing our result in case of success, otherwise we print the error detail.

<? php
require(‘nusoap.php);
$s= new soap_server;
$s->register(‘validateString’);
function validateString($stringValue) {
if( is_string($stringValue) {
return $stringValue;
else {
return new soap_fault(‘Client’,’’.’This is not a valid string.’);
}
}
$s->service($HTTP_RAW_POST_DATA);
?>

Simple PHP SOAP Server Example

$s= new soap_server;

Code walk through
First we instantiate the soap server using the soap_server class.

$s->register(‘validateString’);

To allow our function to be called from remote location, we need to register it with server object.

function validateString($stringValue) {
if( is_string($stringValue) {
return $stringValue;
else {
return new soap_fault(‘Client’,’’.’This is not a valid string.’);
}
}

Next we have a function definition which checks if the parameter passed to the function is a validate string or not.

$s->service($HTTP_RAW_POST_DATA);

If the input string is a valid string then it will return the string, otherwise it will return the error using soap_fault class. Finally the above method passes the incoming data from the remote client to the SOAP server’s service method. This service method processes the incoming request and calls the appropriate method.
Summary
Using PHP and NuSoap, we can develop robust and interoperable Web Services. In the above example we have seen how PHP consumes and deploys web services with SOAP. In the current scenario we have used local host but actually we can place our client and server code on different machines in the network and check the code in a distributed system.

referrence website: http://www.phpbuilder.com/columns/rajeev_rakesh_20071024.php3

 
1 Comment

Posted by on September 29, 2009 in PHP

 

Connect MySQL in Visual C#

Instructions:

  1. Download and Install MySQL Connection Driver in http://dev.mysql.com/downloads/connector/net/6.0.html
  2. Create a test project in Visual C#
  3. Add Reference to MySQL.Data
  4. Add “using MySql.Data.MySqlClient;”

using MySql.Data.MySqlClient;

private void connectoToMySql(string server)
{
//set your connection string.
//NOTE: I am a big supporter of having the connection
//stored in the web.config, not inline like this
string connString = “SERVER=” + server + “;” +
“DATABASE=mydatabase;” +
“UID=testuser;” +
“PASSWORD=testpassword;”;
//create your mySQL connection
MySqlConnection cnMySQL = new MySqlConnection(connString);
//create your mySql command object
MySqlCommand cmdMySQL = cnMySQL.CreateCommand();
//create your mySQL reeader object
MySqlDataReader reader;
//set the command text (query) of the
//mySQL command object
cmdMySQL.CommandText = “select * from mycustomers”;
//open the mySQL connection
cnMySQL.Open();
//execute the reader, thus retrieving the data
reader = cmdMySQL.ExecuteReader();
//while theres data keep reading
while (reader.Read())
{
string thisrow = “”;
for (int i= 0;i<reader.FieldCount;i++)
thisrow+=reader.GetValue(i).ToString() + “,”;
listBox1.Items.Add(thisrow);
}
cnMySQL.Close();
}
 
Leave a comment

Posted by on September 22, 2009 in C#

 

How to Read and Write INI File in C#


using System.Runtime.InteropServices;

class IniFile
{
public string path;

[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section,
string key, string val, string filePath);

[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section,
string key, string def, StringBuilder retVal,
int size, string filePath);

public IniFile(string INIPath)
{
path = INIPath;
}

public void IniWriteValue(string Section, string Key, string Value)
{
WritePrivateProfileString(Section, Key, Value, this.path);
}

public string IniReadValue(string Section, string Key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.path);
return temp.ToString();
}

}

 
1 Comment

Posted by on September 11, 2009 in C#, Window Application

 

Printing PDF documents in C#

using System.Diagnostics;

PrintDialog printDialog1 = new PrintDialog();
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = @”C:\c.pdf”;
info.Verb = “Print”;
info.Arguments = printDialog1.PrinterSettings.PrinterName;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.StartInfo = info;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.CloseMainWindow();

http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/8ce3dd94-ff2c-4c3c-ba85-f67b9dd2f2e8

 
Leave a comment

Posted by on September 8, 2009 in Window Application

 

Web Services in C#

Web Services are the basic fundamental building blocks of invoking features that can be accessed by an application.

The accessibility to provide the features across different platforms that are developed using different languages, and can be used by any remote application, over the internet, etc.., makes the web service more useful at times by means of providing the user only the specific and relevant information, avoiding the accessibility to resources that have to be securely maintained.

Web Services comprises of the following main aspects that are included,

  1. XML Web Services: The communication between the service and the application is through a standard format called XML (eXtensible Markup Language) which is universal and is accepted on any platform across the distributed network.
  2. WSDL (Web Service Description Language): It consists of the description about the web service, which is basically a file with .wsdl extension that you can find in your application folder. It includes the information about the namespace of the xml file which is the tag <xmlns:”name”>. it also holds the description of the elements that the service consists of and also the information relevant to the parameters supplied.
  3. SOAP (Simple Object Access Protocol): SOAP is a protocol that by means of which Web Services is enabled; it is the format that is acclaimed universally due to its nature of standardization and rules that it implements. The inter-communication in web services uses SOAP for the efficient communication.
  4. UDDI (Universal Discription, Discovery and Integration): UDDI is specifically a governing body that monitors the publication and discovery of the web services implementation with respect to message communication between the application and also at the enterprise level.
  5. IIS(Internet Information Server for MicroSoft Visual Studio .Net) : It is the core aspect in web technology which deals with the Client/Server model, as the web service is a module available throughout the web for usage. Whenever a client sends the request to find the web service to the UDDI , the UDDI in turn contacts the web server IIS(for Dot Net) and the discovery, description of the web service is returned after which the client sends a request to consume the web service.

A Simple Example:

A simple Example to create a Web Service:

Service Application

From the Visual Studio .net IDE select the file–> new –> project, select Visual C# projects from the Project Types and Select an ASP.NET Web Service from the templates available and name it as addnumservice. The extension of web service is of type .asmx file, change the name of the service.asmx page as ‘testservice.asmx’ or as per the naming convention that you are accustomed to but do adopt to a format.

Now your service application is ready to be coded for depending on your requirements. Now in the window pane select the ‘click here to switch to code view’ and you are taken to the code-behind file where you can write your code.

In the attribute [WebMethod] you can see a default simple method that is used to display a simple text “Hello World” , using the [WebMethod] attribute the code for your service is included,

Write the function for the above discussed web service method that is shown as below. In the Web method code include the following content,

[WebMethod] public int add(int a,int b) { return (a+b); }

Now that, your have written your method, the project needs to be built. To do that right click on your project name and from the context menu available select the build option which will complete your service method creation.

Environment: Windows, IIS, .Net

Client Application

This is the application that invokes the Web Service that is defined above.

Create a new project, select Visual C# Projects from the Project Types and select an ASP.NET Web Application from the Templates available and name it as clientusingwebservice or as per your convenience.Your web form should consists of two textbox controls for accepting the values from the user, two label controls for naming against the textboxes, a button control and a label control to display the message.

Now specify the relevant control ID’s naming as per your convenience and then the most important thing, in the Solution Explorer right-click on the References folder that you can find and select the Add Web Reference option. A Dialogue box pops up where you can find the list of options related to the repository of the web services, select the option (Web services on the local machine)™ after clicking on the link you are displayed with all the services currently available on the local machine. Select the relevant service that you want to include onto your application, in our example it being the (testservice)™.

Next follows the code that is included in the application that has to use the service, for this create an object of the service type and by using that object we call the method that is present in the service, as shown below;

write this code just above the Page_Load method. //creating an object for the service that has to be called for clientusingservice.localhost.Service1 serviceobj=new clientusingservice.localhost.Service1(); private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here }

And now for the Button click event from where you will perform the addition of two numbers accepted from the textboxes through the method in the service will be written, code as follows;

private void btnadd_Click(object sender, System.EventArgs e) { int sum; sum=serviceobj.add(int.Parse(txtnum1.Text),int.Parse(txtnum2.Text)); lblmsg.Text="Addition performed using service" +a; }

Now you are ready to use and see the working of the web that you have created by following the procedure as mentioned above build the solution and press F5 to view the results.In the next publication you will learn more about the enhancements that the web service can implement WSE, which include some advance features that are included in WS-*, like the WS-security, configuration, Addressing, etc..,.

 
Leave a comment

Posted by on September 3, 2009 in C#