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() +
"®istration_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();
}
Related
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;
}
}
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;
}
}
}
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() + "®istration_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
I need to send an image and text from android to wcf service, tried with http client with multipart but no luck, kindly suggest.
send image using multipartBuilder and send text separately as json via http url connection, the below code for sending image to wcf service is this
Android code
public String postFiless( byte[] imgbyt, String urlString) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
byte[] data = imgbyt;
String fileName = String.format("File_%d.jpg",new Date().getTime());
ByteArrayBody bab = new ByteArrayBody(data, fileName);
builder.addPart("image", bab);
final HttpEntity entity = builder.build();
post.setEntity(entity );
HttpResponse response = client.execute(post);
Log.e("result code", ""+response.getStatusLine().getStatusCode());
return getContent(response);
}
public static String getContent(HttpResponse response) throws IOException {
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String body = "";
String content = "";
while ((body = rd.readLine()) != null)
{
content += body + "\n";
}
return content.trim();
}
WCF CODE TO GET THE IMAGE STREAM SENT FROM ANDROID
Three steps to upload image using Multipart Parser from android to WCF Rest Service
//Step 1
//WCF Rest Interface
// Namespace
using System.IO;
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, UriTemplate = "/UploadImg")]
string UploadImg(Stream fileStream);
Step 2
// WCF Implementation class
// Name spaces
using System.IO;
public string UploadImg(Stream fileStream) {
string strRet = string.Empty;
string strFileName = AppDomain.CurrentDomain.BaseDirectory + "Log\\"; // System.Web.Hosting.HostingEnvironment.MapPath("~/Logs/");
string Path = HttpContext.Current.Server.MapPath("~/Photos");// System.Web.Hosting.HostingEnvironment.MapPath("~/Photos/");// HttpContext.Current.Server.MapPath("~/Photos/")
try {
MultipartParser parser = new MultipartParser(fileStream);
if (parser.Success) {
string fileName = parser.Filename;
string contentType = parser.ContentType;
byte[] fileContent = parser.FileContents;
Encoding encoding = Encoding.UTF8;
FileStream fileToupload = new FileStream(Path + "/" + fileName, FileMode.Create);
fileToupload.Write(fileContent, 0, fileContent.Length);
fileToupload.Close();
fileToupload.Dispose();
fileStream.Close();
strRet= fileName;
} else {
return "Image Not Uploaded";
} }
catch (Exception ex) {
// handle the error
}
return strRet;
}
Step 3
// MultipartParser class
//Namespace
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
public class MultipartParser {
public IDictionary<string, string> Parameters = new Dictionary<string, string>();
public MultipartParser(Stream stream) {
this.Parse(stream, Encoding.UTF8);
}
public MultipartParser(Stream stream, Encoding encoding) {
this.Parse(stream, encoding);
}
public string getcontent(Stream stream, Encoding encoding) {
// Read the stream into a byte array
byte[] data = ToByteArray(stream);
// Copy to a string for header parsing
string content = encoding.GetString(data);
string delimiter = content.Substring(0, content.IndexOf("\r\n"));
string[] sections = content.Split(new string[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in sections) {
Match nameMatch = new Regex(#"(?<=name\=\"")(.*?)(?=\"")").Match(s);
string name = nameMatch.Value.Trim().ToLower();
if (!string.IsNullOrWhiteSpace(name)) {
int startIndex = nameMatch.Index + nameMatch.Length + "\r\n\r\n".Length;
}
}
string strRet = ""; //Parameters["name"];
return strRet;
}
private void Parse(Stream stream, Encoding encoding) {
this.Success = false;
// Read the stream into a byte array
byte[] data = ToByteArray(stream);
// Copy to a string for header parsing
string content = encoding.GetString(data);
// The first line should contain the delimiter
int delimiterEndIndex = content.IndexOf("\r\n");
if (delimiterEndIndex > -1) {
string delimiter = content.Substring(0, content.IndexOf("\r\n"));
// Look for Content-Type
Regex re = new Regex(#"(?<=Content\-Type:)(.*?)(?=\r\n\r\n)");
Match contentTypeMatch = re.Match(content);
// Look for filename
re = new Regex(#"(?<=filename\=\"")(.*?)(?=\"")");
Match filenameMatch = re.Match(content);
//re = new Regex(#"(?<=name\=\"")(.*?)(?=\"")");
//Match nameMatch = re.Match(content);
// Did we find the required values?
if (contentTypeMatch.Success && filenameMatch.Success) {
// Set properties
this.ContentType = contentTypeMatch.Value.Trim();
this.Filename = filenameMatch.Value.Trim();
// Get the start & end indexes of the file contents
int startIndex = contentTypeMatch.Index + contentTypeMatch.Length + "\r\n\r\n".Length;
byte[] delimiterBytes = encoding.GetBytes("\r\n" + delimiter);
int endIndex = IndexOf(data, delimiterBytes, startIndex);
int contentLength = endIndex - startIndex;
// Extract the file contents from the byte array
byte[] fileData = new byte[contentLength];
Buffer.BlockCopy(data, startIndex, fileData, 0, contentLength);
this.FileContents = fileData;
this.Success = true; }
} }
private int IndexOf(byte[] searchWithin, byte[] serachFor, int startIndex) {
int index = 0;
int startPos = Array.IndexOf(searchWithin, serachFor[0], startIndex);
if (startPos != -1) {
while ((startPos + index) < searchWithin.Length) {
if (searchWithin[startPos + index] == serachFor[index]) {
index++;
if (index == serachFor.Length) {
return startPos;
}
} else {
startPos = Array.IndexOf<byte>(searchWithin, serachFor[0], startPos + index);
if (startPos == -1) {
return -1;
}
index = 0;
}
}
}
return -1;
}
private byte[] ToByteArray(Stream stream) {
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream()) {
while (true) {
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
public bool Success {
get;
private set;
}
public string ContentType {
get;
private set;
}
public string Filename {
get;
private set;
}
public byte[] FileContents {
get;
private set;
}
public string Imgname {
get;
private set;
} }
// End of Wcf rest Service Code
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.