app crashes when trying to send multiple fcm messages programmatically - xamarin.forms

i am trying to create a messaging app using xamarin.forms. i created a send button and added the following code:
private async void send_Clicked(object sender, EventArgs e)
{
await Task.Run(() => SendNotification(token, "title", message.Text));
}
and the sendnotification is as follows:
public string SendNotification(string DeviceToken, string title, string msg)
{
var result = "-1";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
httpWebRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
httpWebRequest.Method = "POST";
var payload = new
{
//to= "/topics/klm",
to = DeviceToken,
//to = "egjLx6VdFS0:APA91bGQMSSRq_wCzywNC01zJi4FBtHXrXuL-p4vlkl3a3esdH8lxo7mQZUBlrTi7h-6JXx0GrJbwc9Vx6M5Q4OV_3CArcdlP0XMBybervQvfraWvqCgaa75gu9SVzjY4V_qd36JGg4A",
priority = "high",
content_available = true,
data = new
{
text = msg,
},
};
var serializer = new JsonSerializer();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = JsonConvert.SerializeObject(payload);
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
this is private string webAddr = "https://fcm.googleapis.com/fcm/send";
when i click send the first time, i receive the message perfectly, when i hit send the second time, the app freezes then crashes and asks me if i want to close the app or wait. why is this happening? thanks in advance

Related

How to capture image from camera and convert the image to base 64 string send to the server in xamarin forms?

I am new to xamarin forms. I implement a simple program where the image is capture from the camera and convert into base64 string and send it to the server like below.
private async void AddNewPhoto(object sender, EventArgs e)
{
MemoryStream memoryStream = new MemoryStream();
img.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
file.GetStream().CopyTo(memoryStream);
return stream;
});
paths.Enqueue(filePath);
imgPaths.Add(file);
val.Add(img.Source);
// Set StackLayout in XAML to the class field
parent = headerStack1;
parent.Children.Add(img);
}
async void btnSubmitClicked(object sender, EventArgs args)
{
if (paths.Count > 0)
{
string URL1 = "";
string basicDomain1 = AppConstant.ComplaintsUploadImageURL + PhoneNo + "~secretcode-" +
secretCode;
MultipartFormDataContent form1 = new MultipartFormDataContent();
DependencyService.Get<IHudService>().ShowHud("Loading");
List<string> pathItems = new List<string>();
for each (MediaFile ph in imgPaths)
{
var fileName = filePath.Split('\\').LastOrDefault().Split('/').LastOrDefault();
var file = ph;
var upfilebytes = File.ReadAllBytes(file.Path);
var base64 = Convert.ToBase64String(upfilebytes);
var content = new StringContent(base64);
form1.Add(content, "image_64string");
Dictionary<string, string> UploadJson = new Dictionary<string, string>();
UploadJson.Add("image_txt", imgText);
form1.Add(new StringContent(UploadJson["image_txt"]), "image_txt");
form1.Add(new StringContent("jpg"), "image_extension");
var response_ = await this.apiService.PostImageRequest(form1, URL1, basicDomain1);
if (!response_.IsSuccess)
{
await Application.Current.MainPage.DisplayAlert("Error", response_.Message, "Network Problem!!");
return;
}
}
}
}
But it shows the error "Can not access the closed stream." How to fix this error?

FCM PushNotification to iOS device from .NET

Is it possible to use Firebase's FCM to send apns push notifications to an ios device?
Desired Workflow:
iOS app sends request to my .NET server to provide it the push token. My .NET server will handle all push notifications. So I assume this would be http requests to firebase and firebase would send out the notification?
Is this workflow possible?
I have worked with Android Applications using Firebase's FCM.. so i think there must be way to work with ios.
here is the snippet of code for sending push notification using fcm in c#.
NotifBooking objnotif = new NotifBooking();
string ApplicationID = "AIzaSyCBM20ZXXXXXXXXXXjog3Abv88";
string SENDER_ID = "962XXXXXXX";
var value = "Alert :" + Message + ""; //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));
tRequest.ContentType = "application/json";
var data1 = new
{
to = "" + dt.Rows[i]["RegId"].ToString().Trim() + "",//Device RegID
priority = "high",
notification = new
{
body = Message,
title = Heading,
is_background = true,
image = "abc.com/images/1_icon.png",
appicon = "abc.com/images/1_icon.png",
sound = "default"
},
data = new
{
//body = Message,
//is_background=false,
//title = "Test FCM",
//appicon = "myicon",
image = "abc.com/images/1_icon.png"
},
};
Console.WriteLine(data1);
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data1);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
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;
}
}
}
}
objnotif.data = json;
}
You should get device token from Firebase and register the current user in backend side with the same token.
After that, you can send push notifications from your backend.
Put this code in AppDelegate class.
Call InitAPNS() from FinishedLaunching.
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
//TODO: save token and register one in backend side
Settings.DeviceTokenFCM = InstanceId.SharedInstance.Token;
}
public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
ShowPushMessage(userInfo);
}
private void ShowPushMessage(NSDictionary userInfo)
{
if (userInfo != null)
{
try
{
var apsDictionary = userInfo["aps"] as NSDictionary;
var alertDictionary = apsDictionary?["alert"] as NSDictionary;
var body = alertDictionary?["body"].ToString();
var title = alertDictionary?["title"].ToString();
var window = UIApplication.SharedApplication.KeyWindow;
var vc = window.RootViewController;
var alert = UIAlertController.Create(title, body, UIAlertControllerStyle.Alert);
alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Cancel, null));
vc.PresentViewController(alert, animated: true, completionHandler: null);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
}
}
private void InitAPNS()
{
// Monitor token generation
InstanceId.Notifications.ObserveTokenRefresh(TokenRefreshNotification);
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.Sound, (granted, error) =>
{
if (granted)
{
InvokeOnMainThread(UIApplication.SharedApplication.RegisterForRemoteNotifications);
}
});
}
else if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
new NSSet());
UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
UIApplication.SharedApplication.RegisterForRemoteNotifications();
}
else
{
UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
}
Firebase.Core.App.Configure();
}
private void TokenRefreshNotification(object sender, NSNotificationEventArgs e)
{
ConnectToFCM();
}
private void ConnectToFCM()
{
var tokenFirebase = InstanceId.SharedInstance.Token;
////registation token in background thread
System.Threading.Tasks.Task.Run(() =>
{
if (!string.IsNullOrEmpty(tokenFirebase))
{
Firebase.CloudMessaging.Messaging.SharedInstance.SetApnsToken(tokenFirebase, ApnsTokenType.Production);
}
});
Messaging.SharedInstance.ShouldEstablishDirectChannel = true;
}
IOS push Notification using C#.I have worked with Android Applications using Firebase's FCM.here is the snippet of code for sending push notification using fcm in c#.
**
namespace push
{
public partial class pushios : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SendPushNotification(txtDeviceToken.Text, txtMessage.Text);
}
private void SendPushNotification(string deviceToken,string message)
{
try
{
//Get Certificate
var appleCert = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Files/Certificate/IOS/Production_Certificate.p12"));
// Configuration (NOTE: .pfx can also be used here)
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, appleCert, "1234567890");
// Create a new broker
var apnsBroker = new ApnsServiceBroker(config);
// Wire up events
apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
{
aggregateEx.Handle(ex =>
{
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
var notificationException = (ApnsNotificationException)ex;
// Deal with the failed notification
var apnsNotification = notificationException.Notification;
var statusCode = notificationException.ErrorStatusCode;
string desc = $"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}";
Console.WriteLine(desc);
Label1.Text = desc;
}
else
{
string desc = $"Apple Notification Failed for some unknown reason : {ex.InnerException}";
// Inner exception might hold more useful information like an ApnsConnectionException
Console.WriteLine(desc);
Label1.Text = desc;
}
// Mark it as handled
return true;
});
};
apnsBroker.OnNotificationSucceeded += (notification) =>
{
Label1.Text = "Apple Notification Sent successfully!";
};
var fbs = new FeedbackService(config);
fbs.FeedbackReceived += (string devicToken, DateTime timestamp) =>
{
};
apnsBroker.Start();
if (deviceToken != "")
{
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = deviceToken,
Payload = JObject.Parse(("{\"aps\":{\"badge\":1,\"sound\":\"oven.caf\",\"alert\":\"" + (message + "\"}}")))
});
}
apnsBroker.Stop();
}
catch (Exception)
{
throw;
}
}
}
**
I have worked with Android Applications using Firebase's FCM..
namespace pushios.Controllers
{
public class HomeController : ApiController
{
[HttpGet]
[Route("sendmessage")]
public IHttpActionResult SendMessage()
{
var data = new {
to = "xxxxxxxxxxxxxxxxxxx",
data = new
{
body="Test",
confId= "6565",
pageTitle= "test",
pageFormat= "",
dataValue= "",
title= "C#",
webviewURL= "",
priority = "high",
notificationBlastID = "0",
status = true
}
};
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;
}
}
}
}
```

how to make a web application in .NET send notifications to firebase? [duplicate]

I am using this code to send notification message by C# with GCM, using Winforms, Webforms, whatever. Now I want to send to FCM (Firebase Cloud Messaging). Should I update my code? :
public class AndroidGCMPushNotification
{
public AndroidGCMPushNotification()
{
//
// TODO: Add constructor logic here
//
}
public string SendNotification(string deviceId, string message)
{
string SERVER_API_KEY = "server api key";
var SENDER_ID = "application number";
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}", SERVER_API_KEY));
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=" + deviceId + "";
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;
}
}
but the GCM was changed to FCM. Is this same code to send the notification?
Where can I find the SERVER_API_KEY? Is the same solution?
firebase cloud messaging with c#:
working all .net platform (asp.net, .netmvc, .netcore)
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
//serverKey - Key from Firebase cloud messaging server
tRequest.Headers.Add(string.Format("Authorization: key={0}", "AIXXXXXX...."));
//Sender Id - From firebase project setting
tRequest.Headers.Add(string.Format("Sender: id={0}", "XXXXX.."));
tRequest.ContentType = "application/json";
var payload = new
{
to = "e8EHtMwqsZY:APA91bFUktufXdsDLdXXXXXX..........XXXXXXXXXXXXXX",
priority = "high",
content_available = true,
notification = new
{
body = "Test",
title = "Test",
badge = 1
},
data = new
{
key1 = "value1",
key2 = "value2"
}
};
string postbody = JsonConvert.SerializeObject(payload).ToString();
Byte[] byteArray = Encoding.UTF8.GetBytes(postbody);
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())
{
if (dataStreamResponse != null) using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
//result.Response = sResponseFromServer;
}
}
}
}
Here is another approach of writing Notification Service inside ASP.Net REST API.
public async Task<bool> NotifyAsync(string to, string title, string body)
{
try
{
// Get the server key from FCM console
var serverKey = string.Format("key={0}", "Your server key - use app config");
// Get the sender id from FCM console
var senderId = string.Format("id={0}", "Your sender id - use app config");
var data = new
{
to, // Recipient device token
notification = new { title, body }
};
// Using Newtonsoft.Json
var jsonBody = JsonConvert.SerializeObject(data);
using (var httpRequest = new HttpRequestMessage(HttpMethod.Post, "https://fcm.googleapis.com/fcm/send"))
{
httpRequest.Headers.TryAddWithoutValidation("Authorization", serverKey);
httpRequest.Headers.TryAddWithoutValidation("Sender", senderId);
httpRequest.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
var result = await httpClient.SendAsync(httpRequest);
if (result.IsSuccessStatusCode)
{
return true;
}
else
{
// Use result.StatusCode to handle failure
// Your custom error handler here
_logger.LogError($"Error sending notification. Status Code: {result.StatusCode}");
}
}
}
}
catch (Exception ex)
{
_logger.LogError($"Exception thrown in Notify Service: {ex}");
}
return false;
}
References:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
I have posted this answer as this question was viewed most and this server side code was written in VS 2015 in C# for sending push notification either single device based on device id or subscribed topic to Xamarin Android app
public class FCMPushNotification
{
public FCMPushNotification()
{
// TODO: Add constructor logic here
}
public bool Successful
{
get;
set;
}
public string Response
{
get;
set;
}
public Exception Error
{
get;
set;
}
public FCMPushNotification SendNotification(string _title, string _message, string _topic)
{
FCMPushNotification result = new FCMPushNotification();
try
{
result.Successful = true;
result.Error = null;
// var value = message;
var requestUri = "https://fcm.googleapis.com/fcm/send";
WebRequest webRequest = WebRequest.Create(requestUri);
webRequest.Method = "POST";
webRequest.Headers.Add(string.Format("Authorization: key={0}", YOUR_FCM_SERVER_API_KEY));
webRequest.Headers.Add(string.Format("Sender: id={0}", YOUR_FCM_SENDER_ID));
webRequest.ContentType = "application/json";
var data = new
{
// to = YOUR_FCM_DEVICE_ID, // Uncoment this if you want to test for single device
to="/topics/"+_topic, // this is for topic
notification=new
{
title=_title,
body=_message,
//icon="myicon"
}
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
webRequest.ContentLength = byteArray.Length;
using (Stream dataStream = webRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse webResponse = webRequest.GetResponse())
{
using (Stream dataStreamResponse = webResponse.GetResponseStream())
{
using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
result.Response = sResponseFromServer;
}
}
}
}
}
catch(Exception ex)
{
result.Successful = false;
result.Response = null;
result.Error = ex;
}
return result;
}
}
and its uses
// start sending push notification to apps
FCMPushNotification fcmPush = new FCMPushNotification();
fcmPush.SendNotification("your notificatin title", "Your body message","news");
// end push notification
Yes, you should update your code to use Firebase Messaging interface.
There's a GitHub Project for that here.
using Stimulsoft.Base.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
namespace _WEBAPP
{
public class FireBasePush
{
private string FireBase_URL = "https://fcm.googleapis.com/fcm/send";
private string key_server;
public FireBasePush(String Key_Server)
{
this.key_server = Key_Server;
}
public dynamic SendPush(PushMessage message)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(FireBase_URL);
request.Method = "POST";
request.Headers.Add("Authorization", "key=" + this.key_server);
request.ContentType = "application/json";
string json = JsonConvert.SerializeObject(message);
//json = json.Replace("content_available", "content-available");
byte[] byteArray = Encoding.UTF8.GetBytes(json);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
HttpWebResponse respuesta = (HttpWebResponse)request.GetResponse();
if (respuesta.StatusCode == HttpStatusCode.Accepted || respuesta.StatusCode == HttpStatusCode.OK || respuesta.StatusCode == HttpStatusCode.Created)
{
StreamReader read = new StreamReader(respuesta.GetResponseStream());
String result = read.ReadToEnd();
read.Close();
respuesta.Close();
dynamic stuff = JsonConvert.DeserializeObject(result);
return stuff;
}
else
{
throw new Exception("Ocurrio un error al obtener la respuesta del servidor: " + respuesta.StatusCode);
}
}
}
public class PushMessage
{
private string _to;
private PushMessageData _notification;
private dynamic _data;
private dynamic _click_action;
public dynamic data
{
get { return _data; }
set { _data = value; }
}
public string to
{
get { return _to; }
set { _to = value; }
}
public PushMessageData notification
{
get { return _notification; }
set { _notification = value; }
}
public dynamic click_action
{
get
{
return _click_action;
}
set
{
_click_action = value;
}
}
}
public class PushMessageData
{
private string _title;
private string _text;
private string _sound = "default";
//private dynamic _content_available;
private string _click_action;
public string sound
{
get { return _sound; }
set { _sound = value; }
}
public string title
{
get { return _title; }
set { _title = value; }
}
public string text
{
get { return _text; }
set { _text = value; }
}
public string click_action
{
get
{
return _click_action;
}
set
{
_click_action = value;
}
}
}
}
Based on Teste's code .. I can confirm the following works. I can't say whether or not this is "good" code, but it certainly works and could get you back up and running quickly if you ended up with GCM to FCM server problems!
public AndroidFCMPushNotificationStatus SendNotification(string serverApiKey, string senderId, string deviceId, string message)
{
AndroidFCMPushNotificationStatus result = new AndroidFCMPushNotificationStatus();
try
{
result.Successful = false;
result.Error = null;
var value = message;
WebRequest 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}", serverApiKey));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
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=" + deviceId + "";
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
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();
result.Response = sResponseFromServer;
}
}
}
}
}
catch (Exception ex)
{
result.Successful = false;
result.Response = null;
result.Error = ex;
}
return result;
}
public class AndroidFCMPushNotificationStatus
{
public bool Successful
{
get;
set;
}
public string Response
{
get;
set;
}
public Exception Error
{
get;
set;
}
}
You need change url from https://android.googleapis.com/gcm/send to https://fcm.googleapis.com/fcm/send and change your app library too. this tutorial can help you https://firebase.google.com/docs/cloud-messaging/server#implementing-http-connection-server-protocol
Try to send a json object.
Replace this:
tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
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=" + deviceId + "";
Console.WriteLine(postData);
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
For this:
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);
Here's the code for server side firebase cloud request from C# / Asp.net.
Please note that your client side should have same topic.
e.g.
FirebaseMessaging.getInstance().subscribeToTopic("news");
public String SendNotificationFromFirebaseCloud()
{
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.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"to\": \"/topics/news\",\"data\": {\"message\": \"This is a Firebase Cloud Messaging Topic Message!\",}}";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
You can use this library, makes it seamless to send push notifications using Firebase Service from a C# backend download here
public SendNotice(int deviceType, string deviceToken, string message, int badge, int status, string sound)
{
AndroidFCMPushNotificationStatus result = new AndroidFCMPushNotificationStatus();
try
{
result.Successful = false;
result.Error = null;
var value = message;
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var serializer = new JavaScriptSerializer();
var json = "";
tRequest.Headers.Add(string.Format("Authorization: key={0}", "AA******"));
tRequest.Headers.Add(string.Format("Sender: id={0}", "11********"));
if (DeviceType == 2)
{
var body = new
{
to = deviceToken,
data = new
{
custom_notification = new
{
title = "Notification",
body = message,
sound = "default",
priority = "high",
show_in_foreground = true,
targetScreen = notificationType,//"detail",
},
},
priority = 10
};
json = serializer.Serialize(body);
}
else
{
var body = new
{
to = deviceToken,
content_available = true,
notification = new
{
title = "Notification",
body = message,
sound = "default",
show_in_foreground = true,
},
data = new
{
targetScreen = notificationType,
id = 0,
},
priority = 10
};
json = serializer.Serialize(body);
}
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
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();
result.Response = sResponseFromServer;
}
}
}
}
}
catch (Exception ex)
{
result.Successful = false;
result.Response = null;
result.Error = ex;
}
}
I write this code and It's worked for me .
public static string ExcutePushNotification(string title, string msg, string fcmToken, object data)
{
var serverKey = "AAAA*******************";
var senderId = "3333333333333";
var result = "-1";
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://fcm.googleapis.com/fcm/send");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
httpWebRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
httpWebRequest.Method = "POST";
var payload = new
{
notification = new
{
title = title,
body = msg,
sound = "default"
},
data = new
{
info = data
},
to = fcmToken,
priority = "high",
content_available = true,
};
var serializer = new JavaScriptSerializer();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = serializer.Serialize(payload);
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
I am using this approach and it is working fine:
public class PushNotification
{
private static readonly ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// firebase
private static Uri FireBasePushNotificationsURL = new Uri("https://fcm.googleapis.com/fcm/send");
private static string ServerKey = ConfigurationManager.AppSettings["FIREBASESERVERKEY"];
public static async Task<bool> SendPushNotification(List<SendNotificationModel> notificationData)
{
try
{
bool sent = false;
foreach (var data in notificationData)
{
var messageInformation = new Message()
{
notification = new Notification()
{
title = data.Title,
text = data.Message,
ClickAction = "FCM_PLUGIN_ACTIVITY"
},
data = data.data,
priority="high",
to =data.DeviceId
};
string jsonMessage = JsonConvert.SerializeObject(messageInformation);
//Create request to Firebase API
var request = new HttpRequestMessage(HttpMethod.Post, FireBasePushNotificationsURL);
request.Headers.TryAddWithoutValidation("Authorization", "key=" + ServerKey);
request.Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");
HttpResponseMessage result;
using (var client = new HttpClient())
{
result = await client.SendAsync(request);
sent = result.IsSuccessStatusCode;
}
}
return sent;
}
catch(Exception ex)
{
Logger.Error(ex);
return false;
}
}
}
Following Approach, I have used for writing Firebase Notification Service inside ASP.Net REST API.
public async Task<bool> NotifyAsync(string to, string title, string body)
{
try
{
//Server key from FCM console
var serverKey = string.Format("key={0}", "Provide your Server key here from Fibase console");
//Sender id from FCM console
var senderId = string.Format("id={0}", "Provide your Sender Id here from Firebase Console");
var data = new
{
to, // Recipient device token
notification = new { title, body }
};
// Using Newtonsoft.Json
var jsonBody = JsonConvert.SerializeObject(data);
using (var httpRequest = new HttpRequestMessage(HttpMethod.Post, "https://fcm.googleapis.com/fcm/send"))
{
httpRequest.Headers.TryAddWithoutValidation("Authorization", serverKey);
httpRequest.Headers.TryAddWithoutValidation("Sender", senderId);
httpRequest.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
var result = await httpClient.SendAsync(httpRequest);
if (result.IsSuccessStatusCode)
{
return true;
}
else
{
// Use result.StatusCode to handle failure
// Your custom error handler here
return false;
}
}
}
}
catch (Exception ex)
{
throw ex;
}
return false;
}
Refer This blog for send Group Notification
https://firebase.google.com/docs/cloud-messaging/android/send-multiple

I'm new to Json rest full services , how to get methods from json rest service? and how to Parse values to method in api using C# console applications

static void Main(string[] args)
{
const string url = "https://test-api.abccc.com/api/Relayxxx.apixxxx?__token=xxxxxxxxxxxxxxxxxx";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
/* using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"user\":\"xxxx\"," +
"\"password\":\"yyyy\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}*/
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
Please help me how to call functions using this api and how can i get values from specified functions and send values to specific function.

how to parse xml string from Post method response?

I have a xml string that return from Post method:
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
HttpStatusCode rcode = response.StatusCode;
var stream = new GZipInputStream(response.GetResponseStream());
using (StreamReader reader = new StreamReader(stream))
{
responseString = reader.ReadToEnd();
}
response.Close();
}
The responseString is the string I want to parse, using parseXmlString class below. However I can't call the method parseXmlString directly because of the static. How can I pass the responseString to the parseXmlString method to have them parse out and bind to the listBox. Or anyway to have the same result would be great.
void parseXmlString()
{
byte[] byteArray = Encoding.UTF8.GetBytes(responseString);
MemoryStream str = new MemoryStream(byteArray);
str.Position = 0;
XDocument xdoc = XDocument.Load(str);
var data = from query in xdoc.Descendants("tracks").Elements("item")
select new searchResult
{
artist = (string)query.Element("artist"),
album = (string)query.Element("album"),
track = (string)query.Element("track"),
// artistA = (string)query.Element("artists").Element("artist"),
};
// ListBox lb = new ListBox();
listBox1.ItemsSource = data;
var data1 = from query in xdoc.Descendants("artists").Elements("item")
select new searchResult
{
artistA = (string)query.Element("artist"),
};
listBox2.ItemsSource = data1;
}
Your approach is inversed logic. You know that you can have return values on methods, right?-)
What you need to do is let your ParseXmlString method take the responseString as a parameter, and let it return the created IEnumerable, like this:
private IEnumerable<SearchResult> ParseXmlString(responseString)
{
XDocument xdoc = XDocument.Load(responseString);
var data =
from query in xdoc.Descendants("tracks").Elements("item")
select new SearchResult
{
Artist = (string)query.Element("artist"),
Album = (string)query.Element("album"),
Track = (string)query.Element("track"),
};
return
from query in xdoc.Descendants("artists").Elements("item")
select new SearchResult
{
ArtistA = (string)query.Element("artist"),
};
}
And change your async code handling, to perform a callback to your UI thread, when it's done reading out the responseString.
Then, on your UI thread, you would do:
// This being your method to get the async response
GetResponseAsync(..., responseString =>
{
var searchResults = ParseXmlString(responseString);
listBox2.ItemsSource = searchResults;
})
You can see this answer, if you need some basic understanding of callbacks: Callbacks in C#

Resources