skip to main |
skip to sidebar
RSS Feeds
Nope. nothing .. just some random thoughts come to my mind ...
Nope. nothing .. just some random thoughts come to my mind ...
5:41 PM | Sunday, June 9, 2013
Posted by harshadura
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.
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();
}
}
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;
}
1:18 PM | Thursday, December 6, 2012
Posted by harshadura
Feels like a local API, much like XMLRPCREST:
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
easy to route around firewallsIn short from here
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)
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
5:41 AM | Monday, October 29, 2012
Posted by harshadura
Distributed Component Based Software Development by using ASP.NET Web Services and Web Portals.
7:43 PM | Monday, July 16, 2012
Posted by harshadura
Directory “c:/wamp/www/”Find and replace ’127.0.0.1′ with ‘All’
#
# 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
3:35 PM | Wednesday, July 4, 2012
Posted by harshadura
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());
}
}
}
10:43 PM | Tuesday, July 3, 2012
Posted by harshadura
<?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/
6:47 PM | Saturday, February 4, 2012
Posted by harshadura
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.
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());
}
}
}
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++;
}
}