C# Error In My Code Source (using System.Net.Http) - c#

Langage : C# /
Codded Using : Visual Studio /
Using The System.Net.Http.dll
Hello , Please help Me I have 4 error in my code source project created in C# here is all error :
(I am a beginner) but if you can post the code cleaned fixed I thank you very much
Error 1
Error 1 (Code)
Error 2
Error 2 (Code)
Error 3
Error 3 (Code)
Error 4
Error 4 (Code)
using System;
using System.ComponentModel;
using System.Drawing;
using System.Net;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows.Forms;
namespace CheckerProject
{
public partial class Checker
{
public Checker()
{
InitializeComponent();
}
private async void Check()
{
string text = this.textBox1.Text;
using (HttpClientHandler httpClientHandler = new HttpClientHandler
{
AutomaticDecompression = (DecompressionMethods.GZip | DecompressionMethods.Deflate)
})
{
using (HttpClient httpClient = new HttpClient(httpClientHandler))
{
TaskAwaiter<HttpResponseMessage> taskAwaiter = httpClient.PostAsync("https:\\API.com", new StringContent("{\"onlineId\":\"" + text + "\",\"reserveIfAvailable\":false}".ToString(), Encoding.UTF8, "application/json")).GetAwaiter();
if (!taskAwaiter.IsCompleted)
{
await taskAwaiter;
TaskAwaiter<HttpResponseMessage> taskAwaiter2;
taskAwaiter = taskAwaiter2;
taskAwaiter2 = default(TaskAwaiter<HttpResponseMessage>);
}
HttpResponseMessage result = taskAwaiter.GetResult();
taskAwaiter = default(TaskAwaiter<HttpResponseMessage>);
HttpResponseMessage httpResponseMessage = result;
HttpResponseMessage httpResponseMessage2 = httpResponseMessage;
httpResponseMessage = null;
TaskAwaiter<string> taskAwaiter3 = httpResponseMessage2.Content.ReadAsStringAsync().GetAwaiter();
if (!taskAwaiter3.IsCompleted)
{
await taskAwaiter3;
TaskAwaiter<string> taskAwaiter4;
taskAwaiter3 = taskAwaiter4;
taskAwaiter4 = default(TaskAwaiter<string>);
}
string result2 = taskAwaiter3.GetResult();
taskAwaiter3 = default(TaskAwaiter<string>);
string text2 = result2;
string text3 = text2;
text2 = null;
if (httpResponseMessage2.StatusCode.ToString() == "429")
{
//Function
}
if (httpResponseMessage2.StatusCode != HttpStatusCode.BadRequest)
{
if (httpResponseMessage2.StatusCode == HttpStatusCode.Created)
{
//Function
}
else
{
//Function
}
}
else
{
//Function
if (text3.Contains("Online id already exists"))
{
//Function
}
if (text3.Contains("Improper"))
{
//Function
}
}
httpResponseMessage2 = null;
text3 = null;
}
HttpClient httpClient = null;
}
HttpClientHandler httpClientHandler = null;
}
}
}

I will answer the first two errors (they are the same problem).
You should remove the following 2 lines:
HttpClient httpClient = null;
HttpClientHandler httpClientHandler = null;
What you do here is you declare 2 NEW variables and assign the value 'null' to both of them.
What you meant to do is propably to assign 'null' to the existing variables. However that's not needed, since they are declared inside a 'using' block, which will automatically call the 'Dispose' method.

Related

Step Over throws exception, but Step Into not Unity

I am making a unity game and have one strange situation, which I will try to explain.
Here is my UserCreator class in which I want to return nativeCountry from another class (MySQLCountryManager):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class UserCreator : MonoBehaviour
{
public static PersonModel CreateUser(PersonModel model)
{
CountryModel nativeCountry = new CountryModel();
nativeCountry = MySQLCountryManager.GetCountryByName(model.NativeCountry);
<some other code here....>
}
}
And here is MySQLCountryManager class with GetCountryByName method:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
public class MySQLCountryManager : MonoBehaviour
{
public static CountryModel GetCountryByName(string countryName)
{
CountryModel country = new CountryModel();
WWWForm form = new WWWForm();
form.AddField("CountryName", countryName);
UnityWebRequestAsyncOperation getCountryByName = new UnityWebRequestAsyncOperation();
getCountryByName = UnityWebRequest.Post(WebReguests.getCountryByName, form).SendWebRequest();
List<string> results = new List<string>();
if (getCountryByName.webRequest.isNetworkError || getCountryByName.webRequest.isHttpError)
{
Debug.LogError(getCountryByName.webRequest.error);
}
else
{
var data = getCountryByName.webRequest.downloadHandler.text;
string[] result = data.Split(',');
for (int i = 0; i < result.Length; i++)
{
results.Add(result[i]);
}
int id;
bool idOk;
idOk = int.TryParse(results[0], out id );
if (idOk)
{
country.id = id;
}
country.CountryName = results[1];
byte[] flagBytes = Convert.FromBase64String(results[2]);
country.Flag = flagBytes;
byte[] shapeBytes = Convert.FromBase64String(results[3]);
country.Shape = shapeBytes;
byte[] woP = Convert.FromBase64String(results[4]);
country.WorldPosition = woP;
byte[] coa = Convert.FromBase64String(results[5]);
country.CoatOfArms = coa;
byte[] dishPicBytes = Convert.FromBase64String(results[6]);
country.DishPic = dishPicBytes;
byte[] curiosityBytes = Convert.FromBase64String(results[7]);
country.CuriosityPic = curiosityBytes;
country.Continent = results[8];
country.Population = results[9];
country.Capital = results[10];
country.Language = results[11];
country.Currency = results[12];
country.Religion = results[13];
country.DishName = results[14];
}
return country;
}
Now, the problem is, when I start debugging project in Visual Studio 2019 if I go Step Into on native country in UserCreator and then Step Into in MySQLCountryManager.GetCountryById, code works fine and returns nativeCountry as I expect. But when I go Step Over nativeCountry, it always throws some exceptions, like 'Index was out of range', 'Input string is not in a correct format' etc. And this is happening for all methods with UnityWebRequest called from UserCreator class.
I tried to google for this but nothing useful was found.
Any idea why this is happening?
tl;dr: Sounds like a race condition to me!
While stepping into the method you most probably give the asynchronous request just enough time to actually finish in the background.
I don't see where you are waiting for the results of the asynchronous download.
See the examples of UnityWebRequest.Post => as with any other asynchronous execution you have to wait until the results are actually back.
Usually you would use a Coroutine with callback like e.g.
public static void GetCountryByNameAsync(MonoBehaviour caller, string countryName, Action<CountryModel> whenDone)
{
caller.StartCoroutine(GetCountryByNameRoutine(countryName, whenDone))
}
private static IEnumerator GetCountryByNameRoutine(string countryName, Action<CountryModel> whenDone)
{
var form = new WWWForm();
form.AddField("CountryName", countryName);
using(var request = UnityWebRequest.Post(WebReguests.getCountryByName, form))
{
// WAIT until the request has either failed or succeeded
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
Debug.LogError(request.error);
yield break;
}
var data = request.downloadHandler.text;
var results = data.Split(',');
var country = new CountryModel();
if (int.TryParse(results[0], out var id))
{
country.id = id;
}
country.CountryName = results[1];
var flagBytes = Convert.FromBase64String(results[2]);
country.Flag = flagBytes;
var shapeBytes = Convert.FromBase64String(results[3]);
country.Shape = shapeBytes;
var woP = Convert.FromBase64String(results[4]);
country.WorldPosition = woP;
var coa = Convert.FromBase64String(results[5]);
country.CoatOfArms = coa;
var dishPicBytes = Convert.FromBase64String(results[6]);
country.DishPic = dishPicBytes;
var curiosityBytes = Convert.FromBase64String(results[7]);
country.CuriosityPic = curiosityBytes;
country.Continent = results[8];
country.Population = results[9];
country.Capital = results[10];
country.Language = results[11];
country.Currency = results[12];
country.Religion = results[13];
country.DishName = results[14];
whenDone?.Invoke(country);
}
}
then later you would rather use it like e.g.
// caller will be whatever script is actually calling this method
// we will take that reference to make it also responsible for executing the according Coroutine
public static void CreateUserAsync(MonoBehaviour caller, PersonModel model, Action<PersonModel> whenDone)
{
MySQLCountryManager.GetCountryByName(caller, model.NativeCountry, nativeCountry =>
{
<some other code here....>
whenDone?.Invoke(theCreatedPersonModel);
});
}
Or if it gets more complex instead of Coroutines you might rather use an async - await approach and pass the final result back into the Unity main thread.

Can't exit function properly

I have a C# unity function and I'm trying to request some json from a webserver but for some reason its not exiting the function where I want it to:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Proyecto26;
using UnityEditor;
using UnityEngine.Networking;
using System.Text;
using TMPro;
using SimpleJSON;
public class APIRequest
{
// string basicRequestPage = "****";
string basicAPI_Key = "****";
// Start is called before the first frame update
string outputs;
public string basicRequest(int requestTyp)
{
auth test1 = new auth();
test1.key = basicAPI_Key;
switch (requestTyp)
{
case 0:
test1.request = "deckList";
break;
case 1:
test1.request = "card";
break;
}
string output = JsonConvert.SerializeObject(test1);
byte[] outputToServer = Encoding.ASCII.GetBytes(output); ;
//Debug.Log(output);
RestClient.Request(new RequestHelper
{
Uri = basicRequestPage,
Method = "POST",
Timeout = 10,
//EnableDebug = true,
ParseResponseBody = false, //Don't encode and parse downloaded data as JSONe
BodyRaw = outputToServer
}).Then(response =>
{
// EditorUtility.DisplayDialog("Status", response.Text, "Ok");
var rest = response.Text;
//Debug.Log(rest);
outputs = rest.ToString();
//EditorUtility.DisplayDialog("Status", outputs, "Ok");
return outputs;
}).Catch(err =>
{
var error = err as RequestException;
EditorUtility.DisplayDialog("Error Response", error.Response + "", "Ok");
}
);
}
}
Link to code because it wouldn't work with the built in code text
It works perfectly fine as a method but keeps complaining that I don't have a valid return from the function. When I try to return the value I get from API, namely the outputs variable, it says it null. I have tried putting it in the function, in a public variable. but to now avail.
Any ideas?
When you're working with promises you need to return a promise from that method too (Promise chaining):
public IPromise<string> basicRequest(int requestTyp)
{
return RestClient.Request(new RequestHelper
{
Uri = basicRequestPage,
Method = "POST",
Timeout = 10,
//EnableDebug = true,
ParseResponseBody = false, //Don't encode and parse downloaded data as JSONe
BodyRaw = outputToServer
}).Then(response => response.Text.ToString());
}
For more details, check the repository of the Promises library used by the RestClient for Unity here.
You have defined an output of type string however you do not return a string at all exits. After the catch you have to return a string either at the end of the method or in the catch. The last line I have added return ""; should solve the problem.
public string basicRequest(int requestTyp)
{
auth test1 = new auth();
test1.key = basicAPI_Key;
switch (requestTyp)
{
case 0:
test1.request = "deckList";
break;
case 1:
test1.request = "card";
break;
}
string output = JsonConvert.SerializeObject(test1);
byte[] outputToServer = Encoding.ASCII.GetBytes(output);
//Debug.Log(output);
RestClient.Request(new RequestHelper
{
Uri = basicRequestPage,
Method = "POST",
Timeout = 10,
//EnableDebug = true,
ParseResponseBody = false, //Don't encode and parse downloaded data as JSONe
BodyRaw = outputToServer
}).Then(response =>
{
// EditorUtility.DisplayDialog("Status", response.Text, "Ok");
var rest = response.Text;
//Debug.Log(rest);
outputs = rest.ToString();
//EditorUtility.DisplayDialog("Status", outputs, "Ok");
return outputs;
}).Catch(err =>
{
var error = err as RequestException;
EditorUtility.DisplayDialog("Error Response", error.Response + "", "Ok");
}
);
return ""; //<----- this here
}

Getting Too Many Request 429 from API when calling it by a button click

researched on this topic and tried to implement different solutions, but I can't solved it.
I have a function plotmyChartAsync() that is getting values from google trends.
Using this function in Console Application works fine and I get my desiriable results.
But when I try to perform this function with a button from a windows form, it always failing. With this " HttpResponseMessage secondResponse = await clientUsed.GetAsync(secondRequestStr);" I always get 429 failure from the API. It means I am sending to many request. How could I avoid this?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Globalization;
using System.Threading;
namespace GoogleTrendsAnalysis
{
public partial class Form1 : Form
{
private SemaphoreSlim _mutex = new SemaphoreSlim(1);
public Form1()
{
InitializeComponent();
}
public async Task plotmyChartAsync()
{
await _mutex.WaitAsync();
try
{
const string searchKeyWord = "bmw";
const string firstTimePeriodString = "2021-01-10T00";
const string secondTimePeriodString = "+2021-01-15T00";
const string httprequestStr = "https://trends.google.de/trends/api/explore?hl=de&tz=-60&req=%7B%22comparisonItem%22:%5B%7B%22keyword%22:%22" + searchKeyWord + "%22,%22geo%22:%22DE%22,%22time%22:%22" + firstTimePeriodString + secondTimePeriodString + "%22%7D%5D,%22category%22:0,%22property%22:%22%22%7D&tz=-60";
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = await client.GetAsync(httprequestStr, HttpCompletionOption.ResponseHeadersRead);
Uri uri = new Uri(httprequestStr);
Console.WriteLine(cookies.GetCookies(uri));
IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
Console.WriteLine(responseCookies.First());
string cookieused = responseCookies.First().Name + "=" + responseCookies.First().Value;
client.CancelPendingRequests();
client.Dispose();
handler.Dispose();
using (var clientUsed = new HttpClient())
{
clientUsed.BaseAddress = new Uri("https://trends.google.de/trends/api/");
clientUsed.DefaultRequestHeaders.Add("cookie", cookieused);
Console.WriteLine(clientUsed.DefaultRequestHeaders);
HttpResponseMessage responseUsed = await clientUsed.GetAsync(httprequestStr);
responseUsed.EnsureSuccessStatusCode();
Console.WriteLine(responseUsed);
if (responseUsed.IsSuccessStatusCode)
{
string result = responseUsed.Content.ReadAsStringAsync().Result;
result = result.Substring(4, result.Length - 4);
Console.WriteLine("Result: " + result);
dynamic data = JObject.Parse(result);
Console.WriteLine("TOKEN: " + data.widgets[0]["token"]);
string myToken = data.widgets[0]["token"];
string secondRequestStr = "https://trends.google.de/trends/api/widgetdata/multiline?hl=de&tz=-60&req=%7B%22time%22:%22" + firstTimePeriodString + "%5C%5C:00%5C%5C:00" + secondTimePeriodString + "%5C%5C:00%5C%5C:00%22,%22resolution%22:%22HOUR%22,%22locale%22:%22de%22,%22comparisonItem%22:%5B%7B%22geo%22:%7B%22country%22:%22DE%22%7D,%22complexKeywordsRestriction%22:%7B%22keyword%22:%5B%7B%22type%22:%22BROAD%22,%22value%22:%22" + searchKeyWord + "%22%7D%5D%7D%7D%5D,%22requestOptions%22:%7B%22property%22:%22%22,%22backend%22:%22CM%22,%22category%22:0%7D%7D&token=" + myToken + "&tz=-60";
HttpResponseMessage secondResponse = await clientUsed.GetAsync(secondRequestStr);
secondResponse.EnsureSuccessStatusCode();
string secondResult = secondResponse.Content.ReadAsStringAsync().Result;
List<DateTime> dateTimes = new List<DateTime>();
List<double> values = new List<double>();
secondResult = secondResult.Substring(5, secondResult.Length - 5);
dynamic secondData = JObject.Parse(secondResult);
foreach (var t in secondData)
{
foreach (var x in t)
{
foreach (var s in x.timelineData)
{
bool ifhasDataStr = s.hasData[0];
if (ifhasDataStr == true)
{
string formattedValueStr = s.formattedValue[0];
string formattedTimeStr = s.formattedTime;
double myValue = Convert.ToDouble(formattedValueStr);
formattedTimeStr = formattedTimeStr.Replace(" um ", " ");
DateTime dt = DateTime.ParseExact(formattedTimeStr, "dd.MM.yyyy HH:mm", CultureInfo.InvariantCulture);
dateTimes.Add(dt);
values.Add(myValue);
Console.WriteLine("Die ZEIT: " + formattedTimeStr + " / DER WERT: " + myValue);
}
}
}
}
double numberOfPeriods = dateTimes.Count;
double[] valuesArr = values.ToArray();
double[] xs = new double[valuesArr.Length];
for (int i = 0; i < valuesArr.Length; i++)
{
xs[i] = dateTimes[i].ToOADate();
}
formsPlot1.Reset();
formsPlot1.plt.PlotScatter(xs, valuesArr);
formsPlot1.plt.Ticks(dateTimeX: true);
formsPlot1.Render();
}
}
}
finally
{
_mutex.Release();
}
}
protected async void button1_Click(object sender, EventArgs e)
{
await plotmyChartAsync();
}
}
}
After researching it I found that the problem was the cookie...
Here are the Adjustment that need to be done to the code above...
var baseAddress = new Uri("https://trends.google.de/trends/api/");
using (var firstHandler = new HttpClientHandler() { UseCookies = false })
using (var clientUsed = new HttpClient(firstHandler) { BaseAddress = baseAddress })
{
clientUsed.BaseAddress = baseAddress;
clientUsed.DefaultRequestHeaders.Accept.Clear();
//clientUsed.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//clientUsed.DefaultRequestHeaders.Add("cookie", cookieused);
var firstRequest = new HttpRequestMessage(HttpMethod.Get, httprequestStr);
firstRequest.Headers.Add("cookie", cookieused);
Console.WriteLine(httprequestStr);
HttpResponseMessage responseUsed = await clientUsed.SendAsync(firstRequest);
Console.WriteLine(responseUsed);
string result = responseUsed.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);

Bing Maps REST Services Toolkit - Access Value Outside of Delegate

This sample code for the Bing Maps REST Services Toolkit uses a delegate to get the response and then outputs a message from within the delegate method. However, it does not demonstrate how to access the response from outside of the invocation of GetResponse. I cannot figure out how to return a value from this delegate. In other words, let us say I want to use the value of the longitude variable right before the line Console.ReadLine(); How do I access that variable in that scope?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BingMapsRESTToolkit;
using System.Configuration;
using System.Net;
using System.Runtime.Serialization.Json;
namespace RESTToolkitTestConsoleApp
{
class Program
{
static private string _ApiKey = System.Configuration.ConfigurationManager.AppSettings.Get("BingMapsKey");
static void Main(string[] args)
{
string query = "1 Microsoft Way, Redmond, WA";
Uri geocodeRequest = new Uri(string.Format("http://dev.virtualearth.net/REST/v1/Locations?q={0}&key={1}", query, _ApiKey));
GetResponse(geocodeRequest, (x) =>
{
Console.WriteLine(x.ResourceSets[0].Resources.Length + " result(s) found.");
decimal latitude = (decimal)((Location)x.ResourceSets[0].Resources[0]).Point.Coordinates[0];
decimal longitude = (decimal)((Location)x.ResourceSets[0].Resources[0]).Point.Coordinates[1];
Console.WriteLine("Latitude: " + latitude);
Console.WriteLine("Longitude: " + longitude);
});
Console.ReadLine();
}
private static void GetResponse(Uri uri, Action<Response> callback)
{
WebClient wc = new WebClient();
wc.OpenReadCompleted += (o, a) =>
{
if (callback != null)
{
// Requires a reference to System.Runtime.Serialization
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Response));
callback(ser.ReadObject(a.Result) as Response);
}
};
wc.OpenReadAsync(uri);
}
}
}
For the provided example AutoResetEvent class could be utilized to control the flow, in particular to wait asynchronous WebClient.OpenReadCompleted Event is completed like this:
class Program
{
private static readonly string ApiKey = System.Configuration.ConfigurationManager.AppSettings.Get("BingMapsKey");
private static readonly AutoResetEvent StopWaitHandle = new AutoResetEvent(false);
public static void Main()
{
var query = "1 Microsoft Way, Redmond, WA";
BingMapsRESTToolkit.Location result = null;
Uri geocodeRequest = new Uri(string.Format("http://dev.virtualearth.net/REST/v1/Locations?q={0}&key={1}",
query, ApiKey));
GetResponse(geocodeRequest, (x) =>
{
if (response != null &&
response.ResourceSets != null &&
response.ResourceSets.Length > 0 &&
response.ResourceSets[0].Resources != null &&
response.ResourceSets[0].Resources.Length > 0)
{
result = response.ResourceSets[0].Resources[0] as BingMapsRESTToolkit.Location;
}
});
StopWaitHandle.WaitOne(); //wait for callback
Console.WriteLine(result.Point); //<-access result
Console.ReadLine();
}
private static void GetResponse(Uri uri, Action<Response> callback)
{
var wc = new WebClient();
wc.OpenReadCompleted += (o, a) =>
{
if (callback != null)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Response));
callback(ser.ReadObject(a.Result) as Response);
}
StopWaitHandle.Set(); //signal the wait handle
};
wc.OpenReadAsync(uri);
}
}
Option 2
Or to switch to ServiceManager class that makes it easy when working via asynchronous programming model:
public static void Main()
{
var task = ExecuteQuery("1 Microsoft Way, Redmond, WA");
task.Wait();
Console.WriteLine(task.Result);
Console.ReadLine();
}
where
public static async Task<BingMapsRESTToolkit.Location> ExecuteQuery(string queryText)
{
//Create a request.
var request = new GeocodeRequest()
{
Query = queryText,
MaxResults = 1,
BingMapsKey = ApiKey
};
//Process the request by using the ServiceManager.
var response = await request.Execute();
if (response != null &&
response.ResourceSets != null &&
response.ResourceSets.Length > 0 &&
response.ResourceSets[0].Resources != null &&
response.ResourceSets[0].Resources.Length > 0)
{
return response.ResourceSets[0].Resources[0] as BingMapsRESTToolkit.Location;
}
return null;
}

Exception in release but not debug

I have wrapped the C# FCM AdminSDK in a WCF. When I publish the code to my local using debug everything works as expected. When I publish the code using release I get a "Object reference not set to an instance of an object." when attempting to instantiate the "Message" object. Why does this happen?
The exception happens on the line "var fcmMessage = new Message()"
using FirebaseAdmin;
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;
using ID.Service.PushNotification.Enums;
using ID.Service.PushNotification.Models;
using ID.Service.PushNotification.ServiceHelpers;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Hosting;
namespace ID.Service.PushNotification.Helpers
{
public class FcmHelper
{
readonly static FirebaseApp app = FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile(HostingEnvironment.MapPath(#"~/App_Data/jq4bb-37597f7301.json"))
});
public static void BulkPushNotification(List<EnrolmentModel> enrolments, string message, int messageId, DeepLink path = DeepLink.None)
{
foreach (EnrolmentModel enrolment in enrolments)
{
PushNotification(enrolment, message, messageId, path);
}
}
public static async void PushNotification(EnrolmentModel enrolment, string message, int messageId, DeepLink path = DeepLink.None)
{
try
{
var pathLink = (path != DeepLink.None) ? path.GetPath() : "";
var registrationToken = Encoding.UTF8.GetString(Convert.FromBase64String(enrolment.DeviceToken));
LogHelper.Error("rt: " + registrationToken);
LogHelper.Error("msg: " + message);
LogHelper.Error("pl" + pathLink);
var fcmMessage = new Message()
{
Token = registrationToken,
Android = new AndroidConfig()
{
Notification = new AndroidNotification()
{
Body = message,
Title = "Title",
Sound = "bing"
//ClickAction = "rewards",
//Color = "#CA5151",
//Icon="",
},
Priority = Priority.Normal,
TimeToLive = TimeSpan.FromSeconds(2419200),
//Data = new Dictionary<string, string>()
//{
// { "deepLinkPath", pathLink }
//},
}
};
// Send a message to the device corresponding to the provided
// registration token.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(fcmMessage);
bool successfullySent = false;
if (response.ToLower().Contains("projects/com-app/messages/0:"))
{
successfullySent = true;
}
ResultFeedbackServiceHelper.SaveResultFeedback(
response,
Convert.ToInt32(messageId),
Convert.ToInt32(enrolment.DeviceId),
successfullySent,
new List<string> { enrolment.DeviceToken }
);
}
catch (Exception ex)
{
ResultFeedbackServiceHelper.SaveResultFeedback(
ex.Message,
Convert.ToInt32(messageId),
Convert.ToInt32(enrolment.DeviceId),
false,
new List<string> { enrolment.DeviceToken }
);
LogHelper.Error("Error sending push messages to (fcm) gcn " + ex.ToString());
}
}
}
}
Exception:''2019-03-05 15:09:55,637 Thread:'[13]' Level:'ERROR' Message:'Error sending push messages to (fcm) gcn System.NullReferenceException: Object reference not set to an instance of an object.
at ID.Service.PushNotification.Helpers.FcmHelper.d__2.MoveNext() in D:\BuildAgents\Agent1_work\475\s\PNS\Main\ID.Service.PushNotification\Helpers\FCMHelper.cs:line 49'

Categories