RSS

Tag Archives: web service

How to use Sessions in Web Services ASP.Net

Using sessions in web services is little different from its normal usage. Here we can not access sessions with Session as in Page methods. Instead we use HttpContext.Current.Session.

Sessions should be enabled for web methods.

A sample code snippet would be as follows.

/// Summary description for ReceivingService
    /// </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 ReceivingService : System.Web.Services.WebService
    {

        [WebMethod(EnableSession = true)]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public Dictionary<string, object> removeItem(int Id)
        {
            var response = new Dictionary<string, object>();
            bool found = false;

            if ( HttpContext.Current.Session["rec_cart"] != null)
            {
                List<CartItem> cartItems = (List<CartItem>)Session["rec_cart"];
                if (cartItems.Count > 0)
                {
                    foreach(var item in cartItems){
                        if(item.Id == Id){
                            cartItems.Remove(item);
                             HttpContext.Current.Session["rec_cart"] = cartItems;
                            found = true;
                            break;
                        }
                    }
                }
            }
            if (found)
            {
                response["status"] = true;
                response["total"] = GetGrandTotal();
            }
            else
            {
                response["status"] = false;
            }
            return response;
        }
}

I also configured cookieless sessions in web.config to get web service call properly routed.

<sessionState cookieless="true" regenerateExpiredSessionId="true" timeout="100"/>
Advertisements
 
Leave a comment

Posted by on April 11, 2015 in ASP.Net

 

Tags:

PHP SOAP Web Service With NuSOAP

nusoap

In this tutorial, we create a SOAP web service in PHP.  We use NuSOAP as a third party library for this tutorial. NuSOAP is a very useful library that eases SOAP  web service implementation.

It is a set of PHP classes – no PHP extensions required – that allow developers to create and consume web services based on SOAP 1.1, WSDL 1.1 and HTTP 1.0/1.1.
Download NuSOAP

Copy the lib folder to the project.

We use a simple function that performs zip code loookup as our web service.

First we create SOAP server which exposes the functionality for its clients.

zip_code_server.php

<?php

require_once 'lib/nusoap.php';

//Perform client authentication
//Unauthenticated clients are not allowed to access functionality
function doAuthenticate() {
if (isset($_SERVER['PHP_AUTH_USER']) and isset($_SERVER['PHP_AUTH_PW'])) {

if ($_SERVER['PHP_AUTH_USER'] == "codezone4" && $_SERVER['PHP_AUTH_PW'] == "123")
return true;
else
return false;
}
}

//Retrieve zip code for textual area
//Logic of the web service
function get_zip_code($area) {
//Can query database and any other complex operation
if (!doAuthenticate())
return "Invalid username or password";
if ($area == "Temple Hills") {
return 20757;
} else if ($area == "Cheltenham") {
return 20623;
} else {
return "Can not find zip code for " . $area;
}
}

$server = new soap_server();
$server->configureWSDL("zipcodelist", "urn:zipcodelist");

//Register web service function so that clients can access
$server->register("get_zip_code",
array("area" => "xsd:string"),
array("return" => "xsd:int"),
"urn:zipcodelist",
"urn:zipcodelist#get_zip_code",
"rpc",
"encoded",
"Retrieve zip code for a given area");

$POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA'])? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
$server->service($POST_DATA);
?>

Now, run the server. You will see a link to wsdl file. Click that link and view the generated wsdl file. Clients who access the web service needs this wsdl. Save this file with .wsdl extension. You need to specify the URL for wsdl file within client.

zip_code_client.php

<?php
require_once('lib/nusoap.php');
$client = new nusoap_client("http://localhost/NuSOAP/zip_codes.wsdl", true);

$error = $client->getError();
if ($error) {
echo "<h2>Constructor error</h2><pre>" . $error . "</pre>";
}
//Use basic authentication method
$client->setCredentials("codezone4", "123", "basic");
$result = "";

if ($client) {
$result = $client->call("get_zip_code", array("area" => "Cheltenham"));
}
if ($client->fault) {
echo "<h2>Fault</h2><pre>";
print_r($result);
echo "</pre>";
} else {
$error = $client->getError();
if ($error) {
echo "<h2>Error</h2><pre>" . $error . "</pre>";
} else {
echo "<h2>zip code</h2><pre>";
echo $result;
echo "</pre>";
}
}

echo "<h2>Request</h2>";
echo "<pre>" . htmlspecialchars($client->request, ENT_QUOTES) . "</pre>";
echo "<h2>Response</h2>";
echo "<pre>" . htmlspecialchars($client->response, ENT_QUOTES) . "</pre>"
?>

Download Project

Some additional stuff

How to use complex types?

//A complex method
function HelloComplexWorld($mycomplextype)
{
	return $mycomplextype;
}

//Create a complex type 
$server->wsdl->addComplexType('MyComplexType','complexType','struct','all','',
		array( 'ID' => array('name' => 'ID','type' => 'xsd:int'),
				'YourName' => array('name' => 'YourName','type' => 'xsd:string')));

//Register our method using the complex type
$server->register(
// method name:
		'HelloComplexWorld',
		// parameter list:
		array('name'=>'tns:MyComplexType'),
		// return value(s):
		array('return'=>'tns:MyComplexType'),
		// namespace:
		$namespace,
		// soapaction: (use default)
		false,
		// style: rpc or document
		'rpc',
		// use: encoded or literal
		'encoded',
		// description: documentation for the method
		'Complex Hello World Method');
 
6 Comments

Posted by on December 2, 2012 in PHP

 

Tags: , ,

Java SOAP Web Service With Apache Axis2 in Netbeans

<

Requirements

  1. Java Development Kit (JDK)
  2. NetBeans IDE
  3. Apache Axis 2
  4. Apache Tomcat Server

Main Topics

  1. Setup Development Environment
  2. Create Web Service
  3. Deploy Web Service to Tomcat Server

1. Setup Development Environment

Install Axis2 Support Plugin

Go to Tools >> Plugins and open Plugin Manager. Check whether Axis2 Support Plugin is already installed. Otherwise you may need to find it from Available Plugins and install.

Configure Axis2 for Tomcat

Extract axis2.war archive to Tomcat webapps directory.

You can find this directory in your CATALINA_BASE/webapps. If you are not sure where CATALINA_BASE points to, open Services tab and select Tomcat server. Right click Tomcat server and select properties. Most probably you will find it there. If there is no CATALINA_BASE, you have not run your Tomcat before. Start and stop Tomcat to allow this varible generate.

Start or restart the Tomcat server. Tomcat unpacks the axis2.war file into an axis2 folder in CATALINA_BASE/webapps.

Go to Tools >> Options and click Axis2 icon to view deployment options. Set the target location for Axis2 AAR files to your CATALINA_BASE (not TOMCAT_HOME)/ webapps/axis2 directory.

Make sure the Axis2 URL field contains the correct port number for your Tomcat server. To check the port number, start Tomcat (from the Services tab or from Tools -> Servers) and see what port Coyote HTTP/1.1 uses.

select Use Tomcat Manager for Deployment

Check whether username and password of manager role are correct by referring CATALINA_BASE/conf/tomcat-users.xml.

2. Create Web Service

File >> New Project. The New Project wizard opens. From the Java category, select a Java class library project. Click Next.

Right-click the project and choose New >> Other. The New File wizard opens. From the Web Services category, choose Axis2 Service from Java and click Next.

Keep settings as it is in the following wizard and click Next.


In this wizard enter Java Web Service class name and click Finish.


The IDE generates a HelloAxisWorld.java class in the axishello source package and a HelloAxisWorld Axis2 web service that mirrors this Java class.

3. Deploy Web Service to Tomcat Server

Right-click the web service’s node. The context menu opens. Select Deploy to Server. The IDE compiles an Axis2 AAR file and copies it to the axis2.war file used by the application server.

If you enabled automatic deployment in Tomcat Manager, axis.war will automatically redeploy to server whenever it ‘s get updated.

To test the service, expand the web service node to reveal the operations. Right-click the hello:String node and select Test Operation in Browser.

To test the service, expand the web service node to reveal the operations. Right-click the hello:String node and select Test Operation in Browser.

Browser opens with a test value of your variables. You can find test value in the URL. Change it and refresh the page.

 

 
9 Comments

Posted by on November 3, 2012 in J2EE, Java

 

Tags: , , ,

Java SOAP Web Service With Apache Axis2 in Eclipse

Web Service

Today we are going to build a SOAP based Java web service. We are using AXIS2 which serves as a SOAP implementation. I assume that you have already installed Java JDK in to your machine.

Requirements :

1) Eclipse EE – Download
2) Apache Tomcat – Download
3) Apache Axis2 Binary Distribution – Download
4) Apache Axis2 WAR Distribution – Download

While installing these programs, consider about default ports. There may be port conflicts if you neglect this fact. This becomes an issue only if you are allocating ports which are already used by previously installed programs. For an instance, there may be a port conflict when attempting to install Tomcat server using port 8080 in a machine where Oracle 10g is installed. Both of these use port 8080 by default. So you may change the ports as necessary during or after the installation.

Please note that there may be various compatibility issues when using Eclipse and Apache Tomcat with Axis2 to build our web service. Most of the problems can be minimized with Netbeans. GlassFish server supports out of the box in many occasions with Netbeans.
Let’s deal with Netbeans at a later time.

I’m using Eclipse Indigo, Apache Tomcat 6 and Axis2 for this tutorial.

Extract Apache Axis2 Binary Distribution. Create an Environment Variable as AXIS2_HOME. Get the path to Axis2 installation directory and use it as the value of AXIS2_HOME Environment Variable. (something like C:\Program Files\axis2-1.6.2)

Extract Axis2 WAR Distribution and copy axis2.war file to Tomcat server webapps directory.

Now you are ready to go ahead with this tutorial. First check our road map.
1. Setup Development Environment in Eclipse.
2. Create Web Service.
3. Deploy web service.
4. Create a client who consumes Web Service.

1. Setup Development Environment in Eclipse.

Now you need to configure Eclipse for Tomcat server and Axis2.
Open Eclipse IDE and go to Window >> Preferences
Add new server runtime environment.

Select your Tomcat server version and click Next. Browse your Tomcat installation directory in next window.

Now configure Axis2 in Axis2 preferences under Web Services category. Browse your Axis2 installation directory. You should see this message if this is fine.
“Axis2 runtime loaded successfully”

Select Server and Runtime. Make sure your server runtime is selected. Web service runtime should be Apache Axis2.

 

2. Create Web Service.

First create a new Dynamic Web Project (File >> New >> Other) and choose Web >> Dynamic Web Project. Enter project settings in the first window.
Select the target runtime that we configured earlier.
You should modify the configuration so that Axis2 is included into the project.

Remeber to put a tick on Axis2 web services

Click Next>>Next and Finish. Now Eclipse will load the project.
Now it’s time to create web service class. This class can contain some methods which are exposed to outside. The clients are going to consume this web service class. First we create a Plain Old Java Class and convert it into a web service. Right click on project and select New>> Class

Add a public method to this class.

package com.codezone4;

public class MyService
{
 public String testMethod(String param)
 {
 return "Read " + param;
 }
}

To expose this file as a web service right click on the Java file and select Web Services >> Create Web Service
or
select File >> New >> Other and choose Web Service.
You can can add web service using one of above methods.

We use bottom-up approach as web service type. Select the class which acts as the web service(that we just created). Make sure your configurations are correct.

Click Next. Make sure Generate a default service.xml file is selected and click Next. Now you are asked to Start Server. Do it!
Then Click Next and Finish the dialog.
Now you should be able to reach your web service through your browser. Tomcat server is started and you gonna run your web service in Tomcat.
Right click on your project and select Run as >> Run on server.

You may see the below screen through your Eclipse web browser. Alternatively you can copy the following URL into your web browser bar.
http://localhost:8440/HelloWorldWebService/
This port number 8888 depends on your Tomcat configuarations.

Go to Services. Under Available Services you will find your own service. Click on MyService link (You will find your web service class name here).
Can you see bunch of beautiful xml? This is your WSDL(Web Service Description Language). The clients who consume your service communicate with this WSDL to access the functionality of the web service.
Copy the URL for WSDL file.
You can validate this file at a later time when you create the client. To do that enable WSDL validation for all files in Eclipse preferences. This option can be found under web service category.

Obviously you can play with your web service without a real client using Web Service Explorer tool in Eclipse. Click that icon

This will launch a screen similar to the following.

Click WSDL page icon. On the next screen, click WSDL Main under navigation section.
Enter your WSDL URL into the box and click Go. On the left you will see a hierarchical representation of your web service. Play around with this for a while and test your web service with different inputs….

3. Deploy web service.

In current situation, the web service can only be run within Eclipse. So we are going to deploy it to Tomcat server. First create .aar (Axis Archive)
Got to your web service directory using command prompt.
Eg. C:\Users\AAA\Documents\Eclipse\HelloWorldWebService\WebContent\WEB-INF\services\MyService

Enter following command to create .aar file.
jar cvf HelloWorldWebService.aar com META-INF
This will generate .aar file in your web service directory. Now wanna upload this file using the Administration panel in Axis2. You can enter this area using Axis home page Administration link.
username : admin
password : axis2

Or else you can simply copy the .aar file and paste into Tomcat webapps\axis2\WEB-INF\services directory.

To verify your deployment first stop Tomcat server in Eclipse. Click on red, small rectangular button on Servers panel to stop Tomcat.
Next go to Tomcat bin directory and find startup.bat file. Run this file to start Tomcat. If you are using Mac run startup.sh file.
Then go to your web service URL.
http://localhost:8440/HelloWorldWebService/

 

4. Create a Web service client

Select File >> New >> Other and choose Web Service Client.
Enter WSDL URL into the box. Here you can browse for WSDL and validate if needed.

This will generate two new classes called MyServiceStub.java and MyServiceCallbackHandler.java. Now we can create client. Create new class called TestClient.java and paste following code.

package com.codezone4;

import java.rmi.RemoteException;
import com.codezone4.MyServiceStub.TestMethod;
import com.codezone4.MyServiceStub.TestMethodResponse;

public class TestClient {

 public static void main(String[] args) throws RemoteException {
 MyServiceStub stub = new MyServiceStub();
 TestMethod method = new TestMethod();
 method.setParam(" Cheers!");
 TestMethodResponse response = stub.testMethod(method);
 System.out.println(response.get_return());

}

}

Run this client as a Java application. Observe the output in console. You should see the message that resulted from remote method call if everything worked fine.

I think you enjoy this web service tut. Please leave a comment.
Happy coding!

 
2 Comments

Posted by on November 3, 2012 in J2EE, Java

 

Tags: , ,