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