Amazon Ad

Friday, 31 May 2013

How To Detect and Run Xolo A500 As Android Emulator

Hi Guys,

I bought a new Xolo 500 but was disappointed when the phone was not detected by my laptop. I tried to find out the solution as i wanted to run my apps on phone as android emulator.

Step 1. Install Intel Android USB driver from Intel's website.

Step 2. Recognize the files of type "Setup Information". This can be seen in the windows explorer in Type column.

Step 3. In my case, I was having the following files

1. android_winusb
2. gadget_multi
3. gserial
4. intelmtp
5. rndis

1. android_winusb : Go to my computer, right click and select properties, Click on "Device Manager".
Right Click on Unknown device and get the Hardware Ids. Copy the value which is like
"USB\VID_05C6&PID_9025&MI_00". Now open android_winusb present in C:\Program Files (x86)\Intel Android Device USB Driver and edit it

in notepad. Make the below line by using the copied hardware id and paste the line in my case its

%CompositeAdbInterface%  = USB_Install, USB\VID_05C6&PID_9025&MI_00

Now right click on the Unknown Device and click on Update Driver button. Select the Android Adb Interface and browse the driver from the location and install the driver. Once you install the driver you see the updated list in Device Manager.

Do the same for the above i.e gadget_multi, gserial,intelmtp and rndis and install the rest of the drivers required for the android device once all are done, Do remember to restart your machine. Once its restarted the phone is ready to use with your machine.

Hope this help!!

Thanks
Ritesh

Wednesday, 29 May 2013

Creating Customised Confirm Box In Phonegap

Hi Guys,

I was facing a problem with JavaScript confirm box with push notification timer. There is no way to close the JavaScript confirm box programatically. I have created my own confirm box using html and JavaScript which is also easy to handle and customizable.

Here is the HTML and JavaScript code for the same.

<div id="notificationpopup" style="left:0;top:0;position:fixed;width:100%;height:100%;background-color:#000;opacity:0.6">
           <div id="popup" style="margin-top:50%;background-color:yellow">
                  <div id="header">
                     <h2>Please Confirm</h2>
                  </div>
                 <div id="popupbody">
                     <div>Do you want to accept?</div>
                     <div>
                           <input type="button" value="Yes" onclick='dialog(1)'>&nbsp;
                           <input type="button" value="No" onclick='dialog(2)'>
                    </div>   
                 </div>
           </div>
</div>
<script src="js/jquery.1.7.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
               function dialog(response)
               {
                        if(response==1)
                          alert("You Clicked Yes");
                        else
                          alert("You Clicked No");
               }
</script>

Thanks
Ritesh

Wednesday, 8 May 2013

Column increment not generating unique values in MS SQL


Hi!,

Sometimes there is a need to increment a column value for generating unique ids. People usually increment the value by one to update the column's value, But sometimes the same value is generated as the requests come at same time and query executes for the request at the same time which results in duplicate values. Here is the solution for the problem

DECLARE @IncrementId AS INT

BEGIN TRANSACTION

SELECT @IncrementId = LastId + 1 FROM table_name WITH (TABLOCKX)

Commit Transaction

END

TABLOCKX acquires exclusive lock on the table it also restricts the deadlocks on the table, There is also TABLOCK which acquires "shared" lock on the table.

Monday, 29 April 2013

Android Phonegap,The last location provider was disabled

Hi All,

I was creating a location based app on android Phonegap using the navigation code, The code was fine as mentioned in Phonegap documentation and was working on my Android phone, But when i tested the app on another android phone (HTC one) i got the error message "The last location provider was disabled".

I managed to solve the problem, Here is the step by step process

Step 1. Go to Settings > Location

Step 2. You need to apply the options

a. Google's location services.

b. GPS Satellite

Step 3. When i tried to run my app after this it was still giving me the same error, But you need to restart the phone. This is very important as the settings require the phone to be restarted. When i restarted the app started working fine and i was able to get the location.

Thanks
Ritesh

Tuesday, 19 March 2013

How To Download My Project From Heroku

Hi,

Today i was facing a problem regarding "How To Download My Project From Heroku". I got it working from the following steps

Step 1. Go to ruby command prompt and type the following command

heroku login

in my case it is

c:\RailsInstaller\Ruby1.9.3\> heroku login

and press enter it would ask for your heroku email and password that you have setup when configuring your project on heroku.

The screen would look like

Enter your Heroku credentials.
Email: <your email address>
Password (typing will be hidden): <your password>
Authentication successful.

Step 2. Next step is to clone the heroku project from git command i.e

heroku git:clone -a <your project name>

It would ask for the SSH keys, select option

2) id_rsa.pub

It should download the files. But still if you face this error i.e

"Permission denied (Public Key)"

Then follow the steps below to get it working.

Step 3.Type

heroku keys:add

It will find the heroku SSH keys. Select the option 2 in my case it is 2 for id_rsa.pub. It would display the message like

Uploading SSH public key c:/users/<windows logged username>/.ssh/id_rsa.pub.... done

Step 4. Then give the command

heroku git:clone -a <your project name>

It should start cloning the app. Once its done go into the directory to view the files by giving command

cd <your project name>

You should see the files which the clone has created.

Step 5. Now its time to install the dependent bundle's required to run the project. Give the command

bundle install

It would install all the bundles required to run the project.

Step 6: Now its the showtime. Run the following command to run the project

rails s

It would start the local server to run the project files.

Step 7: Go to your browser and type in the url

localhost:3000/<your project name>

It would execute the default page.

Enjoy!!!

Saturday, 9 February 2013

Validate ASP.NET validation controls using javascript

Hi,
Sometimes when using both asp.net controls and javascript/jquery there is a need of running both asp.net validation control and our javascript code simultaneously without postback. Below is the code for validating this. The Page_ClientValidate() function actually validates and returns true or false based on the form's validations.

<script type="text/javascript">
      var Done = 1;
      function validate() {
          if (Page_ClientValidate()) {
              if (Done == 1) {
                  return true;
              }
              else {
                  return false;
              }
          }
          else {
              return false;
          }
      }




<script>
<asp:Button id="btnSubmit" runat="server" Text="Submit" onclick='validate()'/>
  </script>

Friday, 11 January 2013

Show Image From MSSQL binary image


Hi Guys,

I was struggling how to display image from MSSQL image column. One solution i found was to create a handler and then in the "Src" attribute set the path to handler and passing the file name. But this didn't solved my problem as i have a shared hosting and the server doesn't allows me to add a handler.

This gave me an idea to search the solution and I found the following solution. This is also applicable to MSSQL varbinary(max) column. Below is the code which is easy to understand.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
           DataKeyNames="id" DataSourceID="SqlDataSource2" Width="169px">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("id") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                 <asp:TemplateField>
                    <ItemTemplate>
                        <%--<%# System.Convert.ToBase64String((byte[])Eval("Picture"))%>--%>
                        <img width="100px" height="100px" src='data:image/png;base64,<%#System.Convert.ToBase64String((byte[])Eval("Picture"))%>' />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:CheckImageConnectionString %>"
            SelectCommand="SELECT [ID], [Picture], [FullSnap] FROM [Emp]">
        </asp:SqlDataSource>
        <asp:SqlDataSource ID="SqlDataSource2" runat="server"
            ConnectionString="<%$ ConnectionStrings:lpuumsConnectionString %>"
            SelectCommand="select id,picture,fullsnap from employeepicture where id in (3,4,5)">
        </asp:SqlDataSource>

Thanks
Ritesh

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>

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:...