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
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() + "®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;
}
}
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() + "®istration_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() + "®istration_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 am developing a Windows phone 8 app that needs to upload photos to amazon s3 storage. However, I find that this is impossible since the HttpClient time out after about 60 seconds regardless of what timeout setting I use.
Is there really no way to upload large files from Windows Phone?
BackgroundTransferRequest is useless since it cannot send the neccessary metadata with file uploads.
I use this code (which times out):
using (var httpClient = new HttpClient())
{
httpClient.Timeout = TimeSpan.FromMinutes(30);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, m_uploadUrl);
httpContent.Headers.Add("Keep-Alive", "true");
request.Content = httpContent; // 3-5 Mb file
response = await httpClient.SendAsync(request);
statusCode = response.StatusCode;
}
I also tried PostAsync(), but same result. After about 60 sec the call completes with a status code 400 or 404. This is not a server timeout. IPhone and Android apps use the same service. No problems there.
Any ideas on how to upload files that takes more than 60 seconds to send?
I too faced similar things. The timeout glitch.
Check if you could use another class instead of HttpClient.
WebClient may be.
Check if this helps you:
http://blog.anthonybaker.me/2013/06/how-to-upload-file-from-windows-phone.html
and even this:
http://chriskoenig.net/2011/08/19/upload-files-from-windows-phone/
I got things working for me with those.
I've used several days now to implement a new uploader and get all the details working. I used HttpWebRequest with the async methods and split the file into chuncks. Finally I got it working and it uploads without the timeout. Here is the complete code:
using System;
using Models;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Services
{
public class UploadData
{
public Stream PostStream { get; set; }
public Stream FileStream { get; set; }
public byte[] HeaderBytes {get; set;}
public byte[] FooterBytes {get; set;}
public byte[] Buffer { get; set; }
public Photo Upload { get; set; }
public int BytesWritten { get; set; }
}
public class UploadEventArgs : EventArgs
{
public Photo Upload { get; set; }
public int Progress { get; set; }
}
public class UploadService
{
public delegate void CompletedEventHandler(object sender, UploadEventArgs e);
public event CompletedEventHandler UploadCompleted;
public delegate void ProgressEventHandler(object sender, UploadEventArgs e);
public event ProgressEventHandler ProgressChanged;
private static string contentType = "multipart/form-data; boundary={0}";
private static string headerString = "Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\nContent-Type: Content-Type: application/octet-stream\r\n\r\n";
private HttpWebRequest m_request;
private static string boundarystr;
private UploadData m_uploadData;
private bool m_isStopped;
public async Task StartUpload(Photo upload, Uri uri, Dictionary<string, string> parameters)
{
try
{
m_isStopped = false;
var fileStream = (await upload.File.OpenReadAsync()).AsStreamForRead();
var uploadData = new UploadData();
boundarystr = "---------------------------" + DateTime.Now.Ticks.ToString("x");
string para = GetParamsString(parameters);
string headAndParams = para + String.Format(headerString, HttpUtility.UrlEncode(upload.File.Name));
var headerBytes = System.Text.Encoding.UTF8.GetBytes(headAndParams);
var footerBytes = Encoding.UTF8.GetBytes("\r\n--" + boundarystr + "--\r\n");
uploadData.Upload = upload;
uploadData.FileStream = fileStream;
uploadData.FooterBytes = footerBytes;
uploadData.HeaderBytes = headerBytes;
uploadData.BytesWritten = 0;
m_uploadData = uploadData;
m_request = (HttpWebRequest)WebRequest.Create(uri);
m_request.Method = "POST";
m_request.AllowWriteStreamBuffering = false;
m_request.ContentType = string.Format(contentType, boundarystr);
m_request.ContentLength = fileStream.Length + headerBytes.Length + footerBytes.Length;
var asyncResult = m_request.BeginGetRequestStream((ar) => { GetRequestStreamCallback(ar, uploadData); }, m_request);
}
catch (Exception ex)
{
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = new Exception("Start upload failed: " + ex.Message);
var argsStopped = new UploadEventArgs();
argsStopped.Upload = m_uploadData.Upload;
m_uploadData.FileStream.Close();
m_uploadData.PostStream.Close();
OnUploadComplete(argsStopped);
}
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult, UploadData uploadData)
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
postStream.Write(uploadData.HeaderBytes, 0, uploadData.HeaderBytes.Length);
var args = new UploadEventArgs();
args.Upload = uploadData.Upload;
args.Progress = 1;
OnProgressChanged(args);
uploadData.PostStream = postStream;
WriteNextChunck(uploadData);
}
catch (Exception ex)
{
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = new Exception("Header write failed: " + ex.Message);
var argsStopped = new UploadEventArgs();
argsStopped.Upload = m_uploadData.Upload;
m_uploadData.FileStream.Close();
m_uploadData.PostStream.Close();
OnUploadComplete(argsStopped);
}
}
private void WriteNextChunck(UploadData upload)
{
try
{
if ((upload.FileStream.Length - upload.BytesWritten) >= 16 * 1024)
{
upload.Buffer = new byte[16 * 1024];
}
else
{
// Last part
upload.Buffer = new byte[upload.FileStream.Length - upload.BytesWritten];
}
upload.FileStream.Read(upload.Buffer, 0, (int)upload.Buffer.Length);
upload.PostStream.BeginWrite(upload.Buffer, 0, upload.Buffer.Length, BeginWriteCallback, upload);
}
catch (Exception ex)
{
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = new Exception("Buffer write failed: " + ex.Message);
var argsStopped = new UploadEventArgs();
argsStopped.Upload = m_uploadData.Upload;
upload.FileStream.Close();
upload.PostStream.Close();
OnUploadComplete(argsStopped);
}
}
private void BeginWriteCallback(IAsyncResult ar)
{
try
{
var upload = ar.AsyncState as UploadData;
upload.PostStream.EndWrite(ar);
upload.BytesWritten += upload.Buffer.Length;
var args = new UploadEventArgs();
args.Upload = upload.Upload;
args.Progress = (int)(((decimal)upload.BytesWritten / (decimal)upload.FileStream.Length) * 100);
OnProgressChanged(args);
if (m_isStopped)
{
upload.FileStream.Close();
upload.PostStream.Close();
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = new Exception("Upload stopped");
var argsStopped = new UploadEventArgs();
argsStopped.Upload = m_uploadData.Upload;
OnUploadComplete(argsStopped);
return;
}
// write next chunck
if (upload.BytesWritten < upload.FileStream.Length)
{
WriteNextChunck(upload);
}
if (upload.BytesWritten >= upload.FileStream.Length)
{
WriteFooter(upload);
}
}
catch (Exception ex)
{
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = new Exception("Upload write failed: " + ex.Message);
var argsStopped = new UploadEventArgs();
argsStopped.Upload = m_uploadData.Upload;
OnUploadComplete(argsStopped);
}
}
private void WriteFooter(UploadData upload)
{
try
{
upload.PostStream.Write(upload.FooterBytes, 0, upload.FooterBytes.Length);
upload.PostStream.Close();
var asyncResult = m_request.BeginGetResponse(new AsyncCallback(GetResponseCallback), m_request);
}
catch (Exception ex)
{
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = new Exception("Footer write failed: " + ex.Message);
var argsStopped = new UploadEventArgs();
argsStopped.Upload = m_uploadData.Upload;
OnUploadComplete(argsStopped);
}
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
streamResponse.Close();
streamRead.Close();
response.Close();
m_uploadData.FileStream.Close();
m_uploadData.Upload.UploadInfo.StatusCode = response.StatusCode;
if (response.StatusCode == HttpStatusCode.NoContent)
{
m_uploadData.Upload.UploadInfo.Exception = null;
}
else
{
m_uploadData.Upload.UploadInfo.Exception = new Exception(responseString);
}
var args = new UploadEventArgs();
args.Upload = m_uploadData.Upload;
args.Progress = 100;
OnUploadComplete(args);
}
catch (Exception ex)
{
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = ex;
var args = new UploadEventArgs();
args.Upload = m_uploadData.Upload;
OnUploadComplete(args);
}
}
private string GetParamsString(Dictionary<string, string> parameters)
{
bool needsCLRF = false;
string result = "";
foreach (var param in parameters)
{
// Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
// Skip it on the first parameter, add it to subsequent parameters.
if (needsCLRF)
result += "\r\n";
needsCLRF = true;
string prm = string.Format("--{0}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Disposition: form-data; name={1}\r\n\r\n{2}",
boundarystr,
param.Key,
param.Value);
result += prm;
}
// Add the end of the request. Start with a newline
string footer = "\r\n--" + boundarystr + "\r\n";
result += footer;
return result;
}
protected virtual void OnUploadComplete(UploadEventArgs e)
{
if (UploadCompleted != null)
UploadCompleted(this, e);
}
protected virtual void OnProgressChanged(UploadEventArgs e)
{
if (ProgressChanged != null)
ProgressChanged(this, e);
}
public void Stop()
{
m_isStopped = true;
}
}
}
I have hosted a Windows Web API using a basic authentication header with username and password.
I'm trying to create a login form that takes a username and password and sends back a token.
so i have the following code.
I'm using a Attributed method
public class BasicAuthenticationAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
private IPromiseRepository promiseRepository;
public BasicAuthenticationAttribute()
{
this.promiseRepository = new EFPromiseRepository(new PropellorContext());
//repository = promiseRepository;
}
public BasicAuthenticationAttribute(IPromiseRepository promiseRepository, INewsFeedRepository newsfeedRepository)
{
this.promiseRepository = promiseRepository;
}
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
}
else
{
string authToken = actionContext.Request.Headers.Authorization.Parameter;
string decodedToken = authToken;
// Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
string username = decodedToken.Substring(0, decodedToken.IndexOf(":"));
string password = decodedToken.Substring(decodedToken.IndexOf("^")+1);
string APIToken = decodedToken.Substring(decodedToken.IndexOf("="));
APIToken = APIToken.Replace("=", string.Empty);
password = password.Replace("=", string.Empty);
if (!string.IsNullOrEmpty(APIToken))
{
password = password.Replace(APIToken, string.Empty);
}
if (username != null && password != null)
{
try
{
var user = promiseRepository.GetUserByName(username);
var salt = user.PasswordSalt;
System.Security.Cryptography.SHA512Managed HashTool = new System.Security.Cryptography.SHA512Managed();
Byte[] PasswordAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(password, salt));
Byte[] EncryptedBytes = HashTool.ComputeHash(PasswordAsByte);
HashTool.Clear();
var hashedpass = Convert.ToBase64String(EncryptedBytes);
if (hashedpass == user.Password)
{
if (string.IsNullOrEmpty(user.APIToken))
{
String guid = System.Guid.NewGuid().ToString();
user.APIToken = guid;
promiseRepository.UpdateUser(user);
promiseRepository.Save();
}
if (user != null)
{
user = promiseRepository.GetUserByUserID(user.UserID);
HttpContext.Current.User = new GenericPrincipal(new ApiIdentity(user), new string[] { });
base.OnActionExecuting(actionContext);
}
}
if (APIToken != null)
{
if (user.APIToken == APIToken)
{
var userbytoken = promiseRepository.GetUserByAPIToken(APIToken);
HttpContext.Current.User = new GenericPrincipal(new ApiIdentity(userbytoken), new string[] { });
base.OnActionExecuting(actionContext);
}
}
}
catch (Exception)
{
{
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
base.OnActionExecuting(actionContext);
}
throw;
}
}
}
}
}
This works with Fiddler when the correct credentials are passed
I'm attempting to produce the same authentication in my windows phone application.
Passes a username and password into the basic authentication http header.
However I'm not sure how to do this after a large amount of diggging on the internet alot of the exmaples are windows phone 7 and certain methods don't exist anymore.
This is the code i have arrived at.
private void Login1_Click(object sender, RoutedEventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:5650/api/start");
NetworkCredential credentials = new NetworkCredential(userName.Text + ":^",password.Text + "=");
request.Credentials = credentials;
request.BeginGetResponse(new AsyncCallback(GetSomeResponse), request);
Hopefully someone can guide me into the right direction.
it should be simple in principle :(
Here is a sample using HttpClient:
public static async Task<String> Login(string username, string password)
{
HttpClient Client = new HttpClient();
Client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(StringToAscii(string.Format("{0}:{1}", username, password))));
var response = await Client.GetAsync(new Uri(new Uri("http://yourdomain.com"), "/login"));
var status= await response.Content.ReadAsAsync<String>();
return status;
}
And of course you can find the ToBase64String function on the internet. The tricky part here is the Authorization header.
namespace GoogleVoiceCall
{
class Program
{
private const string LOGIN_URL = "https://www.google.com/accounts/ServiceLoginAuth?service=grandcentral";
private const string GOOGLE_VOICE_HOME_URL = "https://www.google.com/voice";
private const string CALL_URL = "https://www.google.com/voice/call/connect";
private static string m_emailAddress = "your email address";
private static string m_password = "password";
private static string m_gizmoNumber = "your gizmo number";
private static string m_destinationNumber = "your destination number";
static void Main(string[] args)
{
try
{
Console.WriteLine("Attempting Google Voice Call");
CookieContainer cookies = new CookieContainer();
// First send a login request to get the necessary cookies.
string loginData = "Email=" + Uri.EscapeDataString(m_emailAddress)
+ "&Passwd=" + Uri.EscapeDataString(m_password);
HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create(LOGIN_URL);
loginRequest.CookieContainer = cookies;
loginRequest.AllowAutoRedirect = true;
loginRequest.Method = "POST";
loginRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
loginRequest.ContentLength = loginData.Length;
loginRequest.GetRequestStream().Write(Encoding.UTF8.GetBytes(loginData), 0, loginData.Length);
HttpWebResponse loginResponse = (HttpWebResponse)loginRequest.GetResponse();
if (loginResponse.StatusCode != HttpStatusCode.OK)
{
throw new ApplicationException("Login failed.");
}
else
{
Console.WriteLine("Login request was successful.");
}
// Second send a request to the Google Voice home page to get a string key needed when placing a callback.
HttpWebRequest keyRequest = (HttpWebRequest)WebRequest.Create(GOOGLE_VOICE_HOME_URL);
keyRequest.CookieContainer = cookies;
HttpWebResponse keyResponse = (HttpWebResponse)keyRequest.GetResponse();
if (keyResponse.StatusCode != HttpStatusCode.OK)
{
throw new ApplicationException("_rnr_se key request failed.");
}
else
{
Console.WriteLine("Key request was successful.");
}
StreamReader reader = new StreamReader(keyResponse.GetResponseStream());
string keyResponseHTML = reader.ReadToEnd();
Match rnrMatch = Regex.Match(keyResponseHTML, #"name=""_rnr_se"".*?value=""(?<rnrvalue>.*?)""");
if (!rnrMatch.Success)
{
throw new ApplicationException("_rnr_se key was not found on your Google Voice home page.");
}
string rnr = rnrMatch.Result("${rnrvalue}");
Console.WriteLine("_rnr_se key=" + rnr);
// Thirdly (and lastly) submit the request to initiate the callback.
string callData = "outgoingNumber=" + Uri.EscapeDataString(m_destinationNumber) +
"&forwardingNumber=" + Uri.EscapeDataString(m_gizmoNumber) +
"&subscriberNumber=undefined&remember=0&_rnr_se=" + Uri.EscapeDataString(rnr);
HttpWebRequest callRequest = (HttpWebRequest)WebRequest.Create(CALL_URL);
callRequest.CookieContainer = cookies;
callRequest.Method = "POST";
callRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
callRequest.ContentLength = callData.Length;
callRequest.GetRequestStream().Write(Encoding.UTF8.GetBytes(callData), 0, callData.Length);
HttpWebResponse callResponse = (HttpWebResponse)callRequest.GetResponse();
if (callResponse.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine("Call request failed.");
}
else
{
Console.WriteLine("Call request was successful.");
}
}
catch (Exception excp)
{
Console.WriteLine("Exception Main. " + excp.Message);
}
finally
{
Console.WriteLine("finished, press any key to exit...");
Console.ReadLine();
}
}
}
}
I have used the above codes for make a call like Googl voice call using Google voicall service, but i am getting an error. error is
_rnr_se key was not found
pelase tell here what are this
m_gizmoNumber and _rnr_se key
add this line before login request :
m_cookies.Add(new Uri(PRE_LOGIN_URL), galxResponse.Cookies);
see here .