Error:MissingRegistration in GCM with asp.net - c#

I have following code which give "Error:MissingRegistration" response from GCM server.
public void SendPushNotification()
{
string stringregIds = null;
List<string> regIDs = _db.Directories.Where(i => i.GCM != null && i.GCM != "").Select(i => i.GCM).ToList();
//Here I add the registrationID that I used in Method #1 to regIDs
stringregIds = string.Join("\",\"", regIDs);
//To Join the values (if ever there are more than 1) with quotes and commas for the Json format below
try
{
string GoogleAppID = "AIzaSyA2Wkdnp__rBokCmyloMFfENchJQb59tX8";
var SENDER_ID = "925760665756";
var value = "Hello";
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
Request.ContentType = "application/json";
tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
string postData = "{\"collapse_key\":\"score_update\",\"time_to_live\":108,\"delay_while_idle\":true,\"data\": { \"message\" : " + "\"" + value + "\",\"time\": " + "\"" + System.DateTime.Now.ToString() + "\"},\"registration_ids\":[\"" + stringregIds + "\"]}";
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();
TempData["msg1"] = "<script>alert('" + sResponseFromServer + "');</script>";
HttpWebResponse httpResponse = (HttpWebResponse)tResponse;
string statusCode = httpResponse.StatusCode.ToString();
tReader.Close();
dataStream.Close();
tResponse.Close();
}
catch (Exception ex)
{
}
}
But exact string returned by 'postData' posted by Postman or Fiddler gives positive response and notification arrived at device.
What I'm missing in my code please help me.
The postData returns this value which successfully posted by Postman And Fiddler
{"collapse_key":"score_update","time_to_live":108,"delay_while_idle":true,"data": { "message" : "Hello","time": "5/13/2016 5:50:59 PM"},"registration_ids":["cXMf6hkYIrw:APA91bGr-8y2Gy-qzNJ3zjrlf8t-4m9uDib9P0j8GW87bH5jq891-x_7P0qqItzlc_HXh11Arg76lCOcjXPrU9LAgtYLwllH2ySxA0ADSfiz3qPolajjvI3d3zE6Rh77dwRqXn3NnbAm"]}

The problem in your code is in ContentType
Instead of using this:-
Request.ContentType = "application/json";
Use
tRequest.ContentType = "application/json";
It will work

Try This:-
private string SendGCMNotification()
{
try
{
string message = "some test message";
//string tickerText = "example test GCM";
string contentTitle = "content title GCM";
string registration_id = "cXMf6hkYIrw:APA91bGr-8y2Gy-qzNJ3zjrlf8t-4m9uDib9P0j8GW87bH5jq891-x_7P0qqItzlc_HX‌​h11Arg76lCOcjXPrU9LAgtYLwllH2ySxA0ADSfiz3qPolajjvI3d3zE6Rh77dwRqXn3NnbAm";
string postData =
"{ \"registration_ids\": [ \"" + registration_id + "\" ], " +
"\"data\": {\"contentTitle\":\"" + contentTitle + "\", " +
"\"message\": \"" + message + "\"}}";
string GoogleAppID = "AIzaSyA2Wkdnp__rBokCmyloMFfENchJQb59tX8";
WebRequest wRequest;
wRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
wRequest.Method = "POST";
wRequest.ContentType = " application/json;charset=UTF-8";
wRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
var bytes = Encoding.UTF8.GetBytes(postData);
wRequest.ContentLength = bytes.Length;
var stream = wRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
var wResponse = wRequest.GetResponse();
stream = wResponse.GetResponseStream();
var reader = new StreamReader(stream);
var response = reader.ReadToEnd();
var httpResponse = (HttpWebResponse)wResponse;
var status = httpResponse.StatusCode.ToString();
reader.Close();
stream.Close();
wResponse.Close();
//TODO check status
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return "sent";
}

Related

Basic Authentication with multiple request header in HttpwebRequest in c#. Getting error 401 unauthorized

Getting 401 unauthorized error on calling external API from a console application.
through hhtpwebrequest class. Below is my code... requestBody gives me Json data to post
Please suggest to me how to do authentication.
public string InvokeRestService()
{
var serviceUrl = "http://xrmd0/api/v1.0/student/specialized/feed";
var reqData = _service.Retrieve("entityname",
new Guid("guid"), new ColumnSet("requestdata"));
var requestBody = reqData.Attributes["requestdata"].ToString();
string prefix = #"abc""";
string userName = prefix + "xyz";
string password = "pwdqawe";
try
{
var request = (HttpWebRequest)WebRequest.Create(new Uri(serviceUrl));
request.Method = "POST";
request.ContentType = "application/json";
request.Accept = "application/json";
//request.Headers["authorization"] = "Basic" + Convert.ToBase64String(Encoding.Default.GetBytes(userName + ":" + password));
request.Headers["Authorization"] = "Basic Auth" + Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(userName + ":" + password));
request.Headers["User-Id"] = "userId";
request.Headers["User-Type"] = "usertype";
if (!string.IsNullOrEmpty(requestBody))
{
byte[] data = Encoding.UTF8.GetBytes(requestBody);
var requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
}
var response = (HttpWebResponse)request.GetResponse();
var responseStream = response.GetResponseStream();
var responseStreamReader = new StreamReader(responseStream, Encoding.UTF8);
var responseString = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
return responseString;
}
catch (Exception ex)
{
}
}

How to implement FCM in ASP.Net C#?

I am using GCM for notifications on Android with c#, but now I want to change GCM to FCM.
What do I have to change for that? Or how can I implement FCM in C#? Any help is appreciated. I am currently using this code for FCM, I just changed URL but it's not working.
try {
msg = message;
var applicationID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var SENDER_ID = "xxxxxxxxxxx";
WebRequest tRequest;
//tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/x-www-form-urlencoded";
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
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=" + message + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + notificationtoken + "";
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();
notification = sResponseFromServer;
tReader.Close();
dataStream.Close();
tResponse.Close();
return sResponseFromServer;
}
catch (Exception ex)
{
notification.Status = false;
notification = "ERROR DESCRIPTION : " + ex.Message;
}
Try this hope this help you..........
try
{
var applicationID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var senderId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string deviceId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var data = new
{
to = deviceId,
notification = new
{
body = "This is the message Body",
title = "This is the title of Message",
icon = "myicon"
},
priority = "high"
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
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();
Response.Write(sResponseFromServer);
Label3.Text = sResponseFromServer;
}
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}

Unable to Push notification by using GCM in android and C#

I have register my device in GCM, but my push GCM doesn't work. What is wrong with my code?
asp.net side
protected void Button1_Click(object sender, EventArgs e)
{
send("APA91bHwwSLPkdIfqxW8gsosp1J1zgUUsHsgY1LFxetxig4Abo3MfYg7mdbvU3gqLMN5VhW08HvHKhxsHzRAqbRs7WtE6jAQux77XZpx9_1p20O9LMrzpa9mw_RmXoyfq5bkxsLEHO7n6ZGWHzmfzZxaimp46GwR8g");
}
void send(string regId)
{
try
{
var applicationID = "tokyo-***se-***12";
var SENDER_ID = "8500****7538";
var value = "push 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}", applicationID));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
// string postData = "{ 'registration_id': [ '" + regId + "' ], 'data': {'message': '" + txtMsg.Text + "'}}";
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 + "";
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();
lblStat.Text = sResponseFromServer;
tReader.Close();
dataStream.Close();
tResponse.Close();
}
catch (Exception w)
{
Response.Write(w.Data);
}
}
web.config
<appSettings >
<add key="GOOGLE_API_KEY" value="AIzaSyCuXwVivtKDKBqS2zxGCrD7Cc2Qwpjxgcw"/>
</appSettings>
It looks like you are sending the wrong authorization key here:
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
You will need to change applicationID here to your API key, which you assigned to GOOGLE_API_KEY.
Lastly, you may want to consider hiding your actual API key from this StackOverflow post.

Posting tasks to Asana using API in C#

I'm trying to figure out how to post a new task to a user in asana, but I keep getting the 400 error code. Can anyone tell me what I am doing wrong.
This is what I have so far:
string apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string ID = "xxxxxxxxxxxxx";
string url = #"https://app.asana.com/api/1.0/tasks";
Data dat = new Data();
dat.workspace = ID;
dat.name = "Buy eggs";
dat.notes = "Testing";
string json = JsonConvert.SerializeObject(dat);
string data ="\"data\": " + json;
byte[] bytes = Encoding.UTF8.GetBytes(data);
var req = (HttpWebRequest)WebRequest.Create(url);
Console.WriteLine(bytes.ToString());
req.Method = WebRequestMethods.Http.Post;
req.ContentLength = bytes.Length;
req.ContentType = "application/json";
var authInfo = apiKey + ":";
var encodedAuthInfo = Convert.ToBase64String(
Encoding.Default.GetBytes(authInfo));
req.Headers.Add("Authorization", "Basic " + encodedAuthInfo);
req.ContentLength = bytes.Length;
Stream reqStream = req.GetRequestStream();
reqStream.Write(bytes, 0, bytes.Length);
reqStream.Close();
try
{
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
string res = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.WriteLine(res);
Console.ReadLine();
}
catch (WebException ex)
{
HttpWebResponse response = ((HttpWebResponse)ex.Response);
string e = url + " caused a " + (int)response.StatusCode + " error.\n" + response.StatusDescription;
Console.WriteLine(e);
Console.ReadLine();
}
I put the serial converter, did i do it wrong?
As the first comment points out, you need to serialize the data properly. The final body posted should look something like:
{ "data": { "name": "My Example Task", ... }}
(Except of course with the ... replaced with more fields.)
I have researched a long and found below code useful and working. I can successfully post Task to Asana through my application. I have used Json serializer for dot net. Thanks to Newtonsoft.Json.
string json = null;
byte[] bytes = null;
string url = "https://app.asana.com/api/1.0/tasks";
HttpWebRequest req = default(HttpWebRequest);
Stream reqStream = default(Stream);
string authInfo = null;
Task TaskData = new Task();
try
{
authInfo = apiKey + Convert.ToString(":");
TaskData.workspace = WorkspaceId;
TaskData.name = TaskName;
TaskData.notes = TaskNotes;
json = JsonConvert.SerializeObject(TaskData);
json = json.Insert((json.Length - 1), ",\"projects\":[" + ProjectId + "]");
json = Convert.ToString("{ \"data\":") + json + "}";
bytes = Encoding.UTF8.GetBytes(json);
req = (HttpWebRequest)WebRequest.Create(url);
req.Method = WebRequestMethods.Http.Post;
req.ContentType = "application/json";
req.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)));
req.ContentLength = bytes.Length;
reqStream = req.GetRequestStream();
reqStream.Write(bytes, 0, bytes.Length);
reqStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
string res = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.WriteLine(res);
Console.ReadLine();
string finalString = res.Remove(0, 8);
finalString = finalString.Remove((finalString.Length - 1));
AsanaObjectId newtask = JsonConvert.DeserializeObject<AsanaObjectId>(finalString);
return newtask;
}
catch (WebException ex)
{
HttpWebResponse response = (HttpWebResponse)ex.Response;
string resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
MessageBox.Show(resp);
System.Environment.Exit(0);
}

not getting the SOAP response

My SOAP request works - hits the server and displays my request in the server logs and sends the response but I am unable to read the response with my codes (C# & ASP.NET) below.Am I missing something?
try
{
string url = "http://a.b.c.d/ABC/services/DOMFlightAvailability?wsdl";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version10;
req.Method = "POST";
string request = "<Request>"
+ "<Origin>BOM</Origin>"
+ "<Destination>BLR</Destination>"
+ "<DepartDate>2014-11-15</DepartDate>"
+ "<ReturnDate>2014-11-15</ReturnDate>"
+ "<AdultPax>1</AdultPax>"
+ "<ChildPax>1</ChildPax>"
+ "<InfantPax>1</InfantPax>"
+ "<Currency>INR</Currency>"
+ "<Clientid>123</Clientid>"
+ "<Clientpassword>123</Clientpassword>"
+ "<Clienttype>123</Clienttype>"
+ "<Preferredclass>E</Preferredclass>"
+ "<mode>ONE</mode>"
+ "<PreferredAirline>AI,G8,IC,6E,9W,S2,IT,9H,I7,SG</PreferredAirline>"
+ "</Request>";
byte[] postBytes = Encoding.ASCII.GetBytes("xmlRequest=" + request + "");
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream resStream = response.GetResponseStream();
var sr = new StreamReader(response.GetResponseStream());
string responseText = sr.ReadToEnd();
Response.Write(responseText);
lblResult.Text = responseText;
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
This is my other way of doing it - hits the server and trasmits the response but I am still unable to get the response data
try
{
DOMFlightAvailabilityPortTypeClient obj = new DOMFlightAvailabilityPortTypeClient();
string req = "<Request>"
+ "<Origin>BOM</Origin>"
+ "<Destination>DEL</Destination>"
+ "<DepartDate>2014-11-20</DepartDate>"
+ "<ReturnDate>2014-12-21</ReturnDate>"
+ "<AdultPax>1</AdultPax>"
+ "<ChildPax>0</ChildPax>"
+ "<InfantPax>0</InfantPax>"
+ "<Currency>INR</Currency>"
+ "<Clientid>123</Clientid>"
+ "<Clientpassword>123</Clientpassword>"
+ "<Clienttype>123</Clienttype>"
+ "<Preferredclass>E</Preferredclass>"
+ "<mode>ONE</mode>"
+ "<PreferredAirline>AI,G8,IC,6E,9W,S2,IT,9H,I7,SG</PreferredAirline>"
+ "</Request>";
string str = obj.getAvailability(req);
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
DataSet ds = new DataSet();
ds.ReadXml(new XmlTextReader(new StringReader(str)));
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}

Categories