Monday, November 11, 2013

Debug your Android app without connecting the USB cable

It is annoying to debug an Android application with your device by connecting an USB cable. We are going to know a handy method to debug your app with your device via Wi-Fi without the USB. Let's know it step-by-step. I have done this successfully with Windows and Android 4.0.0.

No need to be ROOTED


1) You have to connect your device with the PC via Wi-Fi
If you have no wireless router and you need to connect your device with the PC via a Wi-Fi adhoc, then you have to convert your PC to a Wi-Fi hot-spot. There is a free and easy application for windows.(For Linux this will be not necessary)
http://www.mhotspot.com/downloadm.html

2) Follow the below Blog by LeoLink®
http://tech.leolink.net/2012/11/use-adb-wifi-without-rooting-for.html
(You have to change the directory of your CMD to "platform-tools" at "sdk" folder)

**Sometimes connection can be lost. Again check the IP address of the device and connect with
adb connect IP ADDRESS

A Simple method to connect your Android phone with PC localhost via Wi-Fi

Especially when we are developing Android applications, we may need to connect our Android application with our personal computer's local host for the testing purposes. The most convenient method to connect both devices is using Wi-Fi. But it is some what difficult to connect Android phones with a Wi-Fi enabled PC via a Ad-Hoc connection without using a separate software.
There is a more simple way to connect your Android phone and PC via Wi-Fi. To use that method your phone need to have the option called "Portable Hotspot" which is used to share your phone's internet connection with other devices via Wi-Fi.
Turn on the "Portable Hotspot" and connect your PC via Wi-Fi. Then open the Command Prompt of your PC and check the "Wireless LAN adapter wireless network connection" information using "ipconfig" command. Then identify the IPv4 address of it.
By using that IP address you can connect with PC's local-host through your Android phone. To check whether phone can access or not, just type the PC's IP address at your phone's web browser's address bar. If the connection is established successfully, you will be able to see welcome screen of your local-host.
Now, it is obvious that you can use that IP with your android applications to connect them with the PC's localhost.     

Thursday, August 22, 2013

RPC program with input parameters and a return value

We will create a RPC (Remote Procedure Calling) program with C which is something advance than 'Hello World'. But it is still simple to understand. In a program like 'Hello World' we cannot learn how to pass parameters or return a value using protocol definitions because those are not required for a simple printing program.
With this program administrator can store any kind of message or notice for other users in the network. Low level user can access to the admin's messages or notices with their client computers by calling to the server computer. Notices can be stored in a simple text file in .txt format. When client requests the service by passing its particular user name and password, server reads the particular text file and return text to the client. We will see step by step how we can develop our simple program.

1. Define the protocol :-
 All our stuff should start with defining the protocol file or .x file.

 struct credintials{
 char uname[200];
 char pwd[200];
};

program NOTICE_PROG{

 version NOTICE_VERS{
 string NOTICE(credintials)=1;
 }=1;

}=0x33674131; 


In the protocol file in RPC we have to define particular input parameters, return type, program name, version and a program number.
In RPC we have to organize all individual parameters in to one data structure and pass as input parameters. In this case we have defined two char arrays to pass user name and the password from the user.
First column of the ninth line defines the return type of the program. This program should return a string which will be read from a text file. Even though in C we don't have a data type called 'string' but a char array, IDL has the key word 'string' for set of characters.
In the third column of the ninth line we have included 'credintials' as a input parameter which we defined as a structure.
Then we have to save this file with .x extension. In this case I save this as notice.x

2. To simply create a RPC program, we need a external program called 'RPC gen' which can automatically generate header, stubs, Makefile and server, client code templates. If you are using ubuntu it is already installed in your system. If you are working with windows, you have to install it.(How ever I recommend you to use ubuntu environment for this task.)
Then you have to check whether all the required libraries are installed. If not you have to install them. To check the availability of those libraries with terminal

>rpcinfo

3. Then we have to run our note.x file with rpcgen and generate the above mentioned files. Just simply type below command in the linux terminal.

>rpcgen -a -C notice.x

Set of files will be genarated as mentioned below :-
Makefile.notice
notice.h
notice_client.c
notice_server.c
notice_clnt.c
notice_xdr.c
notice_svc.c

4. For the ease of commanding you can rename Makefile.notice to Makefile. Makefile includes set of terminal commands related to compiling our RPC program.

5. Then simply type in terminal as

>make

That will compile the program and generate another new set of files as mentioned below :-
notice_client.o
notice_server.o
notice_clnt.o
notice_xdr.o
notice_svc.o
notice_client
notice_server

6. Now you have successfully completed a sketch of a RPC program. Since notice_client and notice_server executable files are already generated, we can execute them by giving following terminal commands.

To start the server program
>sudo ./notice_server

Open another terminal window and run client program
>./notice_client localhost

You will be informed that the connection failed since we have not code the program yet. But already we have the auto generated basic structure of the client and server program as notice_client.c and notice_server.c

7. Now we will code the notice_client.c file as follows. 
#include "notice.h"


void
notice_prog_1(char *host,char *uname,char *pwd)//changed get additional parameters username and password
{
 CLIENT *clnt;
 char * *result_1;
 credintials  notice_1_arg;

#ifndef DEBUG
 clnt = clnt_create (host, NOTICE_PROG, NOTICE_VERS, "udp");
 if (clnt == NULL) {
  clnt_pcreateerror (host);
  exit (1);
 }
#endif /* DEBUG */
 strcpy(notice_1_arg.uname, uname); //set the user name and passwords to the char pointers in the structure
 strcpy(notice_1_arg.pwd, pwd); //set the user name and passwords to the char pointers in the structure

 result_1 = notice_1(&notice_1_arg, clnt); //pass the values to the notice_1() in notice_server.c
 if (result_1 == (char **) NULL) {
  clnt_perror (clnt, "call failed");
 }else{
  printf("Output is : %s\n",*result_1); //print the returned string from the notice_server.c
 }
#ifndef DEBUG
 clnt_destroy (clnt);
#endif  /* DEBUG */
}


int
main (int argc, char *argv[])
{
 char *host;
 char *uname; //Defined char pointer
 char *pwd; //Defined char pointer

 if (argc < 2) {
  printf ("usage: %s server_host\n", argv[0]);
  exit (1);
 }
 host = argv[1];
 uname=argv[2]; //get the username as a command line argument
 pwd=argv[3];   //get the password as a command line argument
 
 notice_prog_1 (host,uname,pwd); //pass all gathered variables to the notice_porog_1 method as parameters 
exit (0);
}


8. Now we will change the notice_server.c file as follows

#include "notice.h"
#include  <string.h>//Additional header file has been included since we uses string functions in our server program

char * getData1();
char * getData2();
char * getData3();
char * getData4();

char **
notice_1_svc(credintials *argp, struct svc_req *rqstp)
{

 printf("Responses to the client");

 static char * result;
 //int authentication=100;

/*Program code for authentication process for 4 individual clients*/
 int authenticUname;
 int authenticPwd;

 int authenticUname1;
 int authenticPwd1;

 int authenticUname2;
 int authenticPwd2;

 int authenticUname3;
 int authenticPwd3;
 
 authenticUname=strcmp(argp->uname,"udara");
 authenticPwd=strcmp(argp->pwd,"123");

 authenticUname1=strcmp(argp->uname,"nimal");
 authenticPwd1=strcmp(argp->pwd,"456");

 authenticUname2=strcmp(argp->uname,"sarath");
 authenticPwd2=strcmp(argp->pwd,"789");

 authenticUname3=strcmp(argp->uname,"kamal");
 authenticPwd3=strcmp(argp->pwd,"147");
 
 
 if(authenticUname==0 && authenticPwd==0){
  result=getData1();
 }else if(authenticUname1==0 && authenticPwd1==0){
  result=getData2();
 }else if(authenticUname2==0 && authenticPwd2==0){
  result=getData3();
 }else if(authenticUname3==0 && authenticPwd3==0){
  result=getData4();
 }else{
  result="Unauthenticated";
 }
 

 return &result;
}


char * getData1(){
 FILE *input;
 input=fopen("notice1.txt","r");
 char *text2;
 char text[1000];
 text2=fgets(text,999,input);
 //strcpy(dest, src);

 
 
 return text2;

}

char * getData2(){
 FILE *input;
 input=fopen("notice2.txt","r");
 char *text2;
 char text[1000];
 text2=fgets(text,999,input);
 //strcpy(dest, src);

 
 
 return text2;

}

char * getData3(){
 FILE *input;
 input=fopen("notice3.txt","r");
 char *text2;
 char text[1000];
 text2=fgets(text,999,input);
 //strcpy(dest, src);

 
 
 return text2;

}

char * getData4(){
 FILE *input;
 input=fopen("notice4.txt","r");
 char *text2;
 char text[1000];
 text2=fgets(text,999,input);
 //strcpy(dest, src);

 
 
 return text2;

}

9. Now we are almost complete. You have to create notice1.txt, notice2.txt, notice3.txt, notice4.txt and include some text.

10. Run make command again and run the client and server program.

Reference :- http://www.cs.rutgers.edu/~pxk/rutgers/notes/rpc/
Source :- https://github.com/udaraseneviratnesmuc/Simple-RPC 

Wednesday, August 14, 2013

Simple RPC Hello World Program

I was given an assignment to create a simple RPC program and run it. After searching the web I found a project from github (https://github.com/JulesWang/helloworld-RPC) by JulesWang. But the problem was I didn't know even to run that simple and user friendly project. Finally I found how to run it in linux platform.
This is how I did it.

1) I downloaded the .zip file from the github and extracted it.

2) I change the directory in my terminal to where I extracted above zip file.

3) According to the given instructions by the creator type following commands on the terminal.

>make
(After execution of that command all the required files will be generated since the project creator has created a makefile including all the commands to generate required files like client, server stubs etc. )

>sudo ./server
(If an error occurred, it means you may have not installed the portmapper. You can check it by >rpcinfo)

>./client localhost
(Type above command in a separate terminal)

4) Hello World output will be generated.

Ubuntu 12.04 not supporting touch pad's right click button problem

This is the solution if your touch pad is not working with Ubuntu 12.04.

1. You have to create a directory called xorg.conf.d in the X11 directory at etc system directory in Ubuntu. Follow the below terminal commands.

sudo mkdir /etc/X11/xorg.conf.d/

2. Create 51.synaptics.conf file using the text editor including following instructions and place it in xorg.conf.d/

Section "InputClass"
Identifier "Default clickpad buttons"
MatchDriver "synaptics"
Option "SoftButtonAreas" "50% 0 82% 0 0 0 0 0"
EndSection


3. I you are unable to create above file in that directory, create it in a possible place and move it to the destination. (Here I created the that file in home folder)

mv 51.synaptics.conf /etc/X11/xorg.conf.d/

(Here mv for 'move' initial parameter is from where and second parameter is for to where.)

4. Log out and Log In to the account

That's all. Problem will be solved





Wednesday, July 17, 2013

Loading a separate page to a DIV using AJAX

In some occasions we need to load a separate page or pages into a div tag without reloading the whole current page. That functionality can be implemented by using AJAX technology.

According to the below code xxxx.php page will be loaded to the div which has the id=content at the load event of the current page.


<html>

        <head>

       //Importing the Jquery library. Tgis can be through offline or online.
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>

         <script>
                    function formLoad(){
                              $('#content').load('xxxx.php'); //AJAX function to load the page.

                      }
        
         </script>

       </head>

       <body OnLoad="formLoad()"> //Call the formLoad() on load event

                 <div id="content"></div>//div to where the external page will be loaded


       </body>

</html>

Wednesday, June 26, 2013

Infinite Array Problem In C#.net

You can't define C#.net arrays with an infinite array length. You must have to provide a length for the array. But there is a solution to fulfill the need of infinite arrays in C#.net.
We call it as List.

We can define a C#.net array like below,
Syntax:-
List<data_type>name_for_list=new List<data_type>();
eg:-
List<char>plainChar=new List<char>();

We can feed data to the list like below,
Syntax:- 
list_name.Add(value_needed_to_add);
eg :-
plainChar.Add('C');

We can retrieve elements from the list like below,
Syntax:- 
list_name[index_of_the_element];
eg:-
plainChar[3];

Saturday, June 8, 2013

How to POST data to a PHP script using HTML as an Array

When we work with HTML and PHP, sometimes we need to send data to a PHP script as an array. As an example consider about a food ordering page. In that case we should provide the functionality of choosing more than one food item in several quantities. If we are not supposing to do this with array, we are required to do more coding with both HTML and JavaScript. With this technique we are using only the HTML for client side and PHP for the server side.

Note : <input type="hidden"> is an important HTML form element which can hold some data to be sent to the PHP script. But they are not visible to the HTML viewers.


foodMenu.html


<form action="foodMenu.php" method="post">
<div>
        <p>Lunch</p>
        <p>
        <span><input type="hidden" value="Food Item 1 " name="itemName[]">Food Item 1
<input type="hidden" value="100" name="itemCost[]">100/=</span><br>
<input type="textbox" value="0" name="itemQTY[]">
<input type="button" value="Select" >
        </p>
        <p>
        <span><input type="hidden" value="Food Item 2" name="itemName[]">Food Item 2
<input type="hidden" value="150" name="itemCost[]">150/=</span><br>
<input type="textbox" value="0" name="itemQTY[]">
<input type="button" value="Select">
        </p>
        <p>
        <span><input type="hidden" value="Food Item 3" name="itemName[]">Food Item 3
<input type="hidden" value="150" name="itemCost[]">150/=</span><br>
<input type="textbox" value="0" name="itemQTY[]">
<input type="button" value="Select" >
        </p>
<input type="submit" value="Submit" >
 </div>


foodMenu.php


<?php   

$itemName=$_POST['itemName'];  //Grab the posted item names from the html form
$itemQTY=$_POST['itemQTY'];    //Grab the posted item QTY from the html form
$itemPrice=$_POST['itemCost'];  //Grab the posted item prices from the html form

$grandTotal=0;
echo('<table>');
echo('<tr><td>Meal List</td></tr>');
echo('<tr><td>Items</td><td>QTY</td><td>Cost</td></tr>');

for($count=0;$count<count($itemName);$count++){ //loop to print stored data in the arrays
    if($itemQTY[$count]>0){
        echo("<tr>");
        echo('<td>'.$itemName[$count].'</td><td>'.$itemQTY[$count].'</td><td>'.subTotal($itemPrice,$itemQTY,$count));
        echo("</tr>");
    }
}
echo('<tr>');
    echo('<td>'.'</td><td>'.totalQTY($itemQTY).'</td><td>'.$grandTotal.'</td>');                                             
    echo('</tr>');
echo('</table>');
//function to calculate sub totals and grand totals
function subTotal($itemPrice,$itemQTY,$count){
 global $grandTotal;  //refer to above global variable at the begining
$subTotal[$count]=$itemPrice[$count]*$itemQTY[$count];
$grandTotal=$grandTotal+$subTotal[$count];

return $subTotal[$count];

}
//function to calculate the total number of the QTYs
function totalQTY($itemQTY){
return array_sum($itemQTY);
}
?>

Tuesday, May 28, 2013

Popular SMTP settings

Following are setting information to configure a connection to the particular SMTP servers. SMTP or Simple Mail Transfer Protocol is relate with the mail transferring over the Internet.

Gmail
SMTP server address : smtp.gmail.com
SMTP user name : Your full Gmail address (e.g. example@gmail.com)
SMTP password : Your Gmail password
SMTP port : 465
SMTP TLS/SSL required : Yes
Ymail
SMTP server address : smtp.mail.yahoo.com
SMTP user name : Your full Yahoo! Mail email address (including "@yahoo.com")
SMTP password : Yahoo! Mail password
SMTP port : 465
SMTP TLS/SSL required : Yes
AOL
SMTP server address : smtp.aol.com
SMTP user name : Your AOL Mail screen name (what comes before "@aol.com" in your AOL Mail address; if your address is me@aol.com, for example, the corresponding screen name is "me")
SMTP password : Your AOL Mail password
SMTP port : 587 (alternative: 465)
SMTP TLS/SSL required : Yes
Hotmail
SMTP server address : smtp.live.com
SMTP user name : Your full Windows email address (including "@yahoo.com")
SMTP password : Windows live hotmail password
SMTP port : 587
SMTP TLS/SSL required : Yes

Assume that we have sent a E-Mail to the address of abc@gmail.com through GMAIL mail engine. Since we have sent it through GMAIL, our mail is sent to the GMAIL SMTP server via the port 465. Then it reads the recipient's address. The part after the @ says recipient also holds an gmail account. So, SMTP server redirect the mail to GMAIL POP3 server. POP3 server identifies the particular recipient from the address part before the @ and link the particular mail to his account. Recipient log into the POP3 server using his user name and password and read the mail.

Assume what happens if we have sent the particular mail to abc@gmail.com via the YMAIL mail engine. If so, YMAIL SMTP server look at the address part after the @ and understand that recipient doesn't has an account in YMAIL POP3 server. So, it re-directs the mail to the particular SMTP server indicated at the address. After it has been sent to the GMAIL SMTP server same routine is happening as mentioned in the above paragraph.

Sunday, May 26, 2013

Find number of days between given two days in PHP

We are going to study how can we calculate the number of days between given two days. For the example I am going to find the number of days between current date and another given date.

<?php

    $year="1990";
    $month="March";
    $day="23";


$today=date('Y-m-d'); // in-built function to get current date.

$datetime1 = date_create($year.'-'.$month.'-'.$day); //Given date
$datetime2 = date_create($today); //System date for current date
$interval = date_diff($datetime1, $datetime2); //$datetime2 - $datetime1
$date_amount= $interval->format('%R%a');

echo($date_amount);

?>

Automatically populate SELECT items in HTML using JAVASCRIPT

We are going to learn how we can automatically populate a data set to view in a select element in HTML using javascript. As an example we will populate set of years, months and dates inside of select element which can be used to input a particular birthday in a HTML form.


<script language="javascript">

             function loadYears(){
            var sel = document.getElementById('year');

// 'new Date().getFullYear()' is used to get current year.

            for(var i = 1950; i <= new Date().getFullYear(); i++) {
            var opt = document.createElement('option');
            opt.innerHTML = i;
            opt.value = i;
            sel.appendChild(opt);
            }
            }
           
            function loadDays(){


            document.getElementById('day').innerHTML = ""; //initially clears the data items which were included by the previous function invokes.

            var sel = document.getElementById('day');

     // if/else set is to decide the number of days for a particular month.     

 
   if(document.getElementById('month').value!='February' && document.getElementById('month').value!='April' && document.getElementById('month').value!='June' && document.getElementById('month').value!='August' && document.getElementById('month').value!='November' && document.getElementById('month').value!='September'){
                for(var i = 1; i < 32; i++) {
                var opt = document.createElement('option');
                opt.innerHTML = i;
                opt.value = i;
                sel.appendChild(opt);
                }
                }else{
               
                for(var i = 1; i < 31; i++) {
                var opt = document.createElement('option');
                opt.innerHTML = i;
                opt.value = i;
                sel.appendChild(opt);
                }
            }
            }
           
            function loadMonths(){

//JavaScript array to store the names of the months
 var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];    
            var sel = document.getElementById('month');
            for(var i = 0; i < months.length; i++) {
            var opt = document.createElement('option');
            opt.innerHTML = months[i];
            opt.value = months[i];
            sel.appendChild(opt);
            }
            }
        </script>

<body onload="loadYears();loadMonths()"> <!-- According to my logic Year and month generation functions should be invoked at the body onload event -->

<!-- Following are the particular select elements on the html page -->
<select id="year" name="year"></select>
               
<select id="month" name="month" onclick="loadDays()"> </select><!-- According to my logic days should be loaded at the time of choosing the month. So I invoked that function by the event of onclick here. -->
                           
<select id="day" name="day"></select>

Friday, May 17, 2013

Example Multi Dimensional Array In PHP

Hi ! Multi Dimensional Array or Arrays inside an Array is a basic and useful data structure in PHP. This post is regarding an example which describe you how to declare a multi dimensional array, how to insert data to it, how to print back those elements and how to manipulate those datum.

In this example population amounts in America is categorized into states and to each city. We have to organize them in an array, Print back them and find totals under each states and country.


<?php 
//Multi Dimensional Array
    $population=array(
                            'NY'=>array('New York'=>8008278),
                            'CA'=>array('Los Angeles'=>3694420,'San Diego'=>1223400),
                            'IL'=>array('Chicago'=>2896016),
                            'TX'=>array('Houstan'=>1953631,'Dallas'=>1188580,'San Antonio'=>1144646),
                            'AZ'=>array('Phoenix'=>1321045)
                          
                        );
                  
    $totalStatePopulation=0;                  
    $totalPoupulation=0;
   
    echo('<table border="1" width="400px">');
//$population refers to the above array $state refers to its keys(NY,CA,IL,TX,AZ) $city refers to its values(array('New York'=>8008278),array('Los Angeles'=>3694420,'San Diego'=>1223400),array('Chicago'=>2896016),array('Houstan'=>1953631,'Dallas'=>1188580,'San Antonio'=>1144646),array('Phoenix'=>1321045))
    foreach($population as $state=>$city){
        $totalStatePopulation=0;
      
         //$city is the same variable in the outer loop. So, $name refers to array $city 's keys. $amount is the population amount under each key.
            foreach($city as $name=>$amount){
            echo('<tr>');
//print the keys of the inner arrays
            echo('<td>'.$name.'</td>');
//prints the amounts under inner keys
            echo('<td>'.$amount.'</td>');
            echo('</tr>');
//calculate the state population of the country
            $totalStatePopulation=$totalStatePopulation+$amount;
//calculate the total population of the country
            $totalPoupulation=$totalPoupulation+$amount;
            }
          
          
            echo('<tr>');
//prints the keys of the outer array
            echo('<td>'.$state.'</td>');
            echo('<td style="color:green;font-weight:bold">'.$totalStatePopulation.'</td>');
            echo('</tr>');
    }
   
            echo('<td>Total Population</td>');
            echo('<td style="color:red;font-weight:bold">'.$totalPoupulation.'</td>');
    echo('</table>');


?>

Wednesday, May 15, 2013

How to submit data with Ajax

Hi ! This post is about a way that you can submit (to a PHP Script) a collection of data which have been collected by a HTML form . Here we are going to do it with Ajax technology. Even though this is a simple post you are required to have a somewhat knowledge in Java Script and PHP for a better understanding.
  1. Visit the JQuery site and download the JQuery API. ( Direct link to the API. Just save the page as .js)
  2. Link the JQuery API with your web page where the form is located.
  3. Write a Java Script function to collect data from the form by the IDs of the form items and send them to the PHP script. 

Form.php

<html>
<head>
    <title></title>
    <script type="text/javascript" src="jScript/jquery-1.9.1.min.js"></script> <!-- Link to the JQuery API-->
    <script>
    <!--JavaScript Function-->
    function formSubmit(){

       $.ajax({ // create an AJAX call...
        type: "POST",  // Submitting Method is POST
    url: "collectData.php", // To where the data should be submitted 
    data: { firstName: $('#fName').val(),    //Value in the textbox which is identified by ID 'fName' will be transmitted to variable firstName in the PHP script
            lastName: $('#lName').val(), //Value in the textbox which is identified by ID 'lName' will be transmitted to variable lastName in the PHP script
            age: $('#age').val(), // Value in the textbox which is identified by ID 'age' will be transmitted to variable age in the PHP script           
        },
        success: function(response) { // on success..
                alert(response);   // parameter response retrives any data which are echo by the PHP script
        }
    });
    return false;
    }
    </script>
   
</head>
    <body>
            <form onsubmit="return formSubmit()">  <!-- formSubmit() will be called at the event of click on the submit button of the particular form -->   
                <table>
                    <tr>
                    <td>First Name :</td>
                    <td><input type="text" id="fName"></td>
                    </tr>
                    <tr>
                    <td>Last Name :</td>
                    <td><input type="text" id="lName"></td>
                    </tr>
                    <tr>
                    <td>Age :</td>
                    <td><input type="text" id="age"></td>
                    </tr>
                    <tr>
                    <td></td>
                    <td><input type="submit" value="Submit"></td>
                    </tr>
                </table>
            </form>
    </body>
</html>




collectData.php

<?php   

$firstName=$_POST['firstName']; //Catch the data from form.php and store it in the particular variable
$lastName=$_POST['lastName'];
$age=$_POST['age'];

//Now we have stored the required data in the PHP script. Anything can be done on that data with PHP.


echo("Success"); // This statement will be returned to the parameter response.

?>



With this method you will not be re-directed to the PHP file as the traditional way. Have fun !!!!!