I am using GCM for notifications on Android with c#, but now I want to change GCM to FCM.
What do I have to change for that? Or how can I implement FCM in C#? Any help is appreciated. I am currently using this code for FCM, I just changed URL but it's not working.
try {
msg = message;
var applicationID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var SENDER_ID = "xxxxxxxxxxx";
WebRequest tRequest;
//tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/x-www-form-urlencoded";
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
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=" + message + "&data.time=" + System.DateTime.Now.ToString() + "®istration_id=" + notificationtoken + "";
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();
notification = sResponseFromServer;
tReader.Close();
dataStream.Close();
tResponse.Close();
return sResponseFromServer;
}
catch (Exception ex)
{
notification.Status = false;
notification = "ERROR DESCRIPTION : " + ex.Message;
}
Try this hope this help you..........
try
{
var applicationID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var senderId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string deviceId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
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 = "This is the message Body",
title = "This is the title of Message",
icon = "myicon"
},
priority = "high"
};
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();
Response.Write(sResponseFromServer);
Label3.Text = sResponseFromServer;
}
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
Related
I have tried to implement push Notification in-between from C#.Net(MVC) Web to React Native (Android and IPhone). No Error showing in my code but not show notification in App.
I have tried as reference gave in Stack overflow already
try
{
string server_api_key = ConfigurationManager.AppSettings["SERVER_API_KEY"];
string sender_id = ConfigurationManager.AppSettings["SENDER_ID"];
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
tRequest.Headers.Add($"Authorization: key={server_api_key}");
tRequest.Headers.Add($"Sender: id={sender_id}");
var data = new
{
to = "AAAAaQ5neZA:................................XXXX",
priority = "high",
data = new
{
message = response,
name = loginUser.EmployeeName,
userId = uId,
status = true
}
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
WebResponse tresponse = tRequest.GetResponse();
dataStream = tresponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
string sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tresponse.Close();
return sResponseFromServer;
}
catch (Exception)
{
throw;
}
i am trying to send a notification to a mobile device from firebase
i have created a project in firebase console and using the following block of code to do that
try
{
var applicationID = "AIz***********************KE";
var senderId = "52**********8";
string deviceId = "5a1e*********55";
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 = "test body",
title = "test notification",
// 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;
}
But i am Getting "The remote server returned an error: (401) Unauthorized."
Can any one please correct me where i am doing wrong
Thanks in advance
Srinivas.
How to send push notification to multiple users in firebase using C#.
I using the FCM to send notification to one user but when i try to send to multiple users i have Bad Request Exception.
Thanks in advance ..
string applicationID = NotificationConstants.GoogleNotificationData.GoogleAppID;
string senderId = NotificationConstants.GoogleNotificationData.SenderId;
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var data = new
{
to = "f3fMjgIVqog:APA91bHxfhY5zbCmHqkfG2igd499DIYVVbqvi6SUT_ZeiMa9W-abce0f9tEqIupgQHiTcoU2eZKA-dZboteeWsbOsrFWdtjjPBxzI3YJTSvPJSUiSOBicBd7xd1Hb2vtioSUNvMtz0-f",
data = dataObject
};
var json = JsonConvert.SerializeObject(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;
}
}
}
}
Your data should be like
string [] registration_ids = { deviceRegId };
var data= new
{
// to = deviceRegId, // uncomment to notify single user
registration_ids = registration_ids,
priority = "high",
notification = new { title, body }
};
string RegId = "************";
string ApplicationID = "*****";
string SENDER_ID = "***";
var value = "sandeepweb"; //message text box
WebRequest tRequest;
tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); tRequest.Method = "post";
tRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
tRequest.Headers.Add(string.Format("Authorization: key={0}", ApplicationID)); tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
//Data post to the Server
string postData =
"collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
+ value + "&data.time=" + System.DateTime.Now.ToString() +
"®istration_id=" + RegId + "";
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(); //Get response from GCM server
tReader.Close(); dataStream.Close();
tResponse.Close();
lblsuccess.Text = sResponseFromServer;
App Crashes When i send any notification. Notifications are sent from Firebase console. Do I need to make some changes in above code?
You can use FireSharp. it uses Firebase REST API behind the scenes and make your queries easy and felxible. You dont have to deal with a large messy code
Push Example:
var todo = new Todo {
name = "Execute PUSH",
priority = 2
};
PushResponse response =await _client.PushAsync("todos/push", todo);
response.Result.name //The result will contain the child name of the new data that was added
I have following code which give "Error:MissingRegistration" response from GCM server.
public void SendPushNotification()
{
string stringregIds = null;
List<string> regIDs = _db.Directories.Where(i => i.GCM != null && i.GCM != "").Select(i => i.GCM).ToList();
//Here I add the registrationID that I used in Method #1 to regIDs
stringregIds = string.Join("\",\"", regIDs);
//To Join the values (if ever there are more than 1) with quotes and commas for the Json format below
try
{
string GoogleAppID = "AIzaSyA2Wkdnp__rBokCmyloMFfENchJQb59tX8";
var SENDER_ID = "925760665756";
var value = "Hello";
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
Request.ContentType = "application/json";
tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
string postData = "{\"collapse_key\":\"score_update\",\"time_to_live\":108,\"delay_while_idle\":true,\"data\": { \"message\" : " + "\"" + value + "\",\"time\": " + "\"" + System.DateTime.Now.ToString() + "\"},\"registration_ids\":[\"" + stringregIds + "\"]}";
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();
TempData["msg1"] = "<script>alert('" + sResponseFromServer + "');</script>";
HttpWebResponse httpResponse = (HttpWebResponse)tResponse;
string statusCode = httpResponse.StatusCode.ToString();
tReader.Close();
dataStream.Close();
tResponse.Close();
}
catch (Exception ex)
{
}
}
But exact string returned by 'postData' posted by Postman or Fiddler gives positive response and notification arrived at device.
What I'm missing in my code please help me.
The postData returns this value which successfully posted by Postman And Fiddler
{"collapse_key":"score_update","time_to_live":108,"delay_while_idle":true,"data": { "message" : "Hello","time": "5/13/2016 5:50:59 PM"},"registration_ids":["cXMf6hkYIrw:APA91bGr-8y2Gy-qzNJ3zjrlf8t-4m9uDib9P0j8GW87bH5jq891-x_7P0qqItzlc_HXh11Arg76lCOcjXPrU9LAgtYLwllH2ySxA0ADSfiz3qPolajjvI3d3zE6Rh77dwRqXn3NnbAm"]}
The problem in your code is in ContentType
Instead of using this:-
Request.ContentType = "application/json";
Use
tRequest.ContentType = "application/json";
It will work
Try This:-
private string SendGCMNotification()
{
try
{
string message = "some test message";
//string tickerText = "example test GCM";
string contentTitle = "content title GCM";
string registration_id = "cXMf6hkYIrw:APA91bGr-8y2Gy-qzNJ3zjrlf8t-4m9uDib9P0j8GW87bH5jq891-x_7P0qqItzlc_HXh11Arg76lCOcjXPrU9LAgtYLwllH2ySxA0ADSfiz3qPolajjvI3d3zE6Rh77dwRqXn3NnbAm";
string postData =
"{ \"registration_ids\": [ \"" + registration_id + "\" ], " +
"\"data\": {\"contentTitle\":\"" + contentTitle + "\", " +
"\"message\": \"" + message + "\"}}";
string GoogleAppID = "AIzaSyA2Wkdnp__rBokCmyloMFfENchJQb59tX8";
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}", GoogleAppID));
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);
}
return "sent";
}