Tuesday, August 20, 2013

Consume Third Party Web Service Using Auto Generated Early Bound Proxy Object - C# - Part 1

Modern software solutions provides bunch of services to their users. Also most of current software solutions are not a stand-alone systems. They have lots of integration points with other systems to interact with each other. WCF web services are the most widely used service providing interface to software systems to interact with each other. There are several ways to consume third party WCF web service. Following two methods are the most commonly used pathways to consume third party web service.
  1. Use generated early bound service proxy classes
  2. Use service reference
In this post we discuss how to generate early bound proxy classes and use these proxy classes to consume third party web service.

Creating WCF web service

We use very similar WCF web service which used to consume C# web service using Android application ("C# Web Services and Android").
WCF web service provides functionality to retrieve person details based on the person Id. Use same person business object class to create person object which used in "C# Web Services and Android". Create "IPersonOperations" interface to define person operations and create "PersonOperations" concrete class to implements the services already defined in " IPersonOperations " interface class.

    interface IPersonOperations
    {
        /// 
        /// Creates the person list.
        /// 
        /// list of person
        List CreatePersonList();

        /// 
        /// Gets the person by unique identifier.
        /// 
        /// The user unique identifier.
        /// person
        Person GetPersonById(string userId);
    }


    public class PersonOperations:IPersonOperations
    {
        /// 
        /// Creates the person list.
        /// 
        /// list of person
        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 unique identifier.
        /// 
        /// The user unique identifier.
        /// 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;
        }
    }


Creating WCF operation contract and service contract

To access the WCF web service we need to create service contract and operation contract. Service contract create service interface to outside of the web service. Operation contract defines the operations which can perform under the relevant service contract. Namespace of the service contract is very important. Accessing web service and operations are totally depends on the service contract namespace. If you didn't provide namespace for service contract then it use default namespace " http://tempuri.org/". In this scenario we use namespace called " http://DemoWebService.com/ ". " IDemoService " is the service which provided by WCF web service and " GetPersonById " is the operation which provided under previously mentioned service.



    [ServiceContract(Namespace="http://DemoWebService.com/")]
    public interface IDemoService
    {
        /// 
        /// Gets the person by unique identifier.
        /// 
        /// The user unique identifier.
        /// person
        [OperationContract]
        Person GetPersonById(string userId);
    }


    public class DemoService : IDemoService
    {
        /// 
        /// Gets the person by unique identifier.
        /// 
        /// The user unique identifier.
        /// 
        /// person
        /// 
        public Person GetPersonById(string userId)
        {
            if (string.IsNullOrEmpty(userId))
            {
                return null;
            }
            else
            {
                PersonOperations result = new PersonOperations();

                return result.GetPersonById(userId);
            }
        }
    }


Important: before add the namespace for the WCF service please add " System.ServiceModel " reference. Otherwise it will give compile time errors.

Configure WCF web service

This is the one of the important step of the hosting WCF service. Following web config shows the important configurations we need to set before host WCF web service.


  
    
  
  
    
    
  
  
    
      
        
          
          
        
      
    
    
      
        
          
        
      
    
    
    
      
        
          
            
          
        
        
      
    
  
  
    
    
  



I add the behavior called " WcfService.DemoService " under service behaviors to register Demo Service behavior in http context. In this example I only used basic http bindings not use secure https bindings. Due to that reason need to set http binding to true. Set basichttpBindings with none security mode.
To avoid following error set " multipleSiteBindingsEnabled " to false. " When 'system.serviceModel/serviceHostingEnvironment/multipleSiteBindingsEnabled' is set to true in configuration, the endpoints are required to specify a relative address. If you are specifying a relative listen URI on the endpoint, then the address can be absolute. To fix this problem, specify a relative uri for endpoint 'http://localhost:8080/DemoService.svc'. " Then finally add service end point like following.
    
      
        
          
            
          
        
        
      
    
	


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.

Monday, January 14, 2013

Telerik Tricks: Radconfirm With Yes No Buttons

Radconfirm modal dialog box contains OK button and Cancel button to get user confirmation. There are several ways can use to change the localization settings of the radconfirm controller’s inner text. One is change localization settings using resource file. Changing localization settings using RadWindowManager is another way to change the inner text of radconfirm.

Following code snippets shows how change radconfirm localization settings using RadWindowManager


    



Following code snippet illustrate the way to change radconfirm localization using JavaScript

    Telerik.Web.UI.RadWindowUtils.Localization =   
    {    
        "OK" : "OK",  
        "Cancel" : "Cancel" 
    };


The main drawback of previously mentioned methodologies is it changes the localization settings of all radconfirm, radalerts and radwindows. To overcome that issue, need to change localization settings of specific radconfirm without effecting other radconfirm dialogs, radalerts and radwindows. Following trick can use to change the localization settings of specific radconfirm. It changes the localization settings before display the radconfirm and it change again localization settings to defaults immediate after the radconfirm get disappear.

 


Sunday, January 13, 2013

Telerik Tricks: Radconfirm with Button Click

Sometimes system requires user confirmation before submitting data or request to the server. Radconfirm is the stylish JavaScript popup which can use instead of standard confirmation. Radconfirm popup is non-blocking, that is radconfirm modal window do not block the execution thread. Because radconfirm window implemented using JavaScript and JavaScript not block the execution thread.  However server should wait until user selects one of the option shows in modal dialog box before submit the action to the server. To achieve that with radconfirm should block the button’s postback action until user confirms the action.

How block postback action of button?

Use OnClientClick action to hold button postback until user confirms. Following code snippet shows waiting mechanism of Submit button. If user clicks on the submit button it do not postback until evaluate function called “ConfirmationFunction”. If “ConfirmationFunction” return true then button continue the postback otherwise postback wont happened.






ConfirmationFunction is the JavaScript function which shows radconfirm modal dialog box and get user confirmation before submit. Following code snippet illustrate how get user confirmation and continue postback. Advantage of following mechanism is if same page contains several radpopup windows’ following mechanism does not overwrite the behaviors of other radconfirms, radalerts and radwindows.