Remote Controlling the Android App from Web Application (ASP.Net) - android

I would like to start/stop the video recording automatically by sending notification from Web Server (Web Application) to Android App. What would be best approach?
I have following approaches in my mind:
Opening Web sockets using Signal R Approach.
SMS Messaging (App will have SMS receiver event, start/stop recording based on messages).

using FCM you send notification on Android App from .net Application:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void Uploadfirebasedata(string firebaseid, string emailid,string Operation)
{
int ret = 0;
string suc = "success";
// XmlDocument xmlupdatedoc = new XmlDocument();
SqlParameter[] param =
{
new SqlParameter("#firebaseid", DbType.String),
new SqlParameter("#emailid", DbType.String),
new SqlParameter("#Operation", DbType.String),
};
param[0].Value = firebaseid;
param[1].Value = emailid;
param[2].Value = Operation;
string SERVER_API_KEY = "YOUR SERVER API KEY";
var SENDER_ID = "YOUR SENDER ID";
var value = "Hi this is from HRM Team";
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}", 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=" +firebaseid + "";
//Console.WriteLine(postData);
//Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentType = "application/json";
tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
var data = new
{
to = firebaseid,
notification = new
{
body = value,
title = "HRM",
icon = "myicon"
}
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
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;
ret = objdata.ExecuteNonQuery("SP_TestWebServiceOperation", param);
if (ret == 1)
{
HttpContext.Current.Response.Write(new JavaScriptSerializer().Serialize(suc + sResponseFromServer));
// xmlupdatedoc.LoadXml("<root><item>Successful</item></root>");
}
else
{
//xmlupdatedoc.LoadXml("<root><item>Unsuccessful</item></root>");
}
}
first you have register your app on to firebase console.
get token from android app using webservice

Related

fcm push notification to mobile with topic messaging using C#

We have an important requirement to push notification to more than 50000 mobile users (Android & IOS). We were implemented this by Topic Messaging. We created batch for every 998 users, and then push to the fcm using topic. But the delivery of push notification is inaccurate. Sometime, some devices get the notification message and some times, no devices. We were use only two topics, one for Android and other for IOS. Sending multiple batches(each batch contains 998 tokens) to the Same topic. Can you please share whats the issue behind this, or please share how to achieve the above scenario.
Batch Push
public string pushBatchbasedonTopic(string Topic, List<string> RegisterIds)
{
_basemobile.WriteToLog("\n Log pushBatchbasedonTopic: ","");
string topic = Topic;
string str = null;
try
{
string senderId = WebConfigurationManager.AppSettings["FCM_SENDER_ID"].ToString();
string applicationkey = WebConfigurationManager.AppSettings["FCM_KEY"].ToString();
WebRequest tRequest = WebRequest.Create("https://iid.googleapis.com/iid/v1:batchAdd");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
tRequest.Timeout = 600000;
var dataser = new
{
to = topic,
registration_tokens = RegisterIds.ToArray()
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(dataser);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationkey));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
tRequest.ContentLength = byteArray.Length;
_basemobile.WriteToLog("\n Log tRequest: ", tRequest.ToString());
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();
str = sResponseFromServer;
_basemobile.WriteToLog("\n Log sResponseFromServer: ", sResponseFromServer);
}
}
}
}
_basemobile.WriteToLog("\n Log TopicCreation: " + str, "");
return str;
}
catch (Exception ex)
{
str = ex.Message;
_basemobile.WriteToLog("\n Log topic creation error: " + ex.Message, "");
_basemobile.WriteToLog("\n Stack Trace topic creation: " + ex.StackTrace, "");
_basemobile.WriteToLog("\n InnerException topic creation: " + ex.InnerException, "");
return str;
}
}
FCM Push
public string pushusingFCMforBatchAndroidBasedOnOneTopic(string Id, string Condition, string Message, string Type, string count)
{
_basemobile.WriteToLog("\n Log pushusingFCMforBatchAndroidBasedOnOneTopic: ", "");
string setcondition = Condition;
//string deviceId = DeviceToken;
string str = null;
try
{
string senderId = WebConfigurationManager.AppSettings["FCM_SENDER_ID"].ToString();
string applicationkey = WebConfigurationManager.AppSettings["FCM_KEY"].ToString();
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
tRequest.Timeout = 600000;
var dataser = new
{
//to = deviceId,
condition = setcondition,
data = new
{
Notification_Id = Id,
msg_type = Type,
Count = count,
sound = "Enabled",
body = Message,
badge = count
}
// count = 0,
//type = Type
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(dataser);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationkey));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
tRequest.ContentLength = byteArray.Length;
_basemobile.WriteToLog("\n Log tRequest: ", tRequest.ToString());
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();
str = sResponseFromServer;
_basemobile.WriteToLog("\n Log sResponseFromServer: ", sResponseFromServer);
}
}
}
}
_basemobile.WriteToLog("\n Log pushfcmandroid: " + str, "");
return str;
}
catch (Exception ex)
{
str = ex.Message;
_basemobile.WriteToLog("\n Log errorios: " + ex.Message, "");
_basemobile.WriteToLog("\n Stack Traceios: " + ex.StackTrace, "");
_basemobile.WriteToLog("\n Inner Exceptionios: " + ex.InnerException, "");
return str;
}
}

Azure http-put UnityWebRequest on android

I'm trying to upload a video to a private Azure blob. The UnityWebRequest works perfectly on PC, but once it's built on an Android device it keeps returning a 403 error.
For debugging I tried to use the normal HttpWebRequest on the android device, with the same settings, which works fine. It's not an option to switch over to HttpWebRequest.
I'm wondering whether the HttpWebRequest has some default options that the UnityWebRequest doesn't, or if perhaps anyone knows of other issues?
HttpWebRequest: Works on both devices
I can provide code if necessary.
[Update]
public IEnumerator PutBlob(string filePath, string blockBlobReference)
{
String httpMethod = "PUT";
Byte[] blobContent = File.ReadAllBytes(filePath);
Int32 blobLength = blobContent.Length;
const String blobType = "BlockBlob";
String urlPath = String.Format("{0}/{1}", AzureStorageConstants.container, blockBlobReference);
String msVersion = "2009-09-19";
//String msVersion = "2015-02-21";
String dateInRfc1123Format = DateTime.UtcNow.AddHours(1).ToString("R", CultureInfo.InvariantCulture);
String canonicalizedHeaders = String.Format("x-ms-blob-type:{0}\nx-ms-date:{1}\nx-ms-version:{2}", blobType, dateInRfc1123Format, msVersion);
String canonicalizedResource = String.Format("/{0}/{1}", AzureStorageConstants.Account, urlPath);
String stringToSign = String.Format("{0}\n\n\n{1}\n\n\n\n\n\n\n\n\n{2}\n{3}", httpMethod, blobLength, canonicalizedHeaders, canonicalizedResource);
String authorizationHeader = CreateAuthorizationHeader(stringToSign);
Uri uri = new Uri(AzureStorageConstants.BlobEndPoint + urlPath);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = httpMethod;
request.Headers.Add("x-ms-blob-type", blobType);
request.Headers.Add("x-ms-date", dateInRfc1123Format);
request.Headers.Add("x-ms-version", msVersion);
request.Headers.Add("Authorization", authorizationHeader);
request.ContentLength = blobLength;
ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(blobContent, 0, blobLength);
yield return requestStream;
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
String ETag = response.Headers["ETag"];
}
}
UnityWebRequest: Works on computer, but not on android
public IEnumerator PutBlob(string filePath, string blockBlobReference)
{
String httpMethod = "PUT";
Byte[] blobContent = File.ReadAllBytes(filePath);
Int32 blobLength = blobContent.Length;
const String blobType = "BlockBlob";
String urlPath = String.Format("{0}/{1}", AzureStorageConstants.container, blockBlobReference);
String msVersion = "2009-09-19";
//String msVersion = "2015-02-21";
String dateInRfc1123Format = DateTime.UtcNow.AddHours(1).ToString("R", CultureInfo.InvariantCulture);
String canonicalizedHeaders = String.Format("x-ms-blob-type:{0}\nx-ms-date:{1}\nx-ms-version:{2}", blobType, dateInRfc1123Format, msVersion);
String canonicalizedResource = String.Format("/{0}/{1}", AzureStorageConstants.Account, urlPath);
String stringToSign = String.Format("{0}\n\n\n{1}\n\n\n\n\n\n\n\n\n{2}\n{3}", httpMethod, blobLength, canonicalizedHeaders, canonicalizedResource);
String authorizationHeader = CreateAuthorizationHeader(stringToSign);
Uri uri = new Uri(AzureStorageConstants.BlobEndPoint + urlPath);
ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback;
using (UnityWebRequest webRequest = new UnityWebRequest())
{
webRequest.SetRequestHeader("x-ms-blob-type", blobType);
webRequest.SetRequestHeader("x-ms-date", dateInRfc1123Format);
webRequest.SetRequestHeader("x-ms-version", msVersion);
webRequest.SetRequestHeader("Authorization", authorizationHeader);
UploadHandler uploadHandler = new UploadHandlerRaw(blobContent);
webRequest.uploadHandler = uploadHandler;
uploadHandler.contentType =
webRequest.url = uri.ToString();
webRequest.method = httpMethod;
webRequest.Send();
while (!webRequest.isDone)
{
ProgressBar = webRequest.uploadProgress;
yield return null;
}
}
}

Android to WCF: Streaming multi part image and Json string

Android to WCF: Streaming multi part image and Json string
I want to create a WCF-RESTful web service method,in which i need to upload an image(multipart-form data) along with some other information (in JSON format). This web service will be accessed by android and iPhone application to send Image and json information as
I want WCF Server Side and Android Code, Help me
I'm trying to upload an image and a text to a wcf service. I create a service to save upload images:
Rest Client Code
protected void Button2_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
MemoryStream mStream = new MemoryStream();
Bitmap bmpPostedImage = new Bitmap(FileUpload1.PostedFile.InputStream);
bmpPostedImage.Save(mStream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imageArray = mStream.ToArray();
mStream.Close();
VehicleCheckListTransaction objAttachmentRequestDto = new VehicleCheckListTransaction();
objAttachmentRequestDto.VehicleCheckListTransactionID = 0;
objAttachmentRequestDto.VehicleCheckListID = 2;
objAttachmentRequestDto.TTID = 10;
objAttachmentRequestDto.UserID = 226;
objAttachmentRequestDto.UserTypeID = 4;
objAttachmentRequestDto.ValidTill = "215-05-10";
objAttachmentRequestDto.CurrentDate = "215-07-22";
objAttachmentRequestDto.CurrentStatus = "Yes";
objAttachmentRequestDto.CreatedBy= 226;
objAttachmentRequestDto.ModifiedBy = 226;
objAttachmentRequestDto.CreatedDate = string.Empty;
objAttachmentRequestDto.ModifiedDate = string.Empty;
objAttachmentRequestDto.Notes = "Some Text";
objAttachmentRequestDto.IsActive = true;
objAttachmentRequestDto.FileName = "";
objAttachmentRequestDto.FilePath = "";
objAttachmentRequestDto.VerifiedBy = 226;
var serializer = new DataContractJsonSerializer(typeof(VehicleCheckListTransaction));
var ms = new MemoryStream();
serializer.WriteObject(ms, objAttachmentRequestDto);
ms.Position = 0;
var reader = new StreamReader(ms);
string requestBody = reader.ReadToEnd();
var client = new RestClient();
client.BaseUrl = new Uri("http://localhost:49188/WDS_SERVICE.svc/");
var request = new RestRequest(Method.POST) { DateFormat = DataFormat.Json.ToString(), Resource = "vehiclechecklisttransaction/Add" };
if (requestBody != null)
request.AddParameter("VehicleCheckListTransaction", requestBody);
request.AddFile("file1", imageArray, "NEVER.jpg");
var response = client.Execute(request);
}
}
WCF Service Code
public string UploadPhoto(Stream request)
{
//Read in our Stream into a string...
StreamReader reader = new StreamReader(request);
string JSONdata = reader.ReadToEnd();
// ..then convert the string into a single "wsCustomer" record.
JavaScriptSerializer jss = new JavaScriptSerializer();
Checklist Checklist = jss.Deserialize<Checklist>(JSONdata);
try
{
FileStream targetStream = null;
Stream sourceStream = Checklist.fileContents;
String guid = Guid.NewGuid().ToString();
//get photofolder path
string photofolderName = "Trip\\Android";
string filename = guid + ".JPEG";
string uriPath = "file:\\C:\\inetpub\\wwwroot\\WDS\\Media\\" + photofolderName + "\\" + filename;
string photopath = new Uri(uriPath).LocalPath;
using (targetStream = new FileStream(photopath, FileMode.Create, FileAccess.Write, FileShare.None))
{
//read from the input stream in 6K chunks
//and save to output stream
const int bufferLen = 65000;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
{
targetStream.Write(buffer, 0, count);
}
targetStream.Close();
sourceStream.Close();
}
db.Checklists.Add(Checklist);
db.SaveChanges();
return filename + "_" + Checklist.ChecklistID;
}
catch (Exception ex)
{
throw new FaultException(ex.Message);
}
}

failed to using google GCM in android and .NET

I try to use GCM in my asp.net and android project.
it takes about 3days and nothing change.
what's wrong with my codes?
I'm really confused...
android side: onCreate
static final String GOOGLE_SENDER_ID = "tokyo-hghgf93712";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final String regIde = GCMRegistrar.getRegistrationId(this);
if (regIde.equals("")) {
GCMRegistrar.register(this, GOOGLE_SENDER_ID);
Log.v(regIde, "Done!");
} else {
Log.v(regIde, "Already registered");
}
.....
asp.net many of my function
function 1:
public void SendCommandToPhone(String sCommand)
{
String DeviceID = ";
// DeviceID = "THE DEVICE ID YOU ARE SENDING TO";
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/x-www-form-urlencoded";
tRequest.Headers.Add(string.Format("Authorization: key={0}", "tokyo-hghgf93712"));
String collaspeKey = Guid.NewGuid().ToString("n");
//String postData=string.Format("registration_id={0}&data.payload={1}&collapse_key={2}", DeviceID, "Pickup Message", collaspeKey);
String postData = string.Format("registration_id={0}&data.payload={1}&collapse_key={2}", DeviceID, sCommand, collaspeKey);
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();
}
function 2:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
string BrowserAPIKey = "AIzaSygfdgdfgdfgfdgdfpjxgcw";
string message = "monaaaaaaa";
string tickerText = "test";
string contentTitle = "title";
string postData = "{ \"registration_ids\": [ \"" + tbRegistrationID.Text + "\" ], \"data\": {\"tickerText\":\"" + tickerText + "\", \"contentTitle\":\"" + contentTitle + "\", \"message\": \"" + message + "\"}}";
string response = SendGCMNotification(BrowserAPIKey, postData);
litResult.Text = response;
}
}
/// <summary>
/// Send a Google Cloud Message. Uses the GCM service and your provided api key.
/// </summary>
/// <param name="apiKey"></param>
/// <param name="postData"></param>
/// <param name="postDataContentType"></param>
/// <returns>The response string from the google servers</returns>
private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")
{
// from here:
// http://stackoverflow.com/questions/11431261/unauthorized-when-calling-google-gcm
//
// original:
// http://www.codeproject.com/Articles/339162/Android-push-notification-implementation-using-ASP
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
//
// MESSAGE CONTENT
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
//
// CREATE REQUEST
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
Request.Method = "POST";
Request.KeepAlive = false;
Request.ContentType = postDataContentType;
Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
Request.ContentLength = byteArray.Length;
// Request.Headers.Add(string.Format("Sender: id={0}", "5637737476457"));
// Request.Headers.Add(string.Format("Authorization: key={0}", "5637737476457"));
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//
// SEND MESSAGE
try
{
WebResponse Response = Request.GetResponse();
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
var text = "Unauthorized - need new token";
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
var text = "Response from web service isn't OK";
}
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadToEnd();
Reader.Close();
return responseLine;
}
catch (Exception e)
{
}
return "error";
}
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
}
function 3:
public void SendNotification(string data)
{
string RegId =
";
string ApplicationID = "AIzaSygfdgdfgdfgfdgdfpjxgcw";
string SENDER_ID = "5637737476457";
var value = "Lokesh"; //message text box
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}", ApplicationID)); tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
//Data post to the Server
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=" + RegId + "";
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(); //Get response from GCM server
//label_Result.Text = sResponseFromServer; //Assigning GCM response to Label text
tReader.Close(); dataStream.Close();
tResponse.Close();
}

Bad Request sending gcm message

I am trying to send gcm message via C#.
I tried several times, but I get http:400-Bad request while trying to send it in json method.
When I try to send it in text, I can't read it (rtl language) - that's why I am trying JSON.
Anyone knows what the problem?
Thanks!
private static string SendNotificationJson2(string id, string msg)
{
var AuthString = "AIzaSyDAtmaqSdutBQemqmd4dQgf33B_6ssbvXA";
var RegistrationID = id;
var Message = msg;
//-- Create GCM request insted of C2DM Web Request Object --//
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
Request.Method = "POST";
Request.KeepAlive = false;
//-- Create Query String --//
Dictionary<String, String> dict = new Dictionary<string, string>();
dict.Add("registration_ids", RegistrationID);
dict.Add("data", Message);
dict.Add("collapse_key", "1");
string postData = GetPostStringFrom(dict);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
Request.ContentType = "application/json";
Request.ContentLength = byteArray.Length;
Request.Headers.Add("Authorization", "key=" + AuthString);
//-- Delegate Modeling to Validate Server Certificate --//
ServicePointManager.ServerCertificateValidationCallback += delegate(
object
sender,
System.Security.Cryptography.X509Certificates.X509Certificate
pCertificate,
System.Security.Cryptography.X509Certificates.X509Chain pChain,
System.Net.Security.SslPolicyErrors pSSLPolicyErrors)
{
return true;
};
//-- Create Stream to Write Byte Array --//
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//-- Post a Message --//
WebResponse Response = Request.GetResponse();
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
return "Unauthorized - need new token";
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
return "Response from web service isn't OK";
//Console.WriteLine("Response from web service not OK :");
//Console.WriteLine(((HttpWebResponse)Response).StatusDescription);
}
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadLine();
Reader.Close();
return "ok";
}
private static string GetPostStringFrom(Dictionary<string,string> postFieldNameValue)
{
// return Newtonsoft.Json.JsonConvert.SerializeObject(postFieldNameValue);
return "\"data\": {\"Message\": \"" + postFieldNameValue["data"] + "\"},\"registration_ids\":[\"" + postFieldNameValue["registration_ids"] + "\"]}";
}</code>
You forgot first bracket in Json data
use
return "{\"data\": {\"Message\": \"" + postFieldNameValue["data"] + "\"},\"registration_ids\":[\"" + postFieldNameValue["registration_ids"] + "\"]}";
instead of
return "\"data\": {\"Message\": \"" + postFieldNameValue["data"] + "\"},\"registration_ids\":[\"" + postFieldNameValue["registration_ids"] + "\"]}";
Your registration ID needs to be a JSON array so use a list instead of a single string.

Categories

Resources