Thursday, December 19, 2013

Android Push Notification Using ASP.NET - Example

Hi,

This is a function used to send the Push Notifications to the Android Device.

Below is a class for pushNotifications
It has a function called SendCommandToPhone(String DeviceID,String sCommand)

DeviceId : the Registered Device Id (Unique key generated by the google play services.This id is stored in our device at the time of registration)
 sCommand : the message we send to android device.

 public class PushNotification
    {
        public PushNotification()
        {

        }

        public void SendCommandToPhone(String DeviceID,String sCommand)
        {
            String GoogleAppID = "---- API Key ---------------------------";
            var SENDER_ID = "---ProjectId------";
            WebRequest tRequest;
            tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
            tRequest.Method = "post";
            tRequest.ContentType = "application/x-www-form-urlencoded";
            tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
            tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
            String collaspeKey = Guid.NewGuid().ToString("n");
            String postData = string.Format("registration_id={0}&data.message={1}&collapse_key={2}", DeviceID, sCommand, collaspeKey);
            Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            tRequest.ContentLength = byteArray.Length;
            Stream dataStream = tRequest.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            WebResponse tResponse = tRequest.GetResponse();
            dataStream = tResponse.GetResponseStream();
            StreamReader tReader = new StreamReader(dataStream);
            String sResponseFromServer = tReader.ReadToEnd();
            tReader.Close();
            dataStream.Close();
            tResponse.Close();
        }
    }





Finally we send the Message to device from our website as follows

 txtMessage.Value is the textbox where we type the message
the below function is written in a button click.


PushNotification apnGCM = new PushNotification();
                try
                {
                    string connectionString = "Data Source=yourServerIP;Initial Catalog=DatabaseName;Uid=userId;Pwd=password;Timeout=60;";
                    using (SqlConnection connection = new SqlConnection(connectionString))
                    {
                        using (SqlCommand command = new SqlCommand(
                                "SELECT * FROM dbo.PushNotification", connection))
                        {
                            connection.Open();
                            SqlDataAdapter da = new SqlDataAdapter();
                            da.SelectCommand = command;
                            DataTable dt = new DataTable();
                            da.Fill(dt);

                            foreach (DataRowView drv in dt.DefaultView)
                            {
                                apnGCM.SendCommandToPhone(drv["RegId"].ToString(), txtMessage.Value);
                            }
                        }
                    }
                }
                catch
                {
                    throw;
                }





This is the Register page .cs file

the Register is called as a post Method from android with the AppName and RegId
You only need RegId to identify the device(I added the AppName to identify the application[to manage multiple apps on same table])

 public partial class Register : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                NameValueCollection nvc = Request.Form;
                string AppName="", RegId="";
                if (!string.IsNullOrEmpty(nvc["AppName"]))
                {
                    AppName = nvc["AppName"];
                }

                if (!string.IsNullOrEmpty(nvc["RegId"]))
                {
                    RegId = nvc["RegId"];
                }
                if (!AppName.Equals("") && !RegId.Equals(""))
                {
                    BindData(AppName, RegId);
                    Response.Write("Device Registered Successfully");
                }
            }
            catch (Exception ex)
            {
                Response.Write("Error On Registering Device");
            }
        }

        private void BindData(String AppName,String RegId)
        {
            if (!AppName.Equals("") && !RegId.Equals(""))
            {
                try
                {
                    string connectionString = "Data Source=IPaddress;Initial Catalog=database;Uid=username;Pwd=password;Timeout=60;";
                    using (SqlConnection connection = new SqlConnection(connectionString))
                    {
                        using (SqlCommand command = new SqlCommand(
                                "INSERT INTO dbo.PushNotification(AppName,RegId) VALUES ('" + AppName + "','" + RegId + "')", connection))
                        {
                            connection.Open();
                            command.ExecuteNonQuery();
                        }
                    }
                }
                catch
                {
                    throw;
                }
            }
        }
    }



The Database contains a table called PushNotification(AppName,RegId)

both AppName & RegId fields are Varchar fields
 

Saturday, November 2, 2013

Datatable to JSON in ASP.NET - For Web Applications Development in Android

All web application on android uses either JSON or XML for receiving data from Android.This is a function which can be used to convert datatable to JSON object.Then it can be give as response.



        public string DataTabletoString(DataTable dtData,String RootNodeName)
        {

            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }
            return "{ \"" + RootNodeName + "\" : " + serializer.Serialize(rows) + " }";
        }

The input parameter is the dataTable andthe rootNodeName

username,password,name,address,emailid,phoneno  

are the Column names in datatable


The output will be

{ "registration" : [{"username":"user1","password":"pswd","name":"gop","address":"gop","emailid":"emp1@gmail.com","phoneno":1234567},{"username":"user2","password":"pswd","name":"emp2","address":"address2","emailid":"emp2@gmail.com","phoneno":1234567},{"username":"user3","password":"pswd","name":"emp3","address":"address3","emailid":"emp3@gmail.com","phoneno":134234}] }

 Here registration is the rootNodeName

Friday, October 25, 2013

Socket Connection in Android - Bi directional (Simple and Easy)

I have written a class for socket programming.This class can be used for creating both server and client socket.you don't have to write classes for server and client separately.

This class contains two constructors.

for Server :

SocketConnection(int Port,final Handler ReturnHandler)

Port : server port where the socket is open (default is 8080)
ReturnHandler : handler for handling the received value from client

 for Client :

SocketConnection(String ipAddress,int Port,final Handler ReturnHandler)

 ipAddress : Ipaddress of the server where the client have to connect.
ReturnHandler : handler for handling the received value from server


Functions :

ReadValues : This function is used to Read the values and do what with the received value
the Red line is where you have to change accourding to your need (I use send Empty message function and integer value). This function is called after the connection is accepted

public void ReadValues()
    {
        Thread threadRead = new Thread(new Runnable() {
           
            @Override
            public void run() {
                // TODO Auto-generated method stub
               
               
                try {
                 BufferedReader in = new BufferedReader(new InputStreamReader(m_SocClient.getInputStream()));
                String line = null;
                while ((line = in.readLine()) != null) {
                    m_ReturnHandler.sendEmptyMessage(Integer.parseInt(line));
                }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        threadRead.start();
       
    }


WriteValues : This function is used to send values to client/Server from Server/Client.I use integer as input parameter you can use any parameter


    public void WriteValues(final int Number)
    {
        Thread threadWrite = new Thread(new Runnable() {
           
            @Override
            public void run() {
                // TODO Auto-generated method stub
                if(outputValues==null)
                {
                    try {
                        outputValues = new PrintWriter(new BufferedWriter(new OutputStreamWriter(m_SocClient.getOutputStream())), true);
                       
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                outputValues.println(Number);
            }
        });
        threadWrite.start();
    }


Monday, October 21, 2013

MenuBuilder jQuery Plugin

This is my first jQuery Plugin.It allows users to build a Menu like structure using 'ul' , 'li' & 'a'.
The menu can be created from a jSON Object.

This supports unlimited number of submenus.you can use this if you have dynamic menus for each page.you can provide the jSON Object in each subpages and load the menu accordingly.

you can combine this with any jQuery Menu Plugin ( I use jQueryUI ).

to get a Menu structure like this

  • Menu A
    • Menu Aa
  • Menu B
    • Menu Ba
    • Menu Bb
      • Menu Bb1
        • Menu Bb11
        • Menu Bb12
      • Menu Bb2
  • Menu C
    • Menu Ca
    • Menu Cb

 the jSON object have to be like below


var jSONObj = {
            "menu": [
                {
                    "name": "Menu A",
                    "url": "~/Demo/page1",
                    "menu": [
                        {
                            "name": "Menu Aa",
                            "url": "~/Demo/page2",
                        }]
                },
                {
                    "name": "Menu B",
                    "url": "",
                    "menu": [
                        {
                            "name": "Menu Ba",
                            "url": "~/Demo/page3",
                        },
                        {
                            "name": "Menu Bb",
                            "url": "~/Demo/page4",
                            "menu": [
                                        {
                                            "name": "Menu Bb1",
                                            "url": "~/Demo/page5",
                                            "menu": [
                                                        {
                                                            "name": "Menu Bb11",
                                                            "url": "~/Demo/page6",
                                                        },
                                                        {
                                                            "name": "Menu Bb12",
                                                            "url": "~/Demo/page7",

                                                        }
                                                            ]
                                        },
                                        {
                                            "name": "Menu Bb2",
                                            "url": "~/Demo/page6",
                                            
                                        }
                                    ]
                        }
                    ]
                },
                {
                    "name": "Menu C",
                    "url": "~/Demo/page9",
                    "menu": [
                                        {
                                            "name": "Menu Ca",
                                            "url": "~/Demo/page10",
                                        },
                                        {
                                            "name": "Menu Cb",
                                            "url": "~/Demo/page11",
                                        }
                    ]
                }
            ]
        }; 


Then simply call the plugin function in the document.ready function


        $(document).ready(function () {
            $('#dvmenu').MenuBuilder(jSONObj);

        });


where  'dvmenu' is the id of the div where the menu is generated


jQuery Plugin : 


(function ($) {

    $.fn.MenuBuilder = function (jSONObject) {
        this.append(populateSubMenuItems(jSONObject));
        return this;
    };

    function populateSubMenuItems(jsonObject) {
        var items = jsonObject.menu;
        var ul = $('<ul/>');
        $.each(items, function (n, elem) {
            if (elem.menu == null) {
                $(ul).append("<li><a href='"+elem.url+"' >" + elem.name + "</a></li>");
            } else {
                var subul = populateSubMenuItems(elem);
                var subli = $('<li/>');
                $(subli).append("<a href='" + elem.url + "' >" + elem.name + "</a>");
                $(subli).append(subul);
                $(ul).append(subli);
            }
        });
        return ul;
    }

}(jQuery));



Save the plugin as jquery.menubuilder.js 



dont forget to include the jQuery file in the page :)

works with almost all versions of jQuery.

the example is shown with jQueryUI Menu

sample : http://jsfiddle.net/urEka/6/





Tuesday, October 8, 2013

Mobile Developer summit 2013 #mods

Going to attend the Mobile Developer summit 2013 @ NIMHANS Convention Centre, Banglore on 10-11th of this Month.

http://www.developermarch.com/mds/

I was interested in the old presentations of the summits.but to download those items I have to register an account.so I found out a way to download them without an account.

 this is for educational purpose only.
















Clicked on the view more button


then the page with all the presentations appeared.

Right click on the  download presentation link and click on the Inspect Element (I am using Firefox)




double click on the item and copy the selected part shown on the screen


copy the address from address bar

http://www.developermarch.com/mds/2012/report/postPresentationFiles.html

replace the underlined part and replace with the selected text


http://www.developermarch.com/mds/2012/report/downloads/MDS2012_jQueryMobile_SDavis.pdf

and paste it in the addressbar and enjoy the presentation.






Saturday, July 27, 2013

Android -> Windows Phone 8 [Galaxy -> Lumia]

I just brought a Nokia Lumia 620 ( Lime Green :D ). As you can get the details about the phone on gsmarena,I am not going to describe it here again.


I was a hardcore android user and an android Developer.But Still I was interested in trying new things.So I choose WP8.When Comparing Hardware,both are almost same but still I got NFC,front camera,dual core processor for 13K from flipkart.
One thing I notice is that social networking is integrated into the operating system.Every main Application which is available on android is available on windows.Message and facebook chat is combined as thread.Gmail sync is good.Mails are received on the phone as they arrive on inbox.Nokia Music is good.Dedicated Camera button.No toggles to turn of bluetooth,wifi,etc.I have to go to settings to turn them on/off.Headphone is not good.I can toggle ring/vibrate from lockscreen. LockscreenNotifications are good we can choose which app to show in lockscreen.I think It is the most secure Mobile OS.

Saturday, July 13, 2013

Working With Google Map in Android

 First configure the sdk and import google play service


 install google play service from the sdk first
then import it to your workspace
add the imported library to your application
 choose any of the google APIs for your application





First extend the FragmentActivity class in your activity
public class MainActivity extends FragmentActivity


Declare these functions

     public GoogleMap mapView;
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mapView == null) {
            // Try to obtain the map from the SupportMapFragment.
            mapView = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapview)).getMap();
            // Check if we were successful in obtaining the map.
            if (mapView != null) {
                setUpMap();
            }
        }
    }

    private void setUpMap() {
        // Hide the zoom controls as the button panel will cover it.
        mapView.getUiSettings().setZoomControlsEnabled(true);
        mapView.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    }

and call the function

        setUpMapIfNeeded(); inside onCreate function





this on your layout xml
           
 <FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
      android:id="@+id/mapview"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      class="com.google.android.gms.maps.SupportMapFragment"/>
    </FrameLayout>


this on your manifest file



<permission
    android:name="com.vivek.gpstrack.permission.MAPS_RECEIVE"
    android:protectionLevel="signature"/>
  <uses-permission android:name="com.vivek.gpstrack.permission.MAPS_RECEIVE"/>

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
  <!-- External storage for caching. -->
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  <!-- My Location -->
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  <!-- Maps API needs OpenGL ES 2.0. -->
  <uses-feature
    android:glEsVersion="0x00020000"
    android:required="true"/>



    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <uses-library android:name="com.google.android.maps" />
    <meta-data
      android:name="com.google.android.maps.v2.API_KEY"
      android:value="use your key here"/>

        <activity
            android:name="com.vivek.gpstrack.MainActivity"
            android:label="@string/title_activity_main"
            android:theme="@android:style/Theme.NoTitleBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>