Showing posts with label WebServices. Show all posts
Showing posts with label WebServices. Show all posts

[Tutorial] Simple Android Application which consumes C# ASP.net Web service


Whoever getting started to learn Web services - Android app interaction I hope this tutorial may be helpful, You can download the full source from here: https://github.com/harshadura/RDA-Android-ASP.WS-interact/archive/master.zip

Prerequisites: 
.NET framework, SQL server 2008, Android device/emulator
 
How to run.

  1. Attach the MDF file into your SQL server.
  2. Change the connection string at the C# project config according to your db connection.
  3. Change the 'Web service URL' on the Android Application.
Notes:
  1. You will need to use WIFI tether to get connect your device with PC/otherwise you will need a router, both connected into it.
  2. Sometimes you will need to configure the security restrictions of your IIS web server to get connect the device.

C# Web Service

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
public class Service : System.Web.Services.WebService
{
    public Service () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public String GetEmployeeByID(String id) {
          
            DataSet2TableAdapters.EmployeeTableAdapter dt1 = new DataSet2TableAdapters.EmployeeTableAdapter();
            String ename = "" + dt1.getEmpByID(id);
            return ename;
    }

    [WebMethod]
    public Employee[] GetEmployees()
    {
        var employees = new List();

        try
        {
            string connect = @"Data Source=HARSHADURA-AZUS\SQLEXPRESS;Initial Catalog=RDA;Integrated Security=True";
            string query = "SELECT eid, ename FROM Employee";

                SqlConnection thisConnection = new SqlConnection(connect);
                thisConnection.Open();
                SqlCommand thisCommand = thisConnection.CreateCommand();
                thisCommand.CommandText = query;
                SqlDataReader thisReader = thisCommand.ExecuteReader();
                while (thisReader.Read())
                {
                    var emp = new Employee();
                    emp.eid = thisReader["eid"].ToString();
                    emp.ename = thisReader["ename"].ToString();
                    employees.Add(emp);
                }
                thisReader.Close();
                thisConnection.Close();
            }
            catch (SqlException e)
            {
                Console.WriteLine(e.Message);
            }
        return employees.ToArray();
    }
}


Android --SOAP Client

 private SoapObject result = null;

 private static String SOAP_ACTION = "http://tempuri.org/GetEmployeeByID";
 private static String NAMESPACE = "http://tempuri.org/";
 private static String METHOD_NAME = "GetEmployeeByID";
 private static String URL = "http://192.168.123.100:8080/Service.asmx?WSDL";

 public void connectSOAP(String empid) {
  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
  request.addProperty("id", empid);

  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
    SoapEnvelope.VER11);
  envelope.dotNet = true;
  envelope.setOutputSoapObject(request);
  HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
  try {
   androidHttpTransport.call(SOAP_ACTION, envelope);
  } catch (Exception e) {
   e.printStackTrace();
  }

  result = (SoapObject) envelope.bodyIn;
  
 }

SocketConnections, RMI vs. Web Services Performance comparison

The web services do allow a loosely coupled architecture. With RMI, you have to make sure that the objects stay in sync in all applications, which means that you always have to deploy both of them at the same time even if only one of them is changed (not necessarily, but it is required quite often because of serial UUIDs and whatnot)
Also it is not very scalable, which might be an issue if you want to have load balancers.
In my mind RMI works best for smaller applications, that are not internet-related. I've used it to have a java application that handles electronic communications

Whether you use Web Services or a more "native" approach depends on the environment as well. If you have to pass through a proxy or some corporate firewall(s), Web Services are more likely to work since they are relying on HTTP only. RMI requires you to open another port for your application which may be difficult (not technically, though) in some environments...
If you know that this issue is not a problem, you should consider using RMI. SOA does not depend on technology so much as on good service design. If you have an EJB container, you can call session beans via RMI and additionally expose them as web services, if you really need to, by the way.
The performance depends on the data that you are planning to exchange. If you want to send complex object nets from one application to another, it's probably faster with RMI, since it's transfered in a binary format (usually). If you have some kind of textual/XML content anyway, web services may be equivalent or even faster, since then you would not need to convert anything at all (for communication).

Socket vs. REST Web Service performance


Its hard to imagine that REST is faster than a simple socket connection given it also goes over a Socket.
However REST may be performant enough, standard and easier to use. I would test whether REST is fast enough and meets your requirements first (or one of the many other existing solutions) before attempting your own Socket solution.

RMI
Feels like a local API, much like XMLRPC
Can provide some fairly nice remote exception data
Java specific means this causes lock in and limits your options
Has horrible versioning problems between different versions of clients
Skeleton files must be compiled in like CORBA, which is not very flexible
REST:
easy to route around firewalls
useful for uploading files as it can be rather lightweight
very simple if you just want to shove simple things at something and get back an integer (like for uploaders)
easy to proxy security behind Apache and let it take the heat
does not define any standard format for the way the data is being exchanged (could be JSON, YAML 1.0, YAML 2.0, arbitrary XML format, etc)
does not define any convention about having remote faults sent back to the caller, integer codes are frequently used, but method of sending back data is not defined. Ideally this would be standardized.
may require a lot of work on the client side caller of the library to make use of data (custom serialization and so forth)
In short from here
web services do allow a loosely coupled architecture. With RMI, you have to make sure that the objects stay in sync in all applications
RMI works best for smaller applications, that are not internet-related and thus not scalable

Ref:

http://stackoverflow.com/questions/100993/rmi-vs-web-services-whats-best-for-java2java-remoting
http://stackoverflow.com/questions/5026952/socket-v-rest-performance


Virtual Mart: ASP.NET Web Services with Web Portals.


Distributed Component Based Software Development by using ASP.NET Web Services and Web Portals.

Virtual Mart-Reservation Agent Portal

Goal: Implement a Virtual Marketplace.

The following entities play a role in the Virtual Marketplace:

• Agent: A portal, which allows passengers to search a route, reserve and cancel Air tickets on various Air Lines. Agent port also facilitates passengers to search hotels availability, reserve and cancel hotel reservations.

• Bank: Provides financial services to the its customers (Passenger, Agent, Airline, Hotel)

• Airline: Provides daily flying schedules for the Agents and accepts reservations from passengers.

• Hotel: Provides logging facilities (BB, HB, and FB) and accepts reservations from passengers.



Following diagram shows the high level architecture of the Virtual Market.
ScreenShot




Released Under MIT Licence 2012 Harsha Siriwardena

@authors: harshadura, chathu

Prequisities.

.NET Framework 3.5
MS Visual Studio 2008
MS Access

Notes.

This project consist with 3 C# SOAP Web Services with 4 ASP.NET Web Portals. Web Portals are depending on the Web Services. So first have to run all the required Web services and then run Web portals.

_______________
2012-October-28

This Project has been done for a partial fulfillment of Distributed Component Based Software Development Subject.



Screenshots of Agent Portal.








How to Access localhost Web Service on Android Device over WIFI

Accessing the localhost over the wifi on my android phone was not easy task for me, many configuration needed to done. I am writing these steps which worked for me. These steps are applicable on Windows 7.

Install the Wamp server

This is one of the best server I know to set up local server. If you have installed Apache or any other server then ignore this step.
Download and install Wamp Server from here.

Add New rule for port 80 in Windows Firewall setting

1. Open control panel and select Windows firewall


2. Select Advanced setting from left panel of Windows firewall setting page.

3. Select Inbound Rules from left panel(1), next Select New Rule(2).


4. Select Port and click next


5. Select “Specific local ports” radio button and enter 80 as a port value.


6. Keep Allow the connection unchanged and move to next.


7. Keep Profile options unchanged and click next.


8. Give some nice name to your New rule and click on Finish.


This will enable port 80 access on local network ip.

Edit httpd.conf file of Wamp server to fix 403 error

We need to edit httpd.conf file else we will get 403 forbidden error when we access the localhost through local network ip.

1 .Click on wamp server tray icon

2. OpenApache server sub menu

3. Select httpd.conf

4 .Find this section of configuration in httpd.conf file

Directory “c:/wamp/www/”
#
# Possible values for the Options directive are “None”, “All”,
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that “MultiViews” must be named *explicitly* — “Options All”
# doesn’t give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be “All”, “None”, or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride all
#
# Controls who can get stuff from this server.
#
# onlineoffline tag – don’t remove
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
Find and replace ’127.0.0.1′ with ‘All’

Find your local network ip

1. open command prompt

2 .type and enter ipconfig command


3. In my case my local area network address is 10.0.0.2

This is the ip which you need to access your localhost on your android phone over wifi. To test it is working type this ip address in your desktop browser where your localhost server is installed. Browser should display your localhost page successfully. This will assure that this local network ip is now can successfully accessible on your Android phone.
I hope this tutorial will help you too access your localhost over wifi.


Reference : http://www.mobitechie.com/android-2/how-to-access-localhost-on-android-over-wifi


http client using Java to access POST GET methods from a web service


Download Sample Project

package javaapplication1;

import java.util.logging.Logger;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.PostMethod;

public class Main {
 private final static Logger LOGGER = Logger.getLogger(Main.class.getName());

 public static void main(String args[]) {
  try {
   PostMethod post = new PostMethod("http://23.21.69.166/ralapanawa/RalaWS.php");
   post.addParameter("tank_id", "kalawewa");
   HttpClient client = new HttpClient();
   int status = client.executeMethod(post);
   String response = post.getResponseBodyAsString();
   LOGGER.info("Request sent! > Reponse : " + response);

  } catch (Exception e) {
   LOGGER.info("Error : " + e.getMessage());
  }
 }
}



How to write REST Web Services using PHP

<?php

function getStatusCodeMessage($status)
{
    $codes = Array(
        100 => 'Continue',
        101 => 'Switching Protocols',
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Found',
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        306 => '(Unused)',
        307 => 'Temporary Redirect',
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Request Entity Too Large',
        414 => 'Request-URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Requested Range Not Satisfiable',
        417 => 'Expectation Failed',
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported'
    );

    return (isset($codes[$status])) ? $codes[$status] : '';
}

function sendResponse($status = 200, $body = '', $content_type = 'text/html')
{
    $status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status);
    header($status_header);
    header('Content-type: ' . $content_type);
    echo $body;
}

class RalapanawaAPI {

    private $db;

    function __construct() {
        $this->db = new mysqli('localhost', 'USER', 'PASS', 'ralapanawa');
    }

    function __destruct() {
        $this->db->close();
    }

    function rala() {

        if (isset($_POST["tank_id"]) && isset($_POST["water_level"]) ) {
            try{
                $tank_id = $_POST["tank_id"];
                $water_level = $_POST["water_level"];

                $stmt = $this->db->prepare("INSERT INTO water_level (tankid, Depth) VALUES (?, ?)");
                $stmt->bind_param("ss", $tank_id, $water_level);
                $stmt->execute();
                $stmt->close();

                sendResponse(200, 'Water Level Saved!');
                return true;
            } catch (Exception $e) {
                $err = 'Caught exception: '.  $e->getMessage().  "\n";
                sendResponse(200, $err);
                return false;
            }
        }

        if (isset($_POST["tank_id"]) ) {

            $depth = "";
            $tank_id = $_POST["tank_id"];

            $stmt = $this->db->prepare("SELECT Depth FROM water_level WHERE tankid=?");
            $stmt->bind_param("s", $tank_id);
            $stmt->execute();
            $stmt->bind_result($depth);

            while ($stmt->fetch()) {
                break;
            }
            $stmt->close();

            $result = array(
                "water_level" => $depth
            );
            sendResponse(200, json_encode($result));
            return true;
        }

        sendResponse(400, 'Invalid request');
        return false;

    }
}

$api = new RalapanawaAPI;
$api->rala();

?>

curl -F "rw_app_id=1" -F "code=test" -F "device_id=test" http://www.wildfables.com/promos/


https://gist.github.com/3041075

REF:
http://www.raywenderlich.com/2941/how-to-write-a-simple-phpmysql-web-service-for-an-ios-app


Retrieve Image objects from a .NET Web Service using Ksoap to Android

Hi Guys!

After lot of effort I have completed one of the tutorials regarding KSOAP Web Services with Android. :D
So I would like to describe how I have solved the things for any case some one will get the use and well for my future reference as well.

Task
Using the following .Net Webservice, call method GetLinkImage  by passing the image ids listed below. The method will return an image. Save these images to a local storage on android device and show them in a suitable way.

Thanks to this web site, got the basics of Koap with Android..

Below is a Simple program with Ksoap using a Webservice.

package com.pxr.tutorial.soap.weather;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Main extends Activity {
 
 private static String SOAP_ACTION = "http://tempuri.org/HelloWorld";
 
 private static String NAMESPACE = "http://tempuri.org/";
 private static String METHOD_NAME = "HelloWorld";
 
 private static String URL = "http://bimbim.in/Sample/TestService.asmx?WSDL";
 
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //Initialize soap request + add parameters
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);        
        request.addProperty("Parameter","Value");
        
        
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(request);
     
        // Make the soap call.
  HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
        try {
         
         //this is the actual part that will call the webservice
   androidHttpTransport.call(SOAP_ACTION, envelope);        
        } catch (Exception e) {
         e.printStackTrace(); 
        }
        
  // Get the SoapResult from the envelope body.  
  SoapObject result = (SoapObject)envelope.bodyIn;
    
  if(result != null){
   TextView t = (TextView)this.findViewById(R.id.resultbox);
   t.setText("SOAP response:\n\n" + result.getProperty(0).toString());
  }
  
    }
}


Here is the Solution to the Above mentioned task! yeY!

package com.harshadura.img_wsdl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class Main extends Activity {

 ImageView image;
 String extStorageDirectory;
 Bitmap decodedByte;

 private int iterator = 0;
 Button btnStartProgress;
 ProgressDialog progressBar;
 private int progressBarStatus = 0;
 private Handler progressBarHandler = new Handler();

 private static String SOAP_ACTION = "http://tempuri.org/TestMethod";
 private static String NAMESPACE = "http://tempuri.org/";
 private static String METHOD_NAME = "TestMethod";
 private static String URL = "http://test.org/ws/testService.asmx?WSDL";

 @Override
 public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  Button buttonDownload = (Button) findViewById(R.id.downloadImages);
  Button buttonDisplay = (Button) findViewById(R.id.displayImages);

  buttonDownload.setOnClickListener(buttonSaveOnClickListener);
  buttonDisplay.setOnClickListener(buttonDisplayClickListener);
  
  createDirIfNotExists("MyImages");  
  extStorageDirectory = Environment.getExternalStorageDirectory()
    .toString() + "/MyImages/";
  Log.v("path", extStorageDirectory);
 }

 public int doSomeTasks() {

  String[] imageIDs = { "123", "124", "125" };

  while (iterator < imageIDs.length) {
   getEncodedImageFromService(imageIDs[iterator]);

   switch (iterator) {
   case 1:
    return 10;
   case 2:
    return 20;
   case 3:
    return 30;
   case 4:
    return 40;
   case 5:
    return 50;
   case 6:
    return 60;
   case 7:
    return 70;
   case 8:
    return 80;
   case 9:
    return 90;
   case 10:
    return 100;
   }
  }

  return 100;
 }

 public static boolean createDirIfNotExists(String path) {
  boolean ret = true;

  File file = new File(Environment.getExternalStorageDirectory(), path);
  if (!file.exists()) {
   if (!file.mkdirs()) {
    Log.e("TravellerLog :: ", "Problem creating Image folder");
    ret = false;
   }
  }
  return ret;
 }

 Button.OnClickListener buttonDisplayClickListener = new Button.OnClickListener() {
  @Override
  public void onClick(View v) {
    Intent intent = new Intent(Main.this, ImageGallery.class);
    startActivity(intent);
  }
 };

 Button.OnClickListener buttonSaveOnClickListener = new Button.OnClickListener() {
  @Override
  public void onClick(View v) {
   progressBar = new ProgressDialog(v.getContext());
   progressBar.setCancelable(true);
   progressBar.setMessage("Retrieving Data...");
   progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
   progressBar.setProgress(0);
   progressBar.setMax(100);
   progressBar.show();
   progressBarStatus = 0;

   new Thread(new Runnable() {
    public void run() {
     while (progressBarStatus < 100) {
      progressBarStatus = doSomeTasks();
      try {
       Thread.sleep(1000);
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
      progressBarHandler.post(new Runnable() {
       public void run() {
        progressBar.setProgress(progressBarStatus);
       }
      });
     }
     if (progressBarStatus >= 100) {
      try {
       Thread.sleep(2000);
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
      iterator = 0;
      progressBar.dismiss();
     }
    }
   }).start();

  }
 };

 public void getEncodedImageFromService(String imageID) {
  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
  request.addProperty("ImageId", imageID);

  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
    SoapEnvelope.VER11);
  envelope.dotNet = true;
  envelope.setOutputSoapObject(request);
  HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
  try {
   androidHttpTransport.call(SOAP_ACTION, envelope);
  } catch (Exception e) {
   e.printStackTrace();
  }

  SoapObject result;
  result = (SoapObject) envelope.bodyIn;

  if (result != null) {
   String encodedImage = result.getProperty(0).toString();
   Log.v("TAG", encodedImage);
   byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
   decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,
     decodedString.length);
   SaveToSDCard();
  }
 }

 public void SaveToSDCard() {
  String imagename = "image" + (iterator + 1) + ".png";
  OutputStream outStream = null;
  File file = new File(extStorageDirectory, imagename);

  try {
   outStream = new FileOutputStream(file);
   decodedByte.compress(Bitmap.CompressFormat.PNG, 100, outStream);
   outStream.flush();
   outStream.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
  iterator++;
 }
}




Thess permissions have to be added in the Android manifest file as well.

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />