GCM Using JSON to send to multiple RegistrationIDs : No notification arrives - c#

I'm using Android Google Cloud Messaging to send notifications to a device, with c#.net. I got the API Key, RegistrationID and senderID ( Well first method worked no there's nothing wrong with the configuration of GCM).
Here's the first method where I want to send the message to just 1 registrationID(check postData, i'm not using Json):
public void SendPushNotification(string regID, string message)
{
{
string GoogleAppID = "APIKey";
var SENDER_ID = "SenderID";
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}", GoogleAppID));
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=" + regID + "";
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();
HttpWebResponse httpResponse = (HttpWebResponse)tResponse;
string statusCode = httpResponse.StatusCode.ToString();
tReader.Close();
dataStream.Close();
tResponse.Close();
}
catch {
throw new WebFaultException<string>("Error", HttpStatusCode.ServiceUnavailable);
}
So when calling it, the device successfully receives the message.
Here's my second method, where I use Json format to send to multiple IDs:
(Note that the procedure doesn't take registrationID as a parameter because I added it to the list i declared in the code)
public void SendPushNotification(string message)
{
string stringregIds = null;
List<string> regIDs = new List<string>();
//Here I add the registrationID that I used in Method #1 to regIDs
//Then I use
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 = "APIKey";
var SENDER_ID = "SenderID";
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}", 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();
HttpWebResponse httpResponse = (HttpWebResponse)tResponse;
string statusCode = httpResponse.StatusCode.ToString();
tReader.Close();
dataStream.Close();
tResponse.Close();
}
catch {
throw new WebFaultException<string>("Error", HttpStatusCode.ServiceUnavailable);
}
The Method doesn't give any errors or anything but the notification doesn't arrive in the device. (I console.writelined postData and it's the same format of http://developer.android.com/google/gcm/http.html
So I don't really know what to fix, it would be really easier to send notifications to users at the same time not just send 1 to each User every X seconds.
Thanks.

Changing
Request.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
to
Request.ContentType = "application/json";
Does answer the question.
He is providing JSON data where he has explicitly implied quite the opposite.
The HTTP header must contain the following headers:
Content-Type: application/json for JSON;
application/x-www-form-urlencoded;charset=UTF-8 for plain text.
See: https://developer.android.com/google/gcm/http.html

Use
Request.ContentType = "application/json";

Replace this line:
Request.ContentType = "application/json";

Related

Push Notification using FCM in-between web and App

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;
}

Firebase integration with C#

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() +
"&registration_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

How to implement FCM in ASP.Net C#?

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() + "&registration_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);
}
}

GCM giving error: (401) Unauthorized

I am trying to write the web api in c# to send push notification in android device. which is giving me the 401 unauthorized error. i have follow all the step to send the notification. i am not able to understand why i am not authorize user.
here is my function to send notification.
public String Post(string message, string regId)
{
try
{
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
tRequest.Headers.Add(string.Format("Authorization: key=**server-api-key**"));
tRequest.Headers.Add(string.Format("Sender: id=**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() + "&registration_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();
tReader.Close();
dataStream.Close();
tResponse.Close();
return sResponseFromServer;
}
catch (Exception e)
{
throw;
}
}
Get the api key from
server key 1
and sender id from
Project number
My post function accept the message and regId which is device id.
I don't know C# and may be missing something. It looks like your post data is not in JSON format. I don't see any braces. This SO question has examples of how to post JSON-formated data.
Also, try validating your API key using curl as explained in this example.

get a userID of a facebook user with http request C# WPF

I'm trying to get the userID of a Facebook user, I already have the access_token and I use http request to do it. My simple problem is that : I want the user's id but my program just crash... I use WPF, C# Here is my little call :
var url = string.Format("https://graph.facebook.com/me?access_token=" + token + "&response_type=id");
var req = WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string postData = "'access_token='" + token;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
var stream = req.GetRequestStream();
stream.Write(byteArray, 0, byteArray.Length);
stream.Close();
WebResponse response = req.GetResponse();
aTextBox.Text = ((HttpWebResponse)response).StatusDescription;
stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
Thanks!
Don't use Web Browser for this! You may use HttpWebRequest for that kind of things:
string url = "https://graph.facebook.com/me?access_token=" + token + "&response_type=id";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
Stream receiveStream = response.GetResponseStream ();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
string responseData = readStream.ReadToEnd();

Categories