In my app, I insert the push notifications management. Now I'm testing only the Android area.
I sent the first test notifications with the FCM console. With this tool, if I send more than one notification, I see all of the in the notifications area of my phone (example: if I send 3 notifications with text "1", "2", and "3", I see all of them in the notification area).
Then, I tried to write some C# code to send these notifications from my server. I can now send the notifications from my code, but if I make the same test as above, I see only the last notification ("3") and not all of them.
I'm sure there is some parameter to be set, but I can't figure out which one is.
Do you know where have I to fix something? Below my C# code:
public string SendMessage()
{
string serverKey = "myserverkey";
try
{
var result = "-1";
var webAddr = "https://fcm.googleapis.com/fcm/send";
var regID = "myAndroidPhoneID";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Authorization:key=" + serverKey);
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"to\": \"" + regID + "\",\"data\": {\"message\": \"1This is a Firebase Cloud Messaging Topic Message!\",},\"priority\":10}";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return "err";
}
}
I also tried to add in my json the parameter collapse_key, changing its value every notification, but I see always only the last.
Solved using this json instead of the posted one:
string json = "{\"to\": \"" + regID + "\",\"notification\": {\"title\": \"New deal\",\"body\": \"20% deal!\"},\"priority\":10}";
Summarized all the steps here: https://programmingistheway.wordpress.com/2017/07/19/devextremephonegap-how-to-manage-push-notifications-with-fcm/
Related
I'm trying to post Json data to my Console. I have the code that is requesting it. I think I either have my Parameters or something else that is wrong. I know I get to the site, but then I get a 500 Server Error. I'm stuck and any help would be appreciated. I took out the URL and USER and Pass. I left the other stuff. I have no idea what I'm doing as I usually work with SQL, but I was told to try this and see if I can get it to work. We are using a Console app with the .NET framework to try and get this to work. Please help as I'm out of ideas. Something might be wrong with the headers.Accept code as well.
I've tried changing the code where my params are, I've tried even google and looking at other stack over flow methods.
public static void Main(string[] args)
{
try
{
string webAddr ="MYURL";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Accept = "application/Json";
using (var streamWriter = new
StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
USER_ID = "MyUser",
PASSWORD = "MyPass",
Query_ID = "4444",
Parameters = ""Key" ("Original"),"Value" ("1.1323")
});
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.WriteLine("Here is your Json Data.....");
Console.WriteLine(responseText);
Console.ReadLine();
//Response success above and error below
}
}
catch (WebException ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
}
}
For the Json data to show up in the Console.
I am trying to send push notification on android device with FCM in C#.Net, but I am getting "InvalidRegistration" error message.
I have used the same from Postman and R-Client as well, but still getting same error.
public String SendNotificationFromFirebaseCloud()
{
string DeviceToken = "RegToken";
string YOUR_FIREBASE_SERVER_KEY = "ServerKey";
var result = "-1";
var webAddr = "https://fcm.googleapis.com/fcm/send";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Authorization:key=" + YOUR_FIREBASE_SERVER_KEY);
httpWebRequest.Headers.Add(string.Format("Sender: id={0}", "MySenderId"));
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"to\":\"" + DeviceToken + "\",\"data\":{\"message\": \"Welcome\"}}";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
{"multicast_id":8671409506357877791,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
"invalid registration" indicates that the device token is incorrect, does not point to an existing device.
Mind that this does not mean a device that's turned off, it means that no device (currently) uses that token at all.
In other words it's an indication of a bad recipient address, effectively the equivalent of an HTTP 404 error.
I'm trying to create a .NET web application integration with RTC, where I would insert new workitems using RTC change management services, as defined in this article (specifically in "Create a Change Request"). I was able to get the URL-to-be-used inside services.xml file (/oslc/contexts/_0_iN4G09EeGGMqpyZT5XdQ/workitems/) and my goal is to insert data using JSON.
My code is basically the following:
CookieContainer cookies = new CookieContainer();
HttpWebRequest documentPost = (HttpWebRequest)WebRequest.Create(rtcServerUrl + "/oslc/contexts/_0_iN4G09EeGGMqpyZT5XdQ/workitems/order");//"Order" is the workitem name
documentPost.Method = "POST";
documentPost.CookieContainer = cookies;
documentPost.Accept = "application/json";
documentPost.ContentType = "application/x-oslc-cm-change-request+json";
documentPost.Timeout = TIMEOUT_SERVICO;
string json = "{ \"dc:title\":\"" + title + "\", \"rtc_cm:filedAgainst\": [ { \"rdf:resource\" : \"" + rtcServerUrl + "/resource/itemOid/com.ibm.team.workitem.Category/" + idCategory + "\"} ] }"; //dc:title and rtc_cm:filedAgainst are the only two mandatory data from the workitem I'm trying to create
using (var writer = new StreamWriter(documentPost.GetRequestStream()))
{
writer.Write(json);
writer.Flush();
writer.Close();
}
Encoding encode = System.Text.Encoding.UTF8;
string retorno = null;
//Login
HttpWebRequest formPost = (HttpWebRequest)WebRequest.Create(rtcServerUrl + "/j_security_check");
formPost.Method = "POST";
formPost.Timeout = TIMEOUT_REQUEST;
formPost.CookieContainer = request.CookieContainer;
formPost.Accept = "text/xml";
formPost.ContentType = "application/x-www-form-urlencoded";
String authString = "j_username=" + userName + "&j_password=" + password; //create authentication string
Byte[] outBuffer = System.Text.Encoding.UTF8.GetBytes(authString); //store in byte buffer
formPost.ContentLength = outBuffer.Length;
System.IO.Stream str = formPost.GetRequestStream();
str.Write(outBuffer, 0, outBuffer.Length); //update form
str.Close();
//FormBasedAuth Step2:submit the login form and get the response from the server
HttpWebResponse formResponse = (HttpWebResponse)formPost.GetResponse();
var rtcAuthHeader = formResponse.Headers["X-com-ibm-team-repository-web- auth-msg"];
//check if authentication has failed
if ((rtcAuthHeader != null) && rtcAuthHeader.Equals("authfailed"))
{
//authentication failed. You can write code to handle the authentication failure.
//if (DEBUG) Console.WriteLine("Authentication Failure");
}
else
{
//login successful
HttpWebResponse responseRetorno = (HttpWebResponse)request.GetResponse();
if (responseRetorno.StatusCode != HttpStatusCode.OK)
retorno = responseRetorno.StatusDescription;
else
{
StreamReader reader = new StreamReader(responseRetorno.GetResponseStream());
retorno = "[Response] " + reader.ReadToEnd();
}
responseRetorno.Close();
formResponse.GetResponseStream().Flush();
formResponse.Close();
}
As I was managed to search for in other forums, this should be enough in order to create the workitem (I have a very similar code working to update workitems using "" URL and PUT method). However, instead of create the workitem in RTC and give me some response with item's identifier, the request's response returns a huge JSON file that ends with "oslc_cm:next":"https:///oslc/contexts/_0_iN4G09EeGGMqpyZT5XdQ/workitems/%7B0%7D?oslc_cm.pageSize=50&_resultToken=_AAY50FEkEee1V4u7RUQSjA&_startIndex=50. It's a JSON representation of the XML I receive when I access /oslc/contexts/_0_iN4G09EeGGMqpyZT5XdQ/workitems/ directly from browser, like I was trying to do a simple query inside the workitem's collection (even though I'm using POST, not GET).
I also tried to use PUT method, but then I receive a 405 status code.
Does anyone have an idea of what am I missing here? My approach is wrong, even though with the same approach I'm able to update existing workitem data in RTC?
Thanks in advance.
I am having trouble with sending JSON data from my Android application written in C# using Xamarin Android (MvvmCross).
The function in Android application could run with no exception; however, my web service (written in Node JS using Express) seems not detecting the post request on its endpoint. Note that the other endpoints which use get (to send the data from web service to Android app) are working perfectly.
Below is my function to post my data to my web service
public async Task<int> insertSales(IEnumerable<Models.SalesTable> newsales)
{
/*ServerDatabaseApi.insertSalesEndpoint = "http://" + ipAddress + ":" + port +
"/insertsales";*/
WebRequest request = WebRequest.CreateHttp(ServerDatabaseApi.insertSalesEndpoint);
request.Method = "POST";
request.ContentType = "application/json";
try
{
using (var streamwriter = new StreamWriter(await request.GetRequestStreamAsync()))
{
string json = JsonConvert.SerializeObject(newsales, Formatting.Indented);
streamwriter.Write(json);
streamwriter.Flush();
}
return 1;
}
catch (WebException we)
{
return 0;
}
}
When running the function above, it is always succeed (return 1; always executes). I have also tried checking the JSON serialization and it is working perfectly fine.
Below also attached the endpoint code used to serve the data.
/*endpoint for inserting a new sales to sales table*/
app.post('/insertsales', function(appReq, appRes){
console.log("Insert sales; count : "+ appReq.body.length);
sql.connect(conn).then(function(){
console.log("Insert sales; count : "+ appReq.body.length);
for (var i = 0 ; i < appReq.body.length ; i++) {
new sql.Request()
.query("insert into SalesTable " +
"values ('"+appReq.body[i].DocumentNo+"','"+appReq.body[i].DateCreated+"','"+appReq.body[i].Location+"',"+
appReq.body[i].TotalDiscountAmount+","+appReq.body[i].Total+",'"+appReq.body[i].SalesmanId+"','"+
appReq.body[i].CustomerId+"',"+appReq.body[i].Latitude+","+appReq.body[i].Longitude+")")
.catch(function(err){
console.log(err);
});
}
}).catch(function(err){
console.log(err);
});
});
I tried to trace whether it reached the endpoint or not using console.log. However, it never executes.
Could you help me to spot where I went wrong? Thanks in advance.
There's nothing in your .NET code that actually sends the WebRequest. You create the request, write some JSON to it's stream, and flush it. Here's a simple way to make the network call (untested):
public async Task<int> InsertSales(IEnumerable<Models.SalesTable> newSales)
{
var ipAddress = "";// your IP address here
var port = ""; // your port here
var endpoint = $"http://{ipAddress}:{port}/insertsalesline";
var requestString = JsonConvert.SerializeObject(newSales);
var content = new StringContent(requestString, Encoding.UTF8, "application/json");
using (var client = new HttpClient())
{
var reponse = await client.PostAsync(endpoint, content);
if (reponse.IsSuccessStatusCode)
return 1;
else
return 0;
}
}
I'm developing a C#.NET MVC Web Api for an Android application. At the moment I am using OneSignal to send push notifications to the users by calling the OneSignal Api and passing the notification content. I need to know how to add a user to a specific segment so that i can send notifications to individual users as well as users of that segment collectively. I have searched in on their documentation but I didn't understand how to do it using OneSignal.SendTag method. So basically how to do it in Visual Studio? So far i have done this:
string api_key = "dsabjd";
var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;
if (user != null)
{
string message = "This job is posted by: \n" + user.Name + "\n" + user.Contact + "\n" +user.City;
if (request != null)
{
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("authorization", "Basic "+api_key);
var serializer = new JavaScriptSerializer();
var obj = new
{
app_id = "1651",
contents = new { en = message },
//data = new { image = "http://dsadasdasd.png" },
data = new { image = imageUrl },
included_segments = new string[] { "All" }
};
var param = serializer.Serialize(obj);
byte[] byteArray = Encoding.UTF8.GetBytes(param);
try
{
using (var writer = request.GetRequestStream())
{
writer.Write(byteArray, 0, byteArray.Length);
}
string responseContent=null;
using (var response = request.GetResponse() as HttpWebResponse)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
responseContent = reader.ReadToEnd();
}
}
if (responseContent != null)
{
// parsing the json returned by OneSignal Push API
dynamic json = JObject.Parse(responseContent);
int noOfRecipients = json.recipients;
if (noOfRecipients > 0)
{
flag = true;
}
}
}
catch (WebException ex)
{
flag = false;
}
}
}
To set tags it is recommend you use sendTags from the OneSignal Android SDK in your app it's supported offline and handles retries for you.
If you need to target individual users it is recommend to call idsAvailable in your app and send this to your server. You can later use the include_player_ids field on the create notification REST API POST call to send a notification to a list of users.