Sending Push Notification on Android Device using Firebase (FCM) - c#

I am trying to send push notification on android device with FCM in C#.Net, but I am getting "InvalidRegistration" error message.
I have used the same from Postman and R-Client as well, but still getting same error.
public String SendNotificationFromFirebaseCloud()
{
string DeviceToken = "RegToken";
string YOUR_FIREBASE_SERVER_KEY = "ServerKey";
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.Headers.Add(string.Format("Sender: id={0}", "MySenderId"));
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"to\":\"" + DeviceToken + "\",\"data\":{\"message\": \"Welcome\"}}";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
{"multicast_id":8671409506357877791,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

"invalid registration" indicates that the device token is incorrect, does not point to an existing device.
Mind that this does not mean a device that's turned off, it means that no device (currently) uses that token at all.
In other words it's an indication of a bad recipient address, effectively the equivalent of an HTTP 404 error.

Related

Error while trying to Create New Product Listing in Shopify using HTTPWebRequest in C#

Here is my code below. Getting the token from shopify works fine. However while creating a new product it keeps giving me an error. I've tried everything possible and it still does not work. Any advice would be appreciated.
Here's how I call the CreateNewProduct method passing the access token from shopify and the shopname with the products endpoint.
CreateNewProduct(accessTokenDTO.access_token, "https://{myshopname}.myshopify.com/admin/api/2020-10/products.json");
Here's the method below.
public static void CreateNewProduct(string token, string Url)
{
Uri shopUri = new Uri(Url);
HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create(shopUri);
GETRequest.ContentType = "application/json";
GETRequest.Headers.Add("X-Shopify-Access-Token", token);
GETRequest.PreAuthenticate = true;
GETRequest.Method = "PUT";
using (var streamWriter = new StreamWriter(GETRequest.GetRequestStream()))
{
string json = "{\"product\": { \"title\": \"Burton Custom Freestyle 151\", \"body_html\": \"<strong>Good snowboard!</strong>\", \"vendor\": \"Burton\", \"product_type\": \"Snowboard\", \"tags\": [ \"Barnes & Noble\", \"John's Fav\", \"\\Big Air\\]}";
streamWriter.Write(json);
streamWriter.Flush();
}
HttpWebResponse GETResponse = (HttpWebResponse)GETRequest.GetResponse();
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(GETResponse.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
Debug.WriteLine("Response Text: " + responseText);
}
GETResponse.Close();
}
400 BadRequest normally refers to the body you are sending with your request is not valid according to the api.
Wheni look at your string that is supposed to be a json, it shows invalid data at the end.
[ \"Barnes & Noble\", \"John's Fav\", \"\\Big Air\\]}";
You are missing closing quotes after Big Air. Also, not sure if those backslash are supposed to be there around Big Air but definitely the missing closing quotes would seem to be the issue
There was an issue with the json not being formatted correctly and method was a PUT instead of POST. See working code below.
public static void CreateNewProduct(string token, string Url)
{
Uri shopUri = new Uri(Url);
HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create(shopUri);
GETRequest.ContentType = "application/json";
GETRequest.Headers.Add("X-Shopify-Access-Token", token);
GETRequest.PreAuthenticate = true;
GETRequest.Method = "POST";
using (var streamWriter = new StreamWriter(GETRequest.GetRequestStream()))
{
string json = "{\"product\": { \"title\": \"Burton Custom Freestyle 151\", \"body_html\": \"<strong>Good snowboard!</strong>\", \"vendor\": \"Burton\", \"product_type\": \"Snowboard\"} }";
streamWriter.Write(json);
streamWriter.Flush();
}
HttpWebResponse GETResponse = (HttpWebResponse)GETRequest.GetResponse();
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(GETResponse.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
Debug.WriteLine("Response Text: " + responseText);
}
GETResponse.Close();
}

POST JSON Data to web API in SSIS Script task from SQL

I have been searching for an answer to this question, but I keep coming up short so hopefully I can find an answer. Admittedly I am not the best C# programmer and this is born out of necessity and not having a resource to help develop this for me, so I have jumped in feet first.
I have some code that I have successfully posted JSON data to the API IF I hard code the JSON string, but I would like to set the results from a SQL query as an OBJ and then serialize them using NEWTONSOFT.JSON to pass to the API in place of the hard coded data.
public void Main()
{
string url = Dts.Variables["$Package::url"].Value.ToString();
string user = Dts.Variables["$Package::user"].Value.ToString();
string pwd = Dts.Variables["$Package::pwd"].GetSensitiveValue().ToString();
string result = Dts.Variables["User::JSON"].Value.ToString();
var JsonResult = JsonConvert.SerializeObject(result);
var request = (HttpWebRequest)WebRequest.Create(url);
string authHeader = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(user + ":" + pwd));
request.Headers.Add("Authorization", "Basic" + " " + authHeader);
request.ContentType = "application/json";
request.Accept = "application/json";
request.Method = "POST";
request.Headers.Add("Cookie: freedomIdentifyKey=XX");
result.ToString();
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(JsonResult);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result2 = streamReader.ReadToEnd();
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
I keep getting Error: 0x1 at Script Task: Exception has been thrown by the target of an invocation.
Any thoughts on how I could resolve this?
You don't need to use a StreamWriter.
string url = Dts.Variables["$Package::url"].Value.ToString();
string user = Dts.Variables["$Package::user"].Value.ToString();
string pwd = Dts.Variables["$Package::pwd"].GetSensitiveValue().ToString();
string result = Dts.Variables["User::JSON"].Value.ToString();
var JsonResult = JsonConvert.SerializeObject(result);
var request = (HttpWebRequest)WebRequest.Create(url);
string authHeader = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(user + ":" + pwd));
request.Headers.Add("Authorization", "Basic" + " " + authHeader);
request.ContentType = "application/json";
request.Accept = "application/json";
request.Method = "POST";
request.Headers.Add("Cookie: freedomIdentifyKey=XX");
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(JsonResult);
using (var dataStream = response.GetResponseStream())
{
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
}
}
And if you want to use HttpClient instead:
string url = Dts.Variables["$Package::url"].Value.ToString();
string user = Dts.Variables["$Package::user"].Value.ToString();
string pwd = Dts.Variables["$Package::pwd"].GetSensitiveValue().ToString();
string result = Dts.Variables["User::JSON"].Value.ToString();
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
var client = new HttpClient();
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
var response = await client.PostAsync(url, result);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
}
catch(HttpRequestException e)
{
// do something
}
Not tested
I was able to get this sorted out. The issue wasn't with the code, but rather with the Newtonsoft.JSON package. It was failing before it even got to the code and I was trying to run it as a SQL 2016 target. When I switched back to a 2019 project it ran fine. To get it to run as a 2016, I installed NEWTONSOFT.JSON using the GACUTIL and it runs great now.
I did make a change and used an SQL query in the code instead of using an execute SQL task and then passing it to a variable.

PHP webpage shows empty string after passing Json through c# RESI API

I have already asked this question but need further help.
c# is not sending json request to PHP
I am trying to send data from c# to PHP webpage using the JSON & REST API HTTP request.
On PHP page I see "String (0)"
c# Code
user user = new user();
{
user.firstname = "aaaa";
user.secondname = "aaaaaaaaaaa";
user.email = "aaa";
user.phonenumber = "aaa";
};
string json = JsonConvert.SerializeObject(user);
HttpWebRequest request = WebRequest.Create("https://scs.agsigns.co.uk/test.php") as HttpWebRequest;
request.ContentType = "application/json";
//request.Accept = "application/json, text/javascript, */*";
request.Method = "POST";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(json);
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream stream = response.GetResponseStream();
string json1 = "";
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
json1 += reader.ReadLine();
}
}
DisplayAlert("Alert", json1, "OK");
PHP
$content = file_get_contents("php://input");
var_dump($content);
In c# I get this alert
c# display alert message
In the PHP webpage, I see following
PHP page shows string(0)
What I want to get data which app sendand save into MySql.
EDIT
I have ammended the PHP file code to save data in MySQL.
I am getting error
Notice: Trying to get property 'name' of non-object in C:\inetpub\scs\test.php on line 16
This is my PHP code.
//Receive the RAW post data.
$content = file_get_contents("php://input");
$obj = json_encode($content);
$insert_stmt = $mysqli->prepare("INSERT INTO test (name,address) VALUES (?,?)");
$name =$obj->{'name'};
$address = $obj->{'address'};
$insert_stmt->bind_param("ss", $name, $address);
//Execute the statement
$insert_stmt->execute();
You should use HttpClient instead of HttpWebRequest
Your request would look like this with HttpClient
public async void SendUserDataToServer()
{
user user = new user();
{
user.firstname = "aaaa";
user.secondname = "aaaaaaaaaaa";
user.email = "aaa";
user.phonenumber = "aaa";
};
string json = JsonConvert.SerializeObject(user);
using (var client = new HttpClient())
{
var response = await client.PostAsync(
"https://scs.agsigns.co.uk/test.php",
new StringContent(json, Encoding.UTF8, "application/json"));
}
DisplayAlert("Alert", json, "OK");
}
Reference: this

Firebase cloud messaging in C#

I am trying to send push notifications from server in C#, i am using the correct registration token and API key but still getting the following response.
{"multicast_id":7864311304033595507,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
I am following this url to implement this solution Send push to Android by C# using FCM (Firebase Cloud Messaging)
Currently i am trying to send notification to a single device but also want to send to multiple device at once, I used to : "/topics/all" as given in the url but it doesn't work. What should I do if I have to send notification to multiple device at once?
Here is my code
try
{
string applicationID = "SERVER_KEY ";
string senderId = "SENDER_ID";
string deviceId = "ba92be2da78e7285";
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var data = new
{
//to = deviceId,
to = deviceId,
notification = new
{
body = "Bring your existing apps and games to the Windows Store with the Desktop Bridge",
title = "Bridge",
sound = "Enabled"
}
};
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();
string str = sResponseFromServer;
}
}
}
}
}
catch (Exception ex)
{
string str = ex.Message;
}
My problem got resolved. I was using device id which is different then registration token id. So I have to use registration token id returned by FirebaseInstanceId.getInstance().getToken() method. Rest of the code is same what I posted in question.

Authorize.Net Creating error creating a new WebHook

I'm a C# developer I need to use webhooks to get some stuff after the gethostpage with redirect.
Everything it's fine if I use GET ( get events, get my webhooks ), but when I'm going to create a new webhook I get a "The remote server returned an error: (400) Bad Request." for sure it's a stupid thing but I'm stuck.
Any tips?
The request
byte[] encoded = System.Text.Encoding.Default.GetBytes(apiLogin + ":" + transactionKey);
string base64 = System.Convert.ToBase64String(encoded);
var isPost = !string.IsNullOrWhiteSpace(json);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = isPost ? "POST" : "GET";
httpWebRequest.Headers.Add("Authorization", "Basic " + base64);
httpWebRequest.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
if (isPost)
{
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
}
}
string result = null;
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
return result;
}
return result;
I'm trying the JSON sample from documentation sample
Found, it is need to create a signature in merchant panel before use "post" webhooks, "get" works also without doing it

Categories

Resources