Showing posts with label Tutorials. Show all posts
Showing posts with label Tutorials. 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;
  
 }

Linux Directory Structure (File System Structure)

Have you wondered why certain programs are located under /bin, or /sbin, or /usr/bin, or /usr/sbin?
For example, less command is located under /usr/bin directory. Why not /bin, or /sbin, or /usr/sbin? What is the different between all these directories?
In this article, let us review the Linux filesystem structures and understand the meaning of individual high-level directories.


1. / – Root

  • Every single file and directory starts from the root directory.
  • Only root user has write privilege under this directory.
  • Please note that /root is root user’s home directory, which is not same as /.

2. /bin – User Binaries

  • Contains binary executables.
  • Common linux commands you need to use in single-user modes are located under this directory.
  • Commands used by all the users of the system are located here.
  • For example: ps, ls, ping, grep, cp.

3. /sbin – System Binaries

  • Just like /bin, /sbin also contains binary executables.
  • But, the linux commands located under this directory are used typically by system aministrator, for system maintenance purpose.
  • For example: iptables, reboot, fdisk, ifconfig, swapon

4. /etc – Configuration Files

  • Contains configuration files required by all programs.
  • This also contains startup and shutdown shell scripts used to start/stop individual programs.
  • For example: /etc/resolv.conf, /etc/logrotate.conf

5. /dev – Device Files

  • Contains device files.
  • These include terminal devices, usb, or any device attached to the system.
  • For example: /dev/tty1, /dev/usbmon0

6. /proc – Process Information

  • Contains information about system process.
  • This is a pseudo filesystem contains information about running process. For example: /proc/{pid} directory contains information about the process with that particular pid.
  • This is a virtual filesystem with text information about system resources. For example: /proc/uptime

7. /var – Variable Files

  • var stands for variable files.
  • Content of the files that are expected to grow can be found under this directory.
  • This includes — system log files (/var/log); packages and database files (/var/lib); emails (/var/mail); print queues (/var/spool); lock files (/var/lock); temp files needed across reboots (/var/tmp);

8. /tmp – Temporary Files

  • Directory that contains temporary files created by system and users.
  • Files under this directory are deleted when system is rebooted.

9. /usr – User Programs

  • Contains binaries, libraries, documentation, and source-code for second level programs.
  • /usr/bin contains binary files for user programs. If you can’t find a user binary under /bin, look under /usr/bin. For example: at, awk, cc, less, scp
  • /usr/sbin contains binary files for system administrators. If you can’t find a system binary under /sbin, look under /usr/sbin. For example: atd, cron, sshd, useradd, userdel
  • /usr/lib contains libraries for /usr/bin and /usr/sbin
  • /usr/local contains users programs that you install from source. For example, when you install apache from source, it goes under /usr/local/apache2

10. /home – Home Directories

  • Home directories for all users to store their personal files.
  • For example: /home/john, /home/nikita

11. /boot – Boot Loader Files

  • Contains boot loader related files.
  • Kernel initrd, vmlinux, grub files are located under /boot
  • For example: initrd.img-2.6.32-24-generic, vmlinuz-2.6.32-24-generic

12. /lib – System Libraries

  • Contains library files that supports the binaries located under /bin and /sbin
  • Library filenames are either ld* or lib*.so.*
  • For example: ld-2.11.1.so, libncurses.so.5.7

13. /opt – Optional add-on Applications

  • opt stands for optional.
  • Contains add-on applications from individual vendors.
  • add-on applications should be installed under either /opt/ or /opt/ sub-directory.

14. /mnt – Mount Directory

  • Temporary mount directory where sysadmins can mount filesystems.

15. /media – Removable Media Devices

  • Temporary mount directory for removable devices.
  • For examples, /media/cdrom for CD-ROM; /media/floppy for floppy drives; /media/cdrecorder for CD writer

16. /srv – Service Data

  • srv stands for service.
  • Contains server specific services related data.
  • For example, /srv/cvs contains CVS related data.

Ref : http://www.thegeekstuff.com/2010/09/linux-file-system-structure/

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" />

[CRACK] How to SKIP stronghold 3-mission- a glimmer of hope level 11


This file will help the players to skip this level and start with the next level (file unlocks the next level)

File name : campaign_manager_state.xml
Download 

Steps to follow
-just need to replace the existing campaign_manager_state file in the C(main) drive with this file
_________

PS: Thanks Harsha Perera for the hack-script. :)