Friday, March 1, 2013

C# Web Services and Android – Part 2

Under part 2 we mainly consider about android based mobile application which used to communicate the web service we already design in Part 1(Click Here).

Android application use SOAP object to request data from web service and get response from the web service. We use third party library called “ksoap2-android” to create SOAP request and communicate with the web service. That library can freely download from following link (That library also included in bin folder of the Android mobile application project).

Download “ksoap2-android-full-2.1.2

To create SOAP object it need web service wsdl URL and operation name it needs to invoke. In the part 1 we specify how find out values for those variables. For the given scenario the wsdl target namespace is “http://DemoWebService.com/” and operation is “GetPersonById”. After that it needs to add parameter values needs to invoke web service operation. Name of the property is very important its need to same as the parameter name which define in the web service otherwise it doesn’t work.  Then it need to create envelop to add the SOAP object.  After set the envelop type (dotNet) its ready to transport the envelope to the web service and retrieve the response from web service.  Before send the envelop it need to mentioned the destination. Destination contains the URL of the web service we need to invoke. In our scenario the URL will be “http://localhost/DemoService.asmx” but localhost not recognize by the android emulator.  Instead of localhost it needs to define IP to recognize the localhost. Android emulator recognized “10.0.2.2” as a localhost (this IP valid for any PC). Finally the destination URL will be “http://10.0.2.2/DemoService.asmx”. After setting destination it’s time to invoke web method. To invoke web method it needs SOAP action. The value of SOAP action can easily find out from web service description (see part 1). In this scenario the SOAP action is “http://DemoWebService.com/GetPersonById”. After invoke web method it returns serializable Person object as response. We can use name of the each property of Person (as named in web service) to extract values from response object. Following code snippet illustrates how to implement each and every process which discuss before (e.g. how to create SOAP request, envelop, made request and retrieve results).


 
 private void GetFullNameById(){
  
  userId = (EditText) findViewById(R.id.txt_user_id);  
  resultText = (TextView)findViewById(R.id.lbl_result);
  fullNameText = (TextView)findViewById(R.id.lbl_full_name);
  
  id = userId.getText().toString();
  Constants projectConstants = new Constants();
  
  if(!(id == null || id.length() == 0)){
   
   String firstName = "";
   String lastName = "";
   String fullName = "";
   
   SoapObject request = new SoapObject(projectConstants.WSDL_TARGET_NAMESPACE, projectConstants.OPERATION_NAME);
   
   request.addProperty("userId", id);
   
   SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
   
   envelope.dotNet = true;     
   envelope.setOutputSoapObject(request);     
   HttpTransportSE httpTransport = new HttpTransportSE(projectConstants.URL);
   
   try     
   {     
    httpTransport.call(projectConstants.SOAP_ACTION, envelope);     
    SoapObject response = (SoapObject) envelope.getResponse();
    
    if(response == null){
     resultText.setText("User Not Found");     
         
     resultText.setVisibility(View.VISIBLE);
     fullNameText.setVisibility(View.GONE);
     return;
    }
    
    firstName = response.getProperty(projectConstants.FirstName).toString();
    lastName = response.getProperty(projectConstants.LastName).toString();
    fullName = firstName + " " + lastName;
    
    if(fullName != null && fullName.length() > 0){
     resultText.setText(fullName);
     
     resultText.setVisibility(View.VISIBLE);
     fullNameText.setVisibility(View.VISIBLE);
     
    }else{
     
     resultText.setText("User Not Found");
     
     resultText.setVisibility(View.VISIBLE);
     fullNameText.setVisibility(View.VISIBLE);    
    }
   }     
   catch (Exception exception)     
   { 
    Log.i("Exception", exception.getMessage());
    
    resultText.setText("Error Occurs");     
    
    resultText.setVisibility(View.VISIBLE);
    fullNameText.setVisibility(View.GONE);
   }   
   
  }
 }


Following constant class defines all constant values need to invoke web service.


public class Constants {
 
 /**
  * Constants for return person object fields
  */
 protected final String FirstName = "FirstName";
 protected final String LastName = "LastName";
 protected final String Id = "Id";
 
 /**
  * SOAP request informations 
  */
 protected final String WSDL_TARGET_NAMESPACE = "http://DemoWebService.com/";
 
 protected final String OPERATION_NAME = "GetPersonById";
 protected final String URL = "http://10.0.2.2/DemoService.asmx";
 protected final String SOAP_ACTION = "http://DemoWebService.com/GetPersonById";
 
}


Important: before invoke web service its need to allow Android emulator to access the local network. Following code portion illustrate how to give permission to access the network. Following code snippet extracted from “AndroidManifest .xml”.


    
        
            
                

                
            
        
    
  


Download Complete Web Service Project
Download Complete Android Mobile Project (Target API Level Android 2.3.3, eclipse version - Helios) – Before run the mobile application please set build path of “ksoap2-android-full-2.1.2” library build path to lib folder