Amazon Ad

Saturday, 20 October 2012

REST Services With Phonegap Android

Hi Guys,

Hope you are doing fine. Today I am going to share how to work with WCF(REST Services) made in asp.net and connecting it with phonegap android app.

Here goes the step wise description

Step 1 :Create a WCF Webservice in asp.net name it Plumber.

Create a WCF webservice in a new asp.net web application. By default the service name is Service1.svc. Two files are created one is the interface and second is the implementation file.

In the interface i.e IService1.svc add the following lines


[OperationContract]
        [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "SearchWorkBook")]
        List<PlumberWork> SearchWorkBook(string PlumberId, string HouseNo,string PostCode,string BoilerCode);

In Service1.svc add the following method


public List<PlumberWork> SearchWorkBook(string PlumberId, string HouseNo,string PostCode,string BoilerCode)
        {
            if (con.State == System.Data.ConnectionState.Closed)
                con.Open();

            List<PlumberWork> list = new List<PlumberWork>();
            string query = "[pSearchWorkBook]";
            SqlCommand cmd = new SqlCommand(query, con);
            cmd.Parameters.AddWithValue("@PlumberId", PlumberId);
            cmd.Parameters.AddWithValue("@HouseNo", HouseNo);
            cmd.Parameters.AddWithValue("@PostCode", PostCode);
            cmd.Parameters.AddWithValue("@BoilerCode", BoilerCode);

            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter adapt = new SqlDataAdapter(cmd);

            DataSet ds = new DataSet();
            adapt.Fill(ds);
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                PlumberWork obj = new PlumberWork();
                obj.SerialNo = ds.Tables[0].Rows[i]["SerialNo"].ToString();
                obj.PostCode = ds.Tables[0].Rows[i]["PostCode"].ToString();
                obj.Notes = ds.Tables[0].Rows[i]["Notes"].ToString();
                obj.EntryDate = ds.Tables[0].Rows[i]["EntryDate"].ToString();
                list.Add(obj);
            }
            return list;
        }
   
After the class ends add another class


 public class PlumberWork
    {
        public string SerialNo{get;set;}
        public string PostCode{get;set;}
        public string Notes{get;set;}
        public string EntryDate { get; set; }
    }




Step 2: Configure the web.config.


    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
    </system.webServer>

    <system.serviceModel>
        <services>
            <service name="Plumber.Service1" behaviorConfiguration="ATServiceBehavior">
                <endpoint address="" binding="webHttpBinding" contract="Plumber.IService1" behaviorConfiguration="web" bindingConfiguration="RestServiceBindingConfig">
                </endpoint>
            </service>
        </services>
        <bindings>
            <webHttpBinding>
                <binding crossDomainScriptAccessEnabled="true" name="RestServiceBindingConfig">
                    <security mode="None"></security>
                </binding>
            </webHttpBinding>
        </bindings>
        <behaviors>
            <serviceBehaviors>
                <behavior name="ATServiceBehavior">
                    <serviceMetadata httpGetEnabled="true"/>
                    <serviceDebug includeExceptionDetailInFaults="true" />
                </behavior>
            </serviceBehaviors>
            <endpointBehaviors>
                <behavior name="web">
                    <webHttp defaultOutgoingResponseFormat="Json" helpEnabled="true"/>
                </behavior>
            </endpointBehaviors>
        </behaviors>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    </system.serviceModel>


Step 3: Create global.asax file for cross domain ajax configuration.

Add the following in your Application_BeginRequest


protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
             
                //For GET
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                //For POST
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, x-requested-with");

                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }

       
        }


Step 4: Publish it on IIS.
Step 5: Create a phonegap application.
Step 6: Call WCF service using jquery ajax.


 function searchwork()
        {
            var servicepath = "http://IP_Address_Of_Computer_Hosting(IIS)/PlumberService/";
            var PlumberId="13";
            var HouseNo = "EA 3772";
            var PostCode = "L1A89A";
            var BoilerCode = "B9022A33A";

            alert('{"PlumberId":"' + PlumberId + '","HouseNo":"' + HouseNo + '","PostCode":"' + PostCode + '","BoilerCode":"'+BoilerCode+'"}');
            $.ajax({
                data: '{"PlumberId":"' + PlumberId + '","HouseNo":"' + HouseNo + '","PostCode":"' + PostCode + '","BoilerCode":"' + BoilerCode + '"}',
                type: "POST",
                dataType: "json",
                contentType: "application/json;charset=utf-8",
                url: servicepath + "PlumberService.svc/SearchWorkBook",
                success: function (data) {
                    for (i = 0; i < data.SearchWorkBookResult.length; i++) {
                        document.write("<br>");
                        document.write(data.SearchWorkBookResult[i].SerialNo);
                        document.write(data.SearchWorkBookResult[i].make);
                        document.write(data.SearchWorkBookResult[i].model);
                        document.write(data.SearchWorkBookResult[i].installationdate);
                        document.write(data.SearchWorkBookResult[i].gcnumber);
                        document.write(data.SearchWorkBookResult[i].gascertificateexpirydate);
                        document.write(data.SearchWorkBookResult[i].HouseNo);
                        document.write(data.SearchWorkBookResult[i].PostCode);
                        document.write(data.SearchWorkBookResult[i].Notes);
                        document.write(data.SearchWorkBookResult[i].EntryDate);
                    }
                },
                error: function (a, e, d) { alert(e + ' ' + d); }
            });
        }


Hope you enjoyed, Please do give your comments.

Thanks
Ritesh Tandon

Wednesday, 23 May 2012

Binding Multiple Spinner Controls with sqllite

hi guys,

hope you are doing well in android. Today my code is about binding multiple dependent spinner controls. These spinner controls are binded with the sql lite database which i would be dealing in my next post. The following code would give you an idea about how to bind multiple spinner controls.

Step1 Bind the spinners
Step2 based on the selection of search create an array
Step3 check the selection made by the user and remove the dependents in case the user selects the default value from the spinner control.
Step4 bind the data and pass it on to the result page.

Hope you guys get some idea about binding the spinner control. Here is the code


package ritesh.tandon.advancsearch



import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class GuestProgramSearch extends Activity
{
    DBHelper MyDB=new DBHelper(this);
    SQLiteDatabase db;
    TextView tv;
    String textMake="Select",textModel="Select",textEditionType="Select",textColour="Select";
    Button btnSearch,btnReset;
    Spinner spinnerMake,spinnerModel,spinnerEdition,spinnerColour;
    Context mctx;
    String Make="",Model="",Editiontype="",Colour="",searchtype="",searchvalue="";
    List<String> dropdownsarray = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.guestprogramsearch);
        tv=(TextView)findViewById(R.id.editTextSearchProgram);
      
        mctx=this;
        ConnectivityManager conMgr =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
      
        if ( conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED  ||  conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED  ) {
            CarSearch srch=new CarSearch();
            srch.createandUpdate( mctx);
        }
        else if ( conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||  conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {
            Toast.makeText(mctx, "You are Not Connected with internet", Toast.LENGTH_LONG).show();
        }

      
        btnSearch=(Button)findViewById(R.id.btnSearch);
        btnReset=(Button)findViewById(R.id.btnReset);
      
      
      
        final String cols[]={"Make"};
        final String cols1[]={"Model"};
        final String cols2[]={"EditionType"};
        final String cols3[]={"Colour"};
      
        spinnerMake =(Spinner)findViewById(R.id.spinnerMake);
        spinnerMake.setAdapter(BindSpinner("Cars",cols,null,true,""));
        spinnerMake.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
            {
                String selected = parentView.getItemAtPosition(position).toString();
              
                if(textMake.equals("Select") && !selected.equals("Select"))
                {
                  
                    dropdownsarray.add("Make");
                }
                else if(!textMake.equals("Select") && !selected.equals("Select"))
                {
                  
                    int index=dropdownsarray.indexOf("Make");
                    for(int i=index+1;i<dropdownsarray.size();i++)
                    {
                        if(dropdownsarray.get(i).equals("Make"))
                            textMake="Select";
                        else if(dropdownsarray.get(i).equals("Model"))
                            textModel="Select";
                        else if(dropdownsarray.get(i).equals("EditionType"))
                            textEditionType="Select";
                        else if(dropdownsarray.get(i).equals("Colour"))
                            textColour="Select";
                        dropdownsarray.remove(i);
                    }
                    removedependents("Make");
                   
                }
                else if(!textMake.equals("Select") && selected.equals("Select"))
                {
                   
                    removedependents("Make");
                    dropdownsarray.remove("Make");
                }
                textMake=selected;
                SearchUpdated();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
            }
        });
      
              
      
        spinnerModel =(Spinner)findViewById(R.id.spinnerModel);
        spinnerModel.setAdapter(BindSpinner("Cars",cols1,null,true,""));
        spinnerModel.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
            {
                String selected = parentView.getItemAtPosition(position).toString();
                if(textModel.equals("Select") && !selected.equals("Select"))
                {
                  
                    dropdownsarray.add("Model");
                }
                else if(!textModel.equals("Select") && !selected.equals("Select"))
                {
                 
                  
                    int index=dropdownsarray.indexOf("Model");
                    for(int i=index+1;i<dropdownsarray.size();i++)
                    {
                        if(dropdownsarray.get(i).equals("Make"))
                            textMake="Select";
                        else if(dropdownsarray.get(i).equals("Model"))
                            textModel="Select";
                        else if(dropdownsarray.get(i).equals("EditionType"))
                            textEditionType="Select";
                        else if(dropdownsarray.get(i).equals("Colour"))
                            textColour="Select";
                        dropdownsarray.remove(i);
                    }
                    removedependents("Model");
                  
                }
                else if(!textModel.equals("Select") && selected.equals("Select"))
                {
                   
                    removedependents("Model");
                    dropdownsarray.remove("Model");
                  
                }
              
                textModel=selected;
                SearchUpdated();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
            }
        });
      
      
        spinnerEdition =(Spinner)findViewById(R.id.spinnerEdition);
        spinnerEdition.setAdapter(BindSpinner("Cars",cols2,null,true,""));
        spinnerEdition.setOnItemSelectedListener(new OnItemSelectedListener()
        {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
            {
                String selected = parentView.getItemAtPosition(position).toString();
                if(textEditionType.equals("Select") && !selected.equals("Select"))
                {
                   
                    dropdownsarray.add("EditionType");
                }
                else if(!textEditionType.equals("Select") && !selected.equals("Select"))
                {
                    //again selection
                  
                    int index=dropdownsarray.indexOf("EditionType");
                    for(int i=index+1;i<dropdownsarray.size();i++)
                    {
                        if(dropdownsarray.get(i).equals("Make"))
                            textMake="Select";
                        else if(dropdownsarray.get(i).equals("Model"))
                            textModel="Select";
                        else if(dropdownsarray.get(i).equals("EditionType"))
                            textEditionType="Select";
                        else if(dropdownsarray.get(i).equals("Colour"))
                            textColour="Select";
                        dropdownsarray.remove(i);
                    }
                    removedependents("EditionType");
                  
                }
                else if(!textEditionType.equals("Select") && selected.equals("Select"))
                {
                    //Select selected again
                    removedependents("EditionType");
                    dropdownsarray.remove("EditionType");
                }
              
                textEditionType=selected;
                SearchUpdated();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
            }
        });
      
      
        spinnerColour =(Spinner)findViewById(R.id.spinnerColour);
        spinnerColour.setAdapter(BindSpinner("Cars",cols3,null,true,""));
        spinnerColour.setOnItemSelectedListener(new OnItemSelectedListener()
        {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
            {
                String selected = parentView.getItemAtPosition(position).toString();
                if(textColour.equals("Select") && !selected.equals("Select"))
                {
                   
                    dropdownsarray.add("Colour");
                }
                else if(!textColour.equals("Select") && !selected.equals("Select"))
                {
                    //again selection
                  
                    int index=dropdownsarray.indexOf("Colour");
                    for(int i=index+1;i<dropdownsarray.size();i++)
                    {
                        if(dropdownsarray.get(i).equals("Make"))
                            textMake="Select";
                        else if(dropdownsarray.get(i).equals("Model"))
                            textModel="Select";
                        else if(dropdownsarray.get(i).equals("EditionType"))
                            textEditionType="Select";
                        else if(dropdownsarray.get(i).equals("Colour"))
                            textColour="Select";
                        dropdownsarray.remove(i);
                    }
                    removedependents("Colour");
                 
                  
                }
                else if(!textColour.equals("Select") && selected.equals("Select"))
                {
                    //Select selected again
                    removedependents("Colour");
                    dropdownsarray.remove("Colour");              
                }
              
                textColour=selected;
                SearchUpdated();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
            }
        });

        btnSearch.setOnClickListener(new OnClickListener()
        {
            boolean flg=false;
            @Override
            public void onClick(View arg0)
            {
                // TODO Auto-generated method stub
                searchvalue=tv.getText().toString();
                Intent intent=new Intent(mctx,GuestProgramSearchResults.class);
                intent.putExtra("Make", textMake);
                intent.putExtra("Model", textModel);
                intent.putExtra("Colour", textColour);
                intent.putExtra("EditionType", textEditionType);
                intent.putExtra("SearchText",searchvalue);
              
                    if(!searchvalue.equals("") || (!textMake.equals("Select")) || (!textModel.equals("Select")) || (!textColour.equals("Select")) || (!textEditionType.equals("Select")))
                    {
                            flg=true;
                    }
                    else
                    {
                        Toast.makeText(mctx, "Please Select At Least One Option To Search.", Toast.LENGTH_SHORT).show();
                        flg=false;
                    }
              
               
              
               
                if(flg==true)
                    startActivity(intent);
              
                }      
        });
      
      
        btnReset.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                textMake="Select";
                textModel="Select";
                textEditionType="Select";
                textColour="Select";
                spinnerMake.setAdapter(BindSpinner("Cars",cols,null,true,""));
                spinnerModel.setAdapter(BindSpinner("Cars",cols1,null,true,""));
                spinnerEdition.setAdapter(BindSpinner("Cars",cols2,null,true,""));
                spinnerColour.setAdapter(BindSpinner("Cars",cols3,null,true,""));
                tv.setText("");
                dropdownsarray.clear();
                textMake="Select";
                textModel="Select";
                textEditionType="Select";
                textColour="Select";
            }      
        });
      
      
    }
  
    public void removedependents(String dropdownsarrayvalue)
    {
      
        int index=dropdownsarray.indexOf(dropdownsarrayvalue);
        if(index!=-1)
        {
            for(int i=index+1;i<dropdownsarray.size();i++)
            {
                String[] c={dropdownsarray.get(i)};
                //tv.setText(tv.getText()+", "+c[0]);
                if(c[0].equals("Make"))
                    spinnerMake.setAdapter(BindSpinner("Cars",c,null,true,""));
                else if(c[0].equals("Model"))
                    spinnerModel.setAdapter(BindSpinner("Cars",c,null,true,""));
                else if(c[0].equals("EditionType"))
                    spinnerEdition.setAdapter(BindSpinner("Cars",c,null,true,""));
                else if(c[0].equals("Colour"))
                    spinnerColour.setAdapter(BindSpinner("Cars",c,null,true,""));
            }
          
        }
    }
  
    public void SearchUpdated()
    {
        try
        {
            if(dropdownsarray.size()>0)
            {  
                  
              
                    String[] cols=new String[dropdownsarray.size()];
                        dropdownsarray.toArray(cols);
              
                    String[] vals=new String[dropdownsarray.size()];

                  
                    for(int i=0;i<dropdownsarray.size();i++)
                    {
                        if(dropdownsarray.get(i).equals("Make"))
                            vals[i]=textMake;
                        else if(dropdownsarray.get(i).equals("Model"))
                            vals[i]=textModel;
                        else if(dropdownsarray.get(i).equals("EditionType"))
                            vals[i]=textEditionType;
                        else if(dropdownsarray.get(i).equals("Colour"))
                            vals[i]=textColour;
                    }
                  
                   
                  
                   
                    if(textMake.equals("Select"))
                        spinnerMake.setAdapter(BindSpinner("Cars",cols,vals,false,"Make"));
                    if(textModel.equals("Select"))
                        spinnerModel.setAdapter(BindSpinner("Cars",cols,vals,false,"Model"));
                    if(textEditionType.equals("Select"))
                        spinnerEdition.setAdapter(BindSpinner("Cars",cols,vals,false,"EditionType"));
                    if(textColour.equals("Select"))
                        spinnerColour.setAdapter(BindSpinner("Cars",cols,vals,false,"Colour"));
                      
            }
        }
        catch(Exception ex)
        {
            tv.setText(ex.toString());
        }
    }
  
    public void  checkNetworkStatus(){

        final ConnectivityManager connMgr = (ConnectivityManager)
         this.getSystemService(Context.CONNECTIVITY_SERVICE);

         final android.net.NetworkInfo wifi =
         connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

         final android.net.NetworkInfo mobile =
         connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

         if( wifi.isAvailable() ){

         Toast.makeText(this, "Wifi" , Toast.LENGTH_LONG).show();
         }
         else if( mobile.isAvailable() ){

         Toast.makeText(this, "Mobile 3G " , Toast.LENGTH_LONG).show();
         }
         else
         {

             Toast.makeText(this, "No Network " , Toast.LENGTH_LONG).show();
         }

    }
    protected void alertbox(String title, String mymessage)
    {
    new AlertDialog.Builder(this)
       .setMessage(mymessage)
      .setTitle(title)
       .setCancelable(true)
       .setNeutralButton(android.R.string.cancel,
          new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton){}
          })
       .show();
    }
    protected ArrayAdapter<String> BindSpinner(String tablename,String[] ColumnNames,String[] ColumnValues,boolean isload,String FieldName)
    {
      
        try
        {
            List<String> x = new ArrayList<String>();
            x.add("Select");
          
          
            MyDB.createDataBase(mctx);
            db=MyDB.openDataBaseFromother();
          
          
            if(isload)
            {
                Cursor c1=db.query(true,tablename,ColumnNames, null, null, null, null, null, null);
                for(c1.moveToFirst(); !c1.isAfterLast(); c1.moveToNext())
                {
                    x.add(c1.getString(0));
                }
                c1.close();
              
            }
            else
            {
                String[] Cols={FieldName};
                String query="",query1="";
                for(int j=0;j<ColumnNames.length;j++)
                {
                    if(query=="")
                    {
                        query=ColumnNames[j]+" = ?";
                        query1=ColumnNames[j]+" = "+ColumnValues[j];
                    }
                    else
                    {
                        if (!query.toString().contains(ColumnNames[j]))
                        {
                            query+=" And "+ColumnNames[j]+" = ?";
                            query1+=" And "+ColumnNames[j]+" = "+ColumnValues[j];
                        }
                    }
                }
                if(ColumnNames.length>0)
                {
              
                Cursor c1=db.query(true,tablename,Cols,query, ColumnValues, null, null, null, null);
                for(c1.moveToFirst(); !c1.isAfterLast(); c1.moveToNext())
                {
                    x.add(c1.getString(0));
                }
                c1.close();
                }
            }
            db.close();
          
                  
            ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, x);
            return spinnerArrayAdapter;
        }
        catch(Exception ex)
        {
            if(db.isOpen())
                db.close();
            Log.w("Error", ex.toString());
            return null;
        }
      
    }

  
}

Tuesday, 22 May 2012

Get Directions Using Phonegap And Google API v3

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width,
minimum-scale=1, maximum-scale=1">
   <title>Map</title>

   <link rel="stylesheet" href="css/jquery.mobile-1.1.0.min.css" />

   <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
   <script type="text/javascript" src="js/jquery.mobile-1.1.0.min.js"></script>
   <script type="text/javascript" src="http://www.google.com/jsapi"></script>
   <script type="text/javascript" src="js/cordova-1.7.0.js"></script>

<script type="text/javascript">

var map;
var marker;
var infowindow;
var watchID;

$(document).ready(function(){
   document.addEventListener("deviceready", onDeviceReady, false);
   //for testing in Chrome browser uncomment
   //onDeviceReady();
});

//PhoneGap is ready function
function onDeviceReady() {
   $(window).unbind();
   $(window).bind('pageshow resize orientationchange', function(e){
       max_height();
   });
   max_height();
   google.load("maps", "3.8", {"callback": map, other_params:
"sensor=true&language=en"});
}

function max_height(){
   var h = $('div[data-role="header"]').outerHeight(true);
   var f = $('div[data-role="footer"]').outerHeight(true);
   var w = $(window).height();
   var c = $('div[data-role="content"]');
   var c_h = c.height();
   var c_oh = c.outerHeight(true);
   var c_new = w - h - f - c_oh + c_h;
   var total = h + f + c_oh;
   if(c_h<c.get(0).scrollHeight){
       c.height(c.get(0).scrollHeight);
   }else{
       c.height(c_new);
   }
}

function map(){
   var latlng = new google.maps.LatLng(31.0167908, 27.8512211);
   var latlng1 = new google.maps.LatLng(31.0167908, 27.1078541);

   var myOptions = {
     zoom: 12,
     center: latlng,
     streetViewControl: true,
     mapTypeId: google.maps.MapTypeId.ROADMAP,
     zoomControl: true
   };
   map = new google.maps.Map(document.getElementById("map"), myOptions);



       var directionsService = new google.maps.DirectionsService();
       var directionDisplay;
       directionsDisplay = new google.maps.DirectionsRenderer();
       directionsDisplay.setMap(map);

       var request = {origin:latlng,destination:latlng1,travelMode:
google.maps.TravelMode.DRIVING  };
       directionsService.route(request, function(response, status) {
       if (status == google.maps.DirectionsStatus.OK)
       {
               directionsDisplay.setDirections(response);
               computeTotalDistance(directionsDisplay.directions);
       }

       if(!marker)
       {
       //create marker
       marker = new google.maps.Marker({position: latlng,map: map});
       var infowindow = new google.maps.InfoWindow({content: "Midwife"});
       google.maps.event.addListener(marker, 'click', function()
       {
               infowindow1.close();
               infowindow.open(map,marker);
       });
       marker.setMap(map);
       marker1 = new google.maps.Marker({position: latlng1,map: map});
       var infowindow1 = new google.maps.InfoWindow({content: "Patient"});
       google.maps.event.addListener(marker1, 'click', function()
       {
               infowindow.close();
               infowindow1.open(map,marker1);
       });
       marker1.setMap(map);
   }

});

}

function geo_error(error){
   //comment
   alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}

function computeTotalDistance(result)
{
 var total = 0;
 var myroute = result.routes[0];
 for (i = 0; i < myroute.legs.length; i++)
 {
   total += myroute.legs[i].distance.value;
 }
 total = total / 1000.
 document.getElementById("distance").innerHTML = "Distance : "+total + " km";
}

</script>

</head>
<body>

<div data-role="page" id="index">
   <div data-role="header" data-theme="b"><h1>Map Header</h1></div>
   <div data-role="content" style="padding:0;">
       <div id="distance" style="border; 1px solid black;font-size:13px"></div>
       <div id="map" style="width:100%;height:100%;"></div>
       <div id="route" style="width: 25%; height:480px; float:right;
border; 1px solid black;"></div>
   </div>
   <div data-role="footer" data-theme="b"><h4>Map Footer</h4></div>
</div>

</html>

Tuesday, 15 May 2012

GPS System Using Google Map and PhoneGap Android


Hi Folks!,

Today i am going to tell you about the GPS system which actually makes a path on the map when the device is moved from one location to another.The application works like this

Step1 The geolocation of the device is detected by the geolocation.js provided by phonegap.

Step2. The timer checks the location after every 3 seconds.

Step3. The map is updated.

Below is the complete code for it.

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map_canvas { height: 100% }
    </style>
    <script src="cordova-1.6.1.js" type="text/javascript"></script>
    <script type="text/javascript">
    var cycle=0,lat,lng,finallat,finallng,image,myLatLng,carMarker,map,myOptions,carPlanCoordinates=[],carPath,image1,myLatLng1,carMarker1;
    var watchProcess=null,previouslat,previouslng,timer;
    
    // Wait for Cordova to load
    document.addEventListener("deviceready", onDeviceReady, false);

    function onDeviceReady()
    {
        navigator.geolocation.getCurrentPosition(onSuccess, onError,{enableHighAccuracy: true });
    }

function GetCurrentPosition()
{
       watchProcess=navigator.geolocation.getCurrentPosition(onSuccess, onError,{enableHighAccuracy: true });
}

    function stop_watchlocation()
    {
        if (watchProcess != null)
        {
            navigator.geolocation.clearWatch(watchProcess);
            watchProcess = null;
            clearIntrval(timer);
        }
    }

    // onSuccess Geolocation
    function onSuccess(position)
    {
     if(cycle==0)
     {
     lat=position.coords.latitude;
         lng=position.coords.longitude;
        
         //alert('lat is '+lat+' lng is '+lng);
        
         previouslat=lat;
         previouslng=lng;
        
     loadScript();
     cycle=1;
     if(!timer)
     {
     timer=setInterval(GetCurrentPosition, 8000);
     }
     }
     else
     {
     finallat=position.coords.latitude;
         finallng=position.coords.longitude;
        
         alert('finallat is '+finallat+' final lng is '+finallng);
        
         /*carPlanCoordinates = [
     new google.maps.LatLng(31.326323, 75.599897),
     new google.maps.LatLng(31.326382, 75.599956)
     new google.maps.LatLng(31.326599, 75.600031),
     new google.maps.LatLng(31.326758, 153.602892)
   ];*/
  
   carPlanCoordinates.push(new google.maps.LatLng(finallat,finallng));
         previouslat=finallat;
         previouslng=finallng;
     currentLoc();
     }
    }

    // onError Callback receives a PositionError object
    //
    function onError(error) {
        alert('code: '    + error.code    + '\n' +
              'message: ' + error.message + '\n');
    }
    
    
    
    
      /*Google API Functions*/
      function initialize()
      {
    
   myOptions = {zoom: 16,center: new google.maps.LatLng(lat,lng),mapTypeId: google.maps.MapTypeId.ROADMAP}

   map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

   /*For the car marker initial icon*/
   image = 'car.gif';
   myLatLng = new google.maps.LatLng(lat, lng);
   carMarker = new google.maps.Marker({position: myLatLng,map: map,icon: image});
  
   carMarker.setMap(map);
  
 }

function currentLoc()
{

/*For the GPS Trakcer Polylines*/
  


   carPath = new google.maps.Polyline({
     path: carPlanCoordinates,
     strokeColor: "#FF0000",
     strokeOpacity: 1.0,
     strokeWeight: 2
   });

   carPath.setMap(map);
  
      
   /*For the car marker final icon*/
   image1 = 'car.gif';
   myLatLng1 = new google.maps.LatLng(finallat, finallng);
   carMarker1 = new google.maps.Marker({position: myLatLng1,map: map,icon: image1});
   carMarker1.setMap(map);
   map.setCenter(myLatLng1);
}

function placeMarker(location)
{
/*For the car marker final icon*/
   image1 = 'car.gif';
   myLatLng1 = new google.maps.LatLng(location.lat(), location.lng());
   carMarker1 = new google.maps.Marker({position: myLatLng1,map: map,icon: image1});
   carMarker1.setMap(map);
}

function loadScript()
{
if(cycle==0)
{
   var script = document.createElement("script");
   script.type = "text/javascript";
   script.src = "http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=true&callback=initialize";
   document.body.appendChild(script);
}
}

//window.onload = loadScript;
/*End Of Google API Functions*/
    </script>
  </head>
  <body>
    <div id="map_canvas" style="width:100%; height:100%"></div>
  </body>
</html>

Sunday, 6 May 2012

Send SMS Using Android Phonegap

Hi Folks!,

Hope you have enjoyed the previous posts and got the working knowledge of the android. Today we are going to do some different stuff using the PhoneGap Open Source Through which we can do lot many things on cross platform mobile phones. Please read the help file with phonegap and then read the following code. The code here would send the sms using the phonegap plugin.

Step 1. Install Phonegap from http://phonegap.com/.

Step 2. Install The plugins for phonegap available on github.

Step 3. Look for SmsPlugin folder and copy the smsplugin.java into your "src" folder in eclipse.

Step 4. Add the following code in your html file.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=320; user-scalable=no" />
<title>Send SMS</title>
   
    <link href="css/style.css" rel="stylesheet" type="text/css" />

    <script src="jquery-1.6.min.js" type="text/javascript" />

    <script src="cordova-1.6.1.js" type="text/javascript" />

    <script src="jquery.mobile-1.0b3.min.js" type="text/javascript" />

    <script src="smsplugin.js" type="text/javascript" />

<script type="text/javascript">             
        function onDeviceReady () {
            $('#send').bind('click', function () {
               
                window.plugins.sms.send($('#phone').val(), $("#txtMessage").val(),
                    function () {
                       alert('Your Message has been sent successfully.');   
                       $("#txtMessage").val("");
                    },
                    function (e) {
                        alert('Sorry There Was An Error :' + e);
                    }
               
                );
              
            });                           
        }
</head>
<body>
        <dl>
            <dt style="width: 80px; margin-left: 18px">Message</dt>
            <dd>
                <textarea rows="3" cols="23" id="txtMessage" name="txtMessage"></textarea></dd>
        </dl>
        </div>
        <div class="info" style="text-align: center">
            <img id="send" src="images\button.jpg" />
        </div>
</body>

Step 5: Modify plugins.xml and add the following line

<plugin name="SmsPlugin" value="ritesh.tandon.sendsms.SmsPlugin" />

here instead of ritesh.tandon.sendsms write your package name and class name.

Thats it folks! , you are ready for the show.

Thnx
Ritessh

 

Wednesday, 18 April 2012

How To Get Complex Data In Android Using ASP.NET WebService

Hi Folks!,

Today i am posting the code that would get the data from the asp.net webservice. The webservice returns the data as DataSet and passes to android device. The code here explains how to deal with the complex data types like dataset from asp.net webservice into andoroid device. Here is the code

public SoapObject soap(String METHOD_NAME, String SOAP_ACTION,
String NAMESPACE, String URL, String IP, String SERVICEPATH)
throws IOException, XmlPullParserException
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); // set up



SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); // put all required data into a soap
envelope.dotNet = true;
envelope.setOutputSoapObject(request); // prepare request
envelope.bodyOut = request;

HttpsTransportSE aht = new KeepAliveHttpsTransportSE(IP, 443,SERVICEPATH, 5000);
aht.debug = true;
//aht.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
aht.call(SOAP_ACTION, envelope);
SoapObject result = (SoapObject) envelope.bodyIn; // get response

SoapObject responseBodyRaw,responseBody,table,tableRow;
responseBodyRaw = (SoapObject)envelope.getResponse();
responseBody = (SoapObject)envelope.getResponse();
// Now, the reponse works as a Vector. On position 0 we have the information of the Reponse while in position 1 we get the info we requested. So we get rid of the information reponse and lets grab the info we requested
responseBody = (SoapObject)responseBody.getProperty(1);
// And now, we have the n tables returned by the asp.net webservice.
table = (SoapObject) responseBody.getProperty(0);

// We can get the row of the table by using the getProperty(rownumber)
tableRow = (SoapObject) table.getProperty(0);

return table;
}

The above method can be called by using this code
SoapObject table=null;

table = soap("Webmethodname","http://tempuri.org/Webmethodname","http://tempuri.org/","http://www.mywebsite.com/service.asmx","www.mywebsite.com", "service.asmx");
//data=table.toString();
titles=new String[table.getPropertyCount()];

for(int i=0;i<table.getPropertyCount();i++)
{
tableRowData = (SoapObject) table.getProperty(i);
                       }

The above code calls the "soap" method and you can get the tableRow Data by using the above code. Hope you guys have understood the concept.

Thnx
ritessh


Monday, 13 February 2012

Connecting Android App With Secure Socket Layer SSL

Hi Folks!,

Today i am going to give you a complete code for consuming web service data on SSL. The webservice was configured on my IIS, Instead of "localhost" android emulator uses "10.0.2.2". Here is the code


package ritesh.tandon.mywebservice;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import org.ksoap2.serialization.*;
import org.ksoap2.*;
import org.ksoap2.transport.*;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class SsltestActivity extends Activity {

private static final String NAMESPACE = "http://tempuri.org/";
private static final String SOAP_ACTION = "http://tempuri.org/ReturnData";
private static final String METHOD_NAME = "ReturnData";
private static final String URL = "https://10.0.2.2/AndroidService/service1.asmx";

TextView tv;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv=(TextView)findViewById(R.id.TextView01);

allowAllSSL();

SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
Request.addProperty("regno", "Tandon");

SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(Request);

//HttpTransportSE aht=new HttpTransportSE(URL);
HttpsTransportSE aht=null;

try
{
aht = new KeepAliveHttpsTransportSE("10.0.2.2", 443, "/AndroidService/service1.asmx", 5000);
aht.debug=true;
aht.call(SOAP_ACTION, soapEnvelope);
SoapPrimitive resultString=(SoapPrimitive)soapEnvelope.getResponse();
tv.setText(" Data is "+resultString);
}
catch (Exception e)
{
System.out.println(aht.requestDump );
tv.setText(e.toString());
}

}


/*-----Below code is for trust connection with ssl-------*/
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    private static void trustAllHosts()
    {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager()
        {
            public java.security.cert.X509Certificate[] getAcceptedIssuers()
            {
                return new java.security.cert.X509Certificate[]{};
            }

            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }
        }};

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static TrustManager[] trustManagers;

    public static class _FakeX509TrustManager implements
            javax.net.ssl.X509TrustManager {
        private static final X509Certificate[] _AcceptedIssuers =
                new X509Certificate[]{};

        public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }

        public boolean isClientTrusted(X509Certificate[] chain) {
            return (true);
        }

        public boolean isServerTrusted(X509Certificate[] chain) {
            return (true);
        }

        public X509Certificate[] getAcceptedIssuers() {
            return (_AcceptedIssuers);
        }
    }

    public static void allowAllSSL() {

        javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new
                HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession
                            session) {
                        return true;
                    }
                });

        javax.net.ssl.SSLContext context = null;

        if (trustManagers == null) {
            trustManagers = new javax.net.ssl.TrustManager[]{new
                    _FakeX509TrustManager()};
        }

        try {
            context = javax.net.ssl.SSLContext.getInstance("TLS");
            context.init(null, trustManagers, new SecureRandom());
        } catch (NoSuchAlgorithmException e) {

        } catch (KeyManagementException e) {

        }

        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    }
/*---------------End code for ssl trust connection--------*/
}

How to implement Captcha v3 in ASP.NET

 I was facing an issue of dom parsing in my website. I finally resolved it by using Google Captcha V3. Step 1: Get your keys from https:...