I am trying a demo of push notification suggested by this article.
https://developers.google.com/web/updates/2015/03/push-notificatons-on-the-open-web?hl=en
and trying to run code from github https://github.com/GoogleChrome/samples/tree/gh-pages/push-messaging-and-notifications
As per instruction I have done following things -
1. Created project on google developer console.
2. Added browser application key in to config.js > gcmAPIKey :'browser api key'
3.Added gsm_sender_id :'Project number' into manifest.json
4. Hosted application on https://somedomain.com
and result is this
Whenever I click on SendPushMessage button it doesn't show any notification. While debugging, I found that this request get fired
https://xxsomedomainxxx.azurewebsites.net/api/get/?subscriptionId=APA91bE_xyl2sP8l1pa8j4n84VGfJgKVb28I0DJK5qo9zUVLy0ZSRsyl2BbjLDSZ-Y625LqsmMp3rIH4PW3s1v_ccBOdCbWYsxaF525FHRbx5odr-z1a1uPrP4zqy4DFlKkwa9pyHhkdxL0ggxGBbC_bB6LTZSDuTKlDeXTRhywcY9X5KxBXrxhS_4M8oJFUi3eW6FikEUiJ
As per my observation I need to catch substriptionId on server and need to do something with it. So what kind of code should I need to write on server for below API
https://xxsomedomainxxx.azurewebsites.net/api/get/
I have created one WCF REST service with following code and its sending notification to android chrome 42+.
But one problem is here, notification shows message from service-worker.js file, not from in this code
var value = "Hello from server";
. I am working on it and update this answer soon.
Please update this function in main.js file
function getNotification(subscription) {
navigator.serviceWorker.ready.then(function (serviceWorkerRegistration) {
serviceWorkerRegistration.pushManager.subscribe()
.then(function (subscription) {
console.log('getNotification', subscription)
fetch('/pushnotificationservice.svc/sendnotification?key=' + subscription.subscriptionId).then(function (obj) {
console.log('getNotification', obj)
});
});
});
WCF Service Code
public string SendNotification(string key)
{
ServiceData myServiceData = new ServiceData();
try
{
string GoogleAppID = "2440XXXXXXXX";//put your project number here
string redId = key;
var SENDER_ID = "youremail#gmail.com";//I haven't tried with another junk value
var value = "Hello from server";//this message do not displayed in notification
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}", "Your browser 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() + "®istration_id=" + key + "";
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 (FaultException fex)
{
myServiceData.Result = false;
myServiceData.ErrorMessage = "unforeseen error occurred. Please try later.";
myServiceData.ErrorDetails = fex.ToString();
throw new FaultException<ServiceData>(myServiceData);
}
}
Related
I have the project in asp.net MVC 5 I need to add all option to my client-side app
which is send a push notification to android and ios app
for this scenario, I had created a page like a firebase cloud messaging =>
create message
c# code
private static string SendPushNotification()
{
string response;
try
{
string serverKey = "##########";
string senderId = "#############";
string deviceId = "//topics/all";
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 = "Greetings",
title = "Augsburg",
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}", serverKey));
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 = sResponseFromServer;
}
}
}
}
}
catch (Exception ex)
{
response = ex.Message;
}
return response;
}
So My query is that
1: I could send all these options to my HTTP request or not
2: There is open to send later open I need to also configure this
option
3: And Target User option?
Could I do this using HTTP request by providing parameters?
Not all.For most of the text fields, you can (see the docs for the HTTP ref):
Message Text = body
Message label: Nope. See the help text (?), it's just a label that the Firebase Console uses.
Delivery Date: See #2.
User Segment: See #3.
Message title = title
Android Notification Channel Name = android_channel_id
Scheduled notifications are currently not available for the REST API.
User Segments currently not available yet.
I have used Push notification in my web application using asp.net webforms.
That Push notification works fine in my Localhost connecting live Database but failed to work in Production Server.
What can be the Issue ?
Do i Need to make changes in my webConfig file?????
Please Suggest
public static void CallPUshNotiFication(string Msg,string EmailId,string PageName)
{
try
{
DataSet dsregID = new DataSet();
StringBuilder strBldId = new StringBuilder();
var applicationID = Validate.ApplicationId;
var SENDER_ID = Validate.SenderId;
List<MobileRegistration11> PuschList = MobileRegistrationManager1.GetDataFromMobileRegistration1(EmailId);
if (PuschList.Count > 0)
{
foreach (var item in PuschList)
{
string regId = Convert.ToString(item.RegistrationId);
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
//
tRequest.UseDefaultCredentials = true;
tRequest.PreAuthenticate = true;
tRequest.Credentials = CredentialCache.DefaultCredentials;
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));
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
+ Msg + "®istration_id=" + regId + "&data.id=" + PageName+ "&data.recordId="+147+"";
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();
strBldId.Append(sResponseFromServer + "<br>"); //printing response from GCM server.
tReader.Close();
dataStream.Close();
tResponse.Close();
}
}
}
catch (Exception ex)
{
}
}
I you have access to your machine, then try running this on command line.
Replace your topic and key. You may need to install curl.
curl -X POST -H "Content-Type: application/json" -H "Authorization: key=<PUT your key>" -d '{
"condition": "'"'"'<Put your topic>' in topics",
"data": {
"payload": ""
}
}
' "https://fcm.googleapis.com/fcm/send"
If this is giving proper response, then we can be certain that your machine is able to access GCM server. Then we can move to other things.
Thanks
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() + "®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();
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.
I need to implement a service for sending invitation mail to users.
I am following Samlman's artice.
I am trying to get a permanent token for Yammer API using the post method shown below.
I'm currently getting:
Error: 404 "server not found error".
There is no inner exception.
Do I need to pass authHeader?
If yes, then how do I send the authHeader?
string authUrl1 = string.Format("https://www.yammer.com/session?client_id={0}" , CLIENT_ID);
string postBody = string.Format(
"{0}{1}{2}{3}{4}{5}{6}",
"utf8=%E2%9C%93&authenticity_token=",
System.Web.HttpUtility.UrlEncode(authToken),
"&network_permalink=&login=",
HttpUtility.UrlEncode(userName),
"&password=",
pwd,
"&remember_me=off");
//make the first post for code
postResults = MakePostRequest(postBody, authUrl1);
private static string MakePostRequest(string postBody, string url, string authHeader = null, string contentType = null)
{
string results = string.Empty;
try
{
//get the session and yamtrack cookie
SetCookies();
wr = WebRequest.CreateHttp(url);
wr.Method = "POST";
wr.CookieContainer = cc;
//if an authHeader was provided, add it as a Bearer token to the request
if (!string.IsNullOrEmpty(authHeader))
wr.Headers.Add("Authorization", "Bearer " + authHeader);
byte[] postByte = Encoding.UTF8.GetBytes(postBody);
if (string.IsNullOrEmpty(contentType))
wr.ContentType = "application/x-www-form-urlencoded";
else
wr.ContentType = contentType;
wr.ContentLength = postByte.Length;
Stream postStream = wr.GetRequestStream();
postStream.Write(postByte, 0, postByte.Length);
postStream.Close();
wResp = (HttpWebResponse)wr.GetResponse();
postStream = wResp.GetResponseStream();
StreamReader postReader = new StreamReader(postStream);
results = postReader.ReadToEnd();
postReader.Close();
postStream.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error in MakePostRequest: " + ex.Message);
}
return results;
}
The information in that blog is incorrect, it does not work and it is unsupported by Yammer. I'd advise you pre-obtain the token using a service account, store it somewhere safe, then pass it as an Authorization header in your POST and/or GET request. A very good example is shown here - http://blogs.technet.com/b/israelo/archive/2015/02/24/consuming-yammer-restful-api-with-angularjs-for-dummies.aspx
I have sent push notification using ASP.net C# by GCM to android mobiles.
But I tried different kinds of code but all arr return Missing Registration error, So please help me.
try PushSharp. it's pretty straightforward.
and check this instruction - How to Configure & Send GCM Google Cloud Messaging Push Notifications using PushSharp
var push = new PushBroker();
//Registering the GCM Service and sending an Android Notification
push.RegisterGcmService(new GcmPushChannelSettings("theauthorizationtokenhere"));
//Fluent construction of an Android GCM Notification
//IMPORTANT: For Android you MUST use your own RegistrationId here that gets generated within your Android app itself!
push.QueueNotification(new GcmNotification().ForDeviceRegistrationId("DEVICE REGISTRATION ID HERE")
.WithJson("{\"alert\":\"Hello World!\",\"badge\":7,\"sound\":\"sound.caf\"}"));
You can install it via nuget.
public class GCMSNS
{
public static string SendGCMNotification(string deviceId, string message)
{
string GoogleAppID = "XYxxxxxxxxxxxxxxxxxxxx";//This is API Key Server
var SENDER_ID = "11111111111111"; //This is Google Project Id
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() + "®istration_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;
}
}