I have download toast notification sample code from microsoft site but the code is not executed properly -- giving an error in httpwebresponse --
protected void ButtonSendToast_Click(object sender, EventArgs e)
{
try
{
// Get the Uri that the Microsoft Push Notification Service returns to the Push Client when creating a notification channel.
// Normally, a web service would listen for Uri's coming from the web client and maintain a list of Uri's to send
// notifications out to.
string subscriptionUri = TextBoxUri.Text.ToString();
HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);
// We will create a HTTPWebRequest that posts the toast notification to the Microsoft Push Notification Service.
// HTTP POST is the only allowed method to send the notification.
sendNotificationRequest.Method = "POST";
// The optional custom header X-MessageID uniquely identifies a notification message.
// If it is present, the // same value is returned in the notification response. It must be a string that contains a UUID.
// sendNotificationRequest.Headers.Add("X-MessageID", "<UUID>");
// Create the toast message.
string toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>" + TextBoxTitle.Text.ToString() + "</wp:Text1>" +
"<wp:Text2>" + TextBoxSubTitle.Text.ToString() + "</wp:Text2>" +
"<wp:Param>/Page2.xaml?NavigatedFrom=Toast Notification</wp:Param>" +
"</wp:Toast> " +
"</wp:Notification>";
// Sets the notification payload to send.
byte[] notificationMessage = Encoding.Default.GetBytes(toastMessage);
// Sets the web request content length.
sendNotificationRequest.ContentLength = notificationMessage.Length;
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");
sendNotificationRequest.Headers.Add("X-NotificationClass", "2");
using (Stream requestStream = sendNotificationRequest.GetRequestStream())
{
requestStream.Write(notificationMessage, 0, notificationMessage.Length);
}
// Send the notification and get the response.
HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse(); // Exception in this line
string notificationStatus = response.Headers["X-NotificationStatus"];
string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
// Display the response from the Microsoft Push Notification Service.
// Normally, error handling code would be here. In the real world, because data connections are not always available,
// notifications may need to be throttled back if the device cannot be reached.
TextBoxResponse.Text = notificationStatus + " | " + deviceConnectionStatus + " | " + notificationChannelStatus;
}
catch (Exception ex)
{
TextBoxResponse.Text = "Exception caught sending update: " + ex.ToString();
}
}
}
I tried running this code in vs 2010 and vs 2013 express but still got the same error
Related
I am having trouble reading the response of the server after it has been read before. I can get the response of the server the first time it has been read but when I send something else back to the server the response will be null and I get a crash on the response = sr.ReadToEnd();.
What should happen with the two args is it updates the location with the second arg. Then it sends to the server and then the server responds with Ok. In following requests the new location is used instead of the first one.
The error message complains abouut line 102, which is:
response = sr.ReadToEnd();
This is the first writing of the args to the server and the response being given.
// these are the args being sent to the server
sw.WriteLine(args[0]);
// the flush sends this to the server which the response is then read
sw.Flush();
try
{
response = sr.ReadToEnd();
//[some if statement...]
else if (args.Length == 2)
{
//response = sr.ReadLine();
if (args[1] != response)
{
// this is what should be put in 'sw.write()' for the updated database entry
// <name><space><location><CR><LF>
// cssbct + " " + "is in fenner", so "cssbct location has changed"
// args[0] + " " + response
// response is now what the arg is
response = args[1];
// write the new response so that it will be sent to the server
sw.WriteLine(args[0] + " " + response);
// send it to the server
sw.Flush();
// write out the args and that the location has changed
Console.WriteLine(args[0] + " " + " location changed to be" + " " + response);
// just testing what the response should be
Console.WriteLine(args[0] + " " + response);
// read the response from the server
response = sr.ReadToEnd();
// if it equals "OK" do this
if (response == "OK")
{
// drops connection to the server
// probably not what is needed but look at later date
Console.WriteLine(response);
Console.WriteLine("Client connection closed");
client.Close();
}
}
}
sw.Flush();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Is what I am doing the correct way to receive the second response by the server?
I dont find a way using the streamReader/Writer to get the second response of the server.
EDIT: The connections
string response = "";
TcpClient client = new TcpClient();
client.Connect("whois.net.dcs.hull.ac.uk", 43);
// client.Connect("whois.networksolutions.com", 43);
Stream stream = client.GetStream();
StreamWriter sw = new StreamWriter(client.GetStream(), Encoding.ASCII);
StreamReader sr = new StreamReader(client.GetStream(), Encoding.ASCII);
Spec of the Client and server response
A request from Client to server Using 1 Arg: name CR LF
A request from client to server Using 2 Args to update the DB:
name space location CRLF
Server responses (don't have access to the server code, it is just said it will just do such things)
A response from server looks like:
[drops connection]
If no entries are found
"ERROR: no entries found
[drops connection]
If the server updates the database wit the new location:
OK
[drops connection]
An idea: Could the reason for the response being null be that it has reached the end of the stream?
I want to send a notification to multiple device in single FCM request. My notification text is same for all devices.
I would like to send notification to mobile devices in a batch of 100 per request. I am using c# asmx service.
Below is my code.
string regid="c_Z5yRoj4TY:APA91bGry2g_CIA1xaRy_LscxOvFX6YHqasKA96TjpG6yi1yytNyM5rtGL6DgxjGMSE5c74d7VdSL6W8zxO1ixVMlpVMwdgcrsGUWV0VfdbddC2XD","c_Z5yRoj4TY:APA91bGry2g_CIA1xaRy_LscxOvFX6YHqasKA96TjpG6yi1yytNyM5rtGL6DgxjGMSE5c74d7";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://fcm.googleapis.com/fcm/send");
httpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
httpWebRequest.Method = "POST";
String collaps_key = "Score_update";
string json = "collapse_key=abcd" + "&data.header=cricket®istration_id=" + regId + "&data.notificationId=" + notificationId + "&data.message=" + msg;
httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
httpWebRequest.Headers.Add(string.Format("Sender: key={0}", SENDER_ID));
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
//Console.WriteLine(json);
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
using (HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
retmsgid = result.ToString();
if (retmsgid.Trim() != "")
{
ResponceString = result.ToString();
string[] msgsplits = retmsgid.Split(',');
string[] msg1 = msgsplits[0].ToString().Split(':');
ReturnMessageId = msg1[1].ToString();
}
else
{
ReturnMessageId = "0";
}
}
httpResponse.Close();
httpResponse.Dispose();
httpWebRequest = null;
}
}
In order to send to specific multiple registration devices, you'll have to make use of the registration_ids parameter:
This parameter specifies the recipient of a multicast message, a message sent to more than one registration token.
The value should be an array of registration tokens to which to send the multicast message. The array must contain at least 1 and at most 1000 registration tokens. To send a message to a single device, use the to parameter.
In your code, you were using registration_id which I think is invalid. It should be registration_ids:
string json = "collapse_key=abcd" + "&data.header=cricket®istration_ids=" + regIds + "&data.notificationId=" + notificationId + "&data.message=" + msg;
-- regIds here is an Array of Strings that contain your registration tokens.
Some previous posts that may also help (see the OPs code snippets):
FCM (Firebase Cloud Messaging) Send to multiple devices
How to send multiple Firebase Cloud Message with C#?
I am developing windows phone app, In this app I want to develop send pushnotifications for devices.
Below is my code
string subscriptionUri = "http://s.notify.live.net/u/1/hk2/H2QAAADrEJ2fJgP0eNwNQ5Xp139q1mNu9TCpEwwxjX6j1";
var sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);
// Create an HTTPWebRequest that posts the toast notification to the Microsoft Push Notification Service.
// HTTP POST is the only method allowed to send the notification.
sendNotificationRequest.Method = "POST";
// The optional custom header X-MessageID uniquely identifies a notification message.
// If it is present, the same value is returned in the notification response. It must be a string that contains a UUID.
// sendNotificationRequest.Headers.Add("X-MessageID", "<UUID>");
// Create the toast message.
var toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>" + message + "</wp:Text1>" +
"</wp:Toast> " +
"</wp:Notification>";
// Set the notification payload to send.
byte[] notificationMessage = Encoding.Default.GetBytes(toastMessage);
// Set the web request content length.
sendNotificationRequest.ContentLength = notificationMessage.Length;
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");
sendNotificationRequest.Headers.Add("X-NotificationClass", "2");
using (var requestStream = sendNotificationRequest.GetRequestStream())
{
requestStream.Write(notificationMessage, 0, notificationMessage.Length);
}
// Send the notification and get the response.
var response = (HttpWebResponse)sendNotificationRequest.GetResponse();
var notificationStatus = response.Headers["X-NotificationStatus"];
var notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
var deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
// Display the response from the Microsoft Push Notification Service.
// Normally, error handling code would be here. In the real world, because data connections are not always available,
// notifications may need to be throttled back if the device cannot be reached.
var rep = notificationStatus + " | " + deviceConnectionStatus + " | " + notificationChannelStatus;
return rep;
Above code I am sending my deviceid for the
string subscriptionUri = "http://s.notify.live.net/u/1/hk2/H2QAAADrEJ2fJgP0eNwNQ5Xp139q1mNu9TCpEwwxjX6j1"
var sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);
// Create an HTTPWebRequest that posts the toast notification to the Microsoft Push Notification Service.
// HTTP POST is the only method allowed to send the notification.
sendNotificationRequest.Method = "POST";
// The optional custom header X-MessageID uniquely identifies a notification message.
// If it is present, the same value is returned in the notification response. It must be a string that contains a UUID.
// sendNotificationRequest.Headers.Add("X-MessageID", "<UUID>");
// Create the toast message.
var toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>" + message + "</wp:Text1>" +
"</wp:Toast> " +
"</wp:Notification>";
// Set the notification payload to send.
byte[] notificationMessage = Encoding.Default.GetBytes(toastMessage);
// Set the web request content length.
sendNotificationRequest.ContentLength = notificationMessage.Length;
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");
sendNotificationRequest.Headers.Add("X-NotificationClass", "2");
using (var requestStream = sendNotificationRequest.GetRequestStream())
{
requestStream.Write(notificationMessage, 0, notificationMessage.Length);
}
// Send the notification and get the response.
var response = (HttpWebResponse)sendNotificationRequest.GetResponse();
var notificationStatus = response.Headers["X-NotificationStatus"];
var notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
var deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
// Display the response from the Microsoft Push Notification Service.
// Normally, error handling code would be here. In the real world, because data connections are not always available,
// notifications may need to be throttled back if the device cannot be reached.
var rep = notificationStatus + " | " + deviceConnectionStatus + " | " + notificationChannelStatus;
return rep;
But whenever comes to response its throwing error.(400 error).
I am getting SubscriptionUri from below code:
var channelOperation = Windows.Networking.PushNotifications.PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
Please help me. How to send pushnotifications for the devices. ?
I am getting following error:
System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=Operation is not valid due to the current state of the object.
Source=System.Windows
StackTrace:
at System.Net.Browser.ClientHttpWebRequest.InternalEndGetRequestStream(IAsyncResult asyncResult)
at System.Net.Browser.ClientHttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult)
at SophosMobileControl.MainPage.<>c__DisplayClass5.<PushTestButton_Click>b__3(IAsyncResult ar)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClass18.<InvokeGetRequestStreamCallback>b__16(Object state2)
InnerException:
with folowwing code:
// Get the URI that the Microsoft Push Notification Service returns to the push client when creating a notification channel.
// Normally, a web service would listen for URIs coming from the web client and maintain a list of URIs to send
// notifications out to.
string subscriptionUri = (App.Current.Resources["Locator"] as ViewModelLocator).Main.PushUri;
HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);
// Create an HTTPWebRequest that posts the toast notification to the Microsoft Push Notification Service.
// HTTP POST is the only method allowed to send the notification.
sendNotificationRequest.Method = "POST";
// Create the toast message.
string toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>" + "Title" + "</wp:Text1>" +
"<wp:Text2>" + "Subtitle" + "</wp:Text2>" +
"</wp:Toast> " +
"</wp:Notification>";
// Set the notification payload to send.
byte[] notificationMessage = Encoding.UTF8.GetBytes(toastMessage);
// Set the web request content length.
sendNotificationRequest.ContentLength = notificationMessage.Length;
sendNotificationRequest.ContentType = "text/xml";
//sendNotificationRequest.Headers["X-WindowsPhone-Target"] = "toast";
//sendNotificationRequest.Headers["X-NotificationClass"] = "2";
sendNotificationRequest.BeginGetRequestStream(ar =>
{
using (Stream postStream = sendNotificationRequest.EndGetRequestStream(ar))
{
postStream.Write(notificationMessage, 0, notificationMessage.Length);
}
}, sendNotificationRequest);
My solution was to change following code:
sendNotificationRequest.BeginGetRequestStream(ar =>
{
using (Stream postStream = sendNotificationRequest.EndGetRequestStream(ar))
{
postStream.Write(notificationMessage, 0, notificationMessage.Length);
}
}, sendNotificationRequest);
by following:
sendNotificationRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), sendNotificationRequest);
void GetRequestStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
// End the stream request operation
Stream postStream = myRequest.EndGetRequestStream(callbackResult);
// Add the post data to the web request
postStream.Write(notificationMessage, 0, notificationMessage.Length);
postStream.Close();
}
I use the following C# web method to webRequest Firebase Cloud Messaging
public void messgaeFCM(String cToken) {
try
{
//send message to clientToken through FCM server
WebRequest wr = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
wr.Method = "POST";
wr.ContentType = "application/json";
wr.Headers.Add("Authorization", "Key='" + FIREBASE_PROJECT_ID +"'");
String notification = "{ 'data': " +
"{" +
"'title': 'Firebase notification'," +
"'detail': 'I am firebase notification. you can customise me. enjoy'," +
"}," +
"'to' : '" + cToken + "'" +
"}";
byte[] byteArray = Encoding.UTF8.GetBytes(notification);
Stream dataStream = wr.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = wr.GetResponse();
}
catch (Exception e)
{
new general().logError(e.Message);
}
}
FIREBASE_PROJECT_ID value set to the FCM project id.
cToken value set for a valid client token.
The above code always returns the following error :
The remote server returned an error: (401) Unauthorized.
Not sure what is wrong...
wr.Headers.Add("Authorization", "Key='" + FIREBASE_PROJECT_ID +"'");
Try removing the single quote:
wr.Headers.Add("Authorization", "Key=" + FIREBASE_PROJECT_ID);