InvalidOperationException with BeginGetRequestStream - c#

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

Related

HTTP Post method is not working for yammer api

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

How to send pushnotifications in windows phone 8.1 runtime app (not silverlight)?

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. ?

Push notification Chrome Mobile Ver 42+

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

toast notification in windows phone 8 - stream error

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

Sending message from C# web method to Firebase Cloud Messaging returns 401

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

Categories