Source: Intelliwins Blog

Intelliwins Blog Send GCM notification from asp.net C# server

Google Cloud Messaging Alert From Asp.net C#Sending alerts via a Google Cloud Messaging service is one of the simplest and trickiest things to do in asp.net. We have tried very simple methods in asp.net to successfully send notifications from server. You need to know how GCM works. First of all you need to register with Google Cloud Messaging Service Where you need to provide the android app ID and details. Then it provides one API key and you also need the Project ID. You need both of these parameters while sending notifications.One more thing is require that is device id. When the GCM registered app is installed in the android device during registration process a device key and device id is created. We need both of these things while sending notification so that we can direct GCM to send notification for a particular device. We need to save this device ID in a database with our server. We need a web service by using which app developer can send device key and id.To send use the following c# method public string SendNotification(string deviceId, string message) { string SERVER_API_KEY = "YOUR GCM API Key"; var SENDER_ID = "YOUR Project ID"; var value = message; WebRequest tRequest; tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send"); tRequest.Method = "post"; tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8"; tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY)); tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID)); string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + deviceId + ""; Console.WriteLine(postData); 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(); return sResponseFromServer; }Any Question Comment Below .Happy Coding !!!

Read full article »
Est. Annual Revenue
$100K-5.0M
Est. Employees
1-25
CEO Avatar

CEO

Update CEO

CEO Approval Rating

- -/100