Showing posts with label How connect C# web service and Android. Show all posts
Showing posts with label How connect C# web service and Android. Show all posts

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


Wednesday, February 27, 2013

C# Web Services and Android – Part 1

C# web services are currently widely used to communicate with any other platforms (like mobile, web applications) through internet. Since last two decades usage of smart phone devices are really increased. When designing the web application we must consider about the smart devices fact as well. C# Web Services with Android tutorial series is really helpful to build communication pathway between C# web services and Android smart phone devices.  

User Story: There is a C# web application which can access through the PC and user needs Android based mobile application which provides selected functionalities of the web application. Web application provide functionality to retrieve full name of the person which belongs to the given user id. User needs Android based mobile application for previously mentioned web function. User uses his/her android device, starts the application then type user id and submits it. Android application should capable to communicate with web service and retrieve relevant data and display.

According to the previous user story we need to implement simple web service to retrieve the person details which belongs to the given id. Also need to implement Android based mobile application which can communicate with web service and display correct results.

How to create simple web service to retrieve person details by given id

In the web service we use business object called “Person”. Following code illustrate the properties of the Person object. We used serializable person object to communicate with mobile device the reason is only serializable objects can transfer through the network.


     /// 
     /// public class Person
     /// 
    [Serializable]
    public class Person
    {
        /// 
        /// Gets or sets the first name.
        /// 
        /// 
        /// The first name.
        /// 
        public string FirstName
        {
            get;
            set;
        }
        
        /// 
        /// Gets or sets the last name.
        /// 
        /// 
        /// The last name.
        /// 
        public string LastName
        {
            get;
            set;
        }

        /// 
        /// Gets or sets the id.
        /// 
        /// 
        /// The id.
        /// 
        public string Id
        {
            get;
            set;
        }
    }


There is another class we used to defined possible operations of person. Following class shows create sample data for person and retrieve relevant person details for given id (return suitable person object).


    /// 
    /// public class PersonOperations
    /// 
    public class PersonOperations
    {
        /// 
        /// Creates the person list.
        /// 
        /// person list
        public List CreatePersonList()
        {
            List personList = new List();

            Person person1 = new Person();

            person1.FirstName = "Iron";
            person1.LastName = "Man";
            person1.Id = "IM01";

            Person person2 = new Person();

            person2.FirstName = "Avatar";
            person2.LastName = "Aang";
            person2.Id = "AA02";

            Person person3 = new Person();

            person3.FirstName = "Avatar";
            person3.LastName = "Korra";
            person3.Id = "AA03";

            personList.Add(person1);
            personList.Add(person2);
            personList.Add(person3);

            return personList;
        }


        /// 
        /// Gets the person by id.
        /// 
        /// The user id.
        /// 
        /// relevant person
        /// 
        public Person GetPersonById(string userId)
        {
            List personList = this.CreatePersonList();

            if (string.IsNullOrEmpty(userId) || personList == null || personList.Count == 0)
            {
                return null;
            }

            Person result = personList.Where(x => x.Id.Equals(userId, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

            if (result == null)
            {
                return null;
            }

            return result;
        }
    }


Following code snippets shows the simple web service. It simply passes the user submitted id to the function called “GetPersonById” and returns the relevant Person object.  In the web method it’s mandatory to define web service namespace. Because SOAP action use web service namespace to recognize the correct web service which hosted in the given host (URL).


    /// 
    /// Summary description for DemoService
    /// 
    [WebService(Namespace = "http://DemoWebService.com/")]
    [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 DemoService : System.Web.Services.WebService
    {

        /// 
        /// Gets the person by id.
        /// 
        /// The user id.
        /// 
        /// relevant person
        /// 
        [WebMethod]
        public Person GetPersonById(string userId)
        {
            if (string.IsNullOrEmpty(userId))
            {
                return null;
            }
            else
            {
                PersonOperations result = new PersonOperations();

                return result.GetPersonById(userId);
            }
        }
    }


Following screenshots shows the details of the web service which hosted in local host. How to host web service in local machine will be discuss in future.

Figure 1 - Web Service


This image demonstrates what are the web-methods define under the web service. Clicking on the function name (GetPersonById) user can trigger the web-method and make sure its functioning properly or not (see image – 2 and 3).

Figure 2 - Invoke the web service with suitable data


Following screen illustrates the result after invoking web-method with data. It shows what the properties of return object and values are.

Figure 3 - Results after invoking web-method with data


Following screen shows the description of the web service. That description contains all necessary details needs to invoke from outside (for example web service name space, soap action etc.).

Figure 4 - Description of the web service


Part two of this post will be post soon and it contains both Visual Studio C# solution and Eclipse project of Android mobile application.