I am trying to use FCM for pushing notifications to Android device from C# server.I am using below mentioned code for sending notifications and it worked perfectly fine but I need to send data payload as well but I don't know how to implement that.
public static void SendPushNotification(String user_id,string not_title)
{
try
{
string applicationID = "AAAAjpeM.......";
string senderId = ".......";
string deviceId = user_id;
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 = not_title,
title = "ABC",
sound = "Enabled"
}
};
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;
}
}
I have tried this but it did'nt works.
var data = new
{
to = deviceId,
data = new
{
body = not_title,
title = "Avicenna",
payload="1",
sound = "Enabled"
}
};
try this:
var data = new
{
to = deviceId,
notification = new
{
body = not_title,
title = "ABC",
sound = "Enabled"
},
data = new
{
payload="1"
}
};
Related
I am trying to send FCM push alarm to an Android app using HTTP request in C#. I've seen some examples and wrote them as a reference, but I ran into problems where I didn't expect them.
I got a data stream returned through an HTTP request, and I wrote data to it with the Write() method, but an exception occurred.
Here is my code.
public void PushNotification()
{
const string FCM_URL = "https://fcm.googleapis.com/v1/projects/xxx/messages:send HTTP/1.1";
const string SERVER_KEY = "xxxxxx";
const string SENDER_ID = "xxxxx";
string postbody;
Byte[] byteArr;
object payload;
WebRequest wReq;
wReq = WebRequest.Create(FCM_URL);
wReq.Method = "post";
wReq.Headers.Add(string.Format("Autorization:key={0}", SERVER_KEY));
wReq.Headers.Add(string.Format("Sender:id={0}", SENDER_ID));
wReq.ContentType = "application/json";
payload = new
{
to = "/topics/all",
priority = "high",
content_available = true,
notification = new
{
body = "Test",
title = "Test",
badge = 1
},
data = new
{
key1 = "val1",
key2 = "val2"
}
};
postbody = JsonConvert.SerializeObject(payload).ToString();
byteArr = Encoding.UTF8.GetBytes(postbody);
wReq.ContentLength = byteArr.Length;
using (Stream dStream = wReq.GetRequestStream())
{
dStream.Write(byteArr, 0, byteArr.Length);
using (WebResponse wResp = wReq.GetResponse()) //Exception: You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
{
using (Stream dStreamResp = wResp.GetResponseStream())
{
if (dStreamResp != null) using (StreamReader wReader = new StreamReader(dStreamResp))
{
string sRespFromServer = wReader.ReadToEnd();
}
}
}
}
}
How I solve it???
I think I made a mistake because I am not familiar with C#. Since the 'using' keyword was used, the stream was not closed after writing. So I modified the code to:
public void PushData(string messageTitle, string messageText)
{
string postbody;
object payload;
Byte[] byteArr;
WebRequest wReq;
WebResponse wResp;
Stream dataStream, dataRespStream;
wReq = WebRequest.Create(FCM_ENDPOINT);
wReq.Method = "POST";
wReq.Headers.Add(string.Format("Authorization: key={0}", serverApiKey));
wReq.Headers.Add(string.Format("Sender: id={0}", senderID));
wReq.ContentType = "application/json";
payload = new
{
to = "/topics/" + _receiverGrpID,
priority = "high",
content_available = true,
data = new
{
title = messageTitle,
body = messageText
}
};
postbody = JsonConvert.SerializeObject(payload).ToString();
byteArr = Encoding.UTF8.GetBytes(postbody);
wReq.ContentLength = byteArr.Length;
dataStream = wReq.GetRequestStream();
dataStream.Write(byteArr, 0, byteArr.Length);
dataStream.Close();
wResp = wReq.GetResponse();
dataRespStream = wResp.GetResponseStream();
if(dataRespStream != null)
{
StreamReader streamReader = new StreamReader(dataRespStream);
_respFromFCMServer = streamReader.ReadToEnd();
}
dataRespStream.Close();
}
Even I was wrong with the request URL. It is natural that this doesn't work.
After solving these, this works!
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 }
};
I am using FCM Notifications in my android app.
the notification has to be sent to sent to a limited number of users (around 200 users) at the same time using .net pages
public static void SendPushNotification()
{
try
{
string applicationID = "ABC****xyz";
string senderId = "01*****89";
string deviceId1 = "def****jdk";
string deviceId2 = "lej****wka";
string deviceId3 = "fqx****pls";
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var data = new
{
//This line is the problem
to = deviceId1+","+deviceId2+","+deviceId3,
notification = new
{
body = "Notification Body",
title = "Notification Title",
sound = "Enabled",
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;
}
}
The to line is problem is where I concatenate multiple devices
How can I just send the notifications for these devices?
Thanks
For sending push notification to multiple devices, you have to use 'registration_ids' instead of 'to' parameter that contains array of device tokens. The limitation is that you can provide a maximum of 1000 device tokens by this method. Check this out for reference FCM Downstream Messages
I am using FCM in my Android and iOS app. The client side code is working correctly because from the Firebase console I can send notifications to both platforms with out any problem. With my C# code I can send notifications successfully to android devices but the notifications never appear on iPhone unless directly coming from the Firebase notification console. I don't know what gives.
C# server-side code
try
{
var applicationID = "application_id";
var senderId = "sender_id";
string deviceId = "device_id_of_reciever";
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",
title = "This is the title",
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();
Response.Write(sResponseFromServer);
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
Notifications are not working on iPhone with my server side code but I get a good response from Firebase.
{
"multicast_id": 479608 XXXXXX529964,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [{
"message_id": "0:1467935842135743%a13567c6a13567c6"
}]
}
Any help or suggestions would be really appreciated.
Try setting the priority field to High in your FCM request.
Eg:
var data = new
{
to = deviceId,
notification = new
{
body = "This is the message",
title = "This is the title",
icon = "myicon"
},
priority = "high"
};
Note though that using high priority in development is fine but in production it should only be used when the user is expected to take action, like reply to a chat message.
I am using FCM in android and IOS push notification.I am using Visual Studio 2015.To be create a web api project and a to add a controller.write the code.Code is given below
using System;
using System.Net;
using System.Web.Http;
using System.Web.Script.Serialization;
using System.Configuration;
using System.IO;
namespace pushios.Controllers
{
public class HomeController : ApiController
{
[HttpGet]
[Route("sendmessage")]
public IHttpActionResult SendMessage()
{
var data = new {
to = "device Tokens", // iphone 6s test token
data = new
{
body = "test",
title = "test",
pushtype="events",
},
notification = new {
body = "test",
content_available = true,
priority= "high",
title = "C#"
}
} ;
SendNotification(data);
return Ok();
}
public void SendNotification(object data)
{
var Serializer = new JavaScriptSerializer();
var json = Serializer.Serialize(data);
Byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(json);
SendNotification(byteArray);
}
public void SendNotification(Byte[] byteArray)
{
try
{
String server_api_key = ConfigurationManager.AppSettings["SERVER_API_KEY"];
String senderid = ConfigurationManager.AppSettings["SENDER_ID"];
WebRequest type = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
type.Method = "post";
type.ContentType = "application/json";
type.Headers.Add($"Authorization: key={server_api_key}");
type.Headers.Add($"Sender: id={senderid}");
type.ContentLength = byteArray.Length;
Stream datastream = type.GetRequestStream();
datastream.Write(byteArray, 0, byteArray.Length);
datastream.Close();
WebResponse respones = type.GetResponse();
datastream = respones.GetResponseStream();
StreamReader reader = new StreamReader(datastream);
String sresponessrever = reader.ReadToEnd();
reader.Close();
datastream.Close();
respones.Close();
}
catch (Exception)
{
throw;
}
}
}
}
In the case of android json is given below
var data = new {
to = "device Tokens", // iphone 6s test token
data = new
{
body = "test",
title = "test",
pushtype="events",
};
In the case of IOS json
var data = new {
to = "device Tokens", // iphone 6s test token
data = new
{
body = "test",
title = "test",
pushtype="events",
},
notification = new {
body = "test",
content_available = true,
priority= "high",
title = "C#"
}
} ;
SERVER_API_KEY,SENDER_ID I am adding the web config.To be collect SERVER_API_KEY,SENDER_ID in FCM.
<add key="SERVER_API_KEY" value="ADD Key in FCM"/>
<add key="SENDER_ID" value="Add key in fcm "/>