Gcm Push Notification with ASP.NET

FCM (Firebase Cloud Messaging) Push Notification with Asp.Net

C# Server Side Code For Firebase Cloud Messaging

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;

namespace Sch_WCFApplication
{
public class PushNotification
{
public PushNotification(Plobj obj)
{
try
{
var applicationID = "AIza---------4GcVJj4dI";

var senderId = "57-------55";

string deviceId = "euxqdp------ioIdL87abVL";

WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");

tRequest.Method = "post";

tRequest.ContentType = "application/json";

var data = new

{

to = deviceId,

notification = new

{

body = obj.Message,

title = obj.TagMsg,

icon = "myicon"

}
};

var serializer = new JavaScriptSerializer();

var json = serializer.Serialize(data);

Byte[] byteArray = Encoding.UTF8.GetBytes(json);

tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));

tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));

tRequest.ContentLength = byteArray.Length;

using (Stream dataStream = tRequest.GetRequestStream())
{

dataStream.Write(byteArray, 0, byteArray.Length);

using (WebResponse tResponse = tRequest.GetResponse())
{

using (Stream dataStreamResponse = tResponse.GetResponseStream())
{

using (StreamReader tReader = new StreamReader(dataStreamResponse))
{

String sResponseFromServer = tReader.ReadToEnd();

string str = sResponseFromServer;

}
}
}
}
}

catch (Exception ex)
{

string str = ex.Message;

}

}

}
}

APIKey and senderId , You get is here---------as follow(Below Images)
(go to your firebase App)

Step. 1

Step. 2

Step. 3

How to send push notification to more then 1000 user through GCM

Well probably you get exception because you are not setting content type. I found article how to send data and rewrote it to your needs. You also would need to install Json.Net package

public class NotificationManager
{
private readonly string AppId;
private readonly string SenderId;

public NotificationManager(string appId, string senderId)
{
AppId = appId;
SenderId = senderId;
//
// TODO: Add constructor logic here
//
}

public void SendNotification(List<string> deviceRegIds, string tickerText, string contentTitle, string message)
{
var skip = 0;
const int batchSize = 1000;
while (skip < deviceRegIds.Count)
{
try
{
var regIds = deviceRegIds.Skip(skip).Take(batchSize);

skip += batchSize;

WebRequest wRequest;
wRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
wRequest.Method = "POST";
wRequest.ContentType = " application/json;charset=UTF-8";
wRequest.Headers.Add(string.Format("Authorization: key={0}", AppId));
wRequest.Headers.Add(string.Format("Sender: id={0}", SenderId));

var postData = JsonConvert.SerializeObject(new
{
collapse_key = "score_update",
time_to_live = 108,
delay_while_idle = true,
data = new
{
tickerText,
contentTitle,
message
},
registration_ids = regIds
});

var bytes = Encoding.UTF8.GetBytes(postData);
wRequest.ContentLength = bytes.Length;

var stream = wRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();

var wResponse = wRequest.GetResponse();

stream = wResponse.GetResponseStream();

var reader = new StreamReader(stream);

var response = reader.ReadToEnd();

var httpResponse = (HttpWebResponse) wResponse;
var status = httpResponse.StatusCode.ToString();

reader.Close();
stream.Close();
wResponse.Close();

//TODO check status
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

Then you can call method

 var notificationManager = new NotificationManager("AppId", "SenderId");
notificationManager.SendNotification(Enumerable.Repeat("test", 1010).ToList(), "tickerText", "contentTitle", "message");

Android push notifications using GCM with ASP.NET only received by one device

Basically what you'll want to do is open a data connection to your web server and send your gcmid to it with some other identifying factor of the phone (such as a userid or the phone id) you'll want to do this in your OnRegistered Method of the GCMIntentService class. I send a Form Post request to the webserver. On the webserver you will probably want to store the information in a database.
I use a multidimensional array for my form variables

public String formPost(String[][] Vars) {

String url = "put url of web server here";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
String tmp = null;
String rturn = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
for (int i = 0; i < Vars.length; i++) {
nameValuePairs.add(new BasicNameValuePair(Vars[i][0], Vars[i][1]));
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String ttmp = parseISToString(response.getEntity().getContent());
Log.i("test", ttmp);
if (ttmp.contains("Success")) {
rturn = ttmp;
Log.i("test", "Success:" + ttmp);
} else {
rturn = ttmp;
Log.i("test", "Fail:" + ttmp);
}

} catch (ClientProtocolException e) {

} catch (IOException e) {
} /*
* catch (RuntimeException e){ Context context =
* getApplicationContext(); CharSequence text =
* "There was an error try again later."; int duration =
* Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text,
* duration);toast.show(); Log.i("test",e.getMessage()); finish(); }
*/
return rturn;

}

GCM push notification Server side for asp.net

That's a mistake in android side. Finally solved.

Push notification from PC to android without Google cloud messaging(GCM)

After some search i found this solution --> http://www.rabbitmq.com/

I didn't test my self, but you cand find a tutorial here http://simonwdixon.wordpress.com/2011/06/03/getting-started-with-rabbitmq-on-android-part-1/

Just say that GCM is prepared to have some consideration with device battery. It is possible that these workarounds for push notifications don't be so nice with devices



Related Topics



Leave a reply



Submit