Sending notification using firebase Api but not receiving on the browser - c#

I am trying to send notification using firebase api in asp.net core everything is working fine on local pc but on live project the response of the function shows that the notification has been sent properly but i am not receiving any on the browser but the strange part is that when i try to send notification to the same user my retreiving the token saved in the db from firebase console i received it on the browser.
Here is the code.
Everything is working just fine it retrieves the token from db against the username and send notification to the token and result also seems fine.
public async Task<IActionResult> SendNotification(NotificationModel model)
{
try
{
var response = new ResponseModel();
if (string.IsNullOrEmpty(model.ToUsername))
{
response.Message = "an error occurred while processing your request";
response.ResponseStatus = Core.Enums.ResponseStatus.Error;
return BadRequest(response);
}
var tokens = _deviceManager.GetDeviceTokens(model.ToUsername);
if (tokens.Any())
{
var result = await NotificationsManager.SendPushNotifications(model.Message, model.Tittle, tokens);
response.Data = model;
response.Message = "Success";
response.ResponseStatus = Core.Enums.ResponseStatus.Success;
var errorsList = new List<KeyValuePair<string, string>>();
for (int i = 0; i < result.Responses.Count; i++)
{
var item = result.Responses[i];
errorsList.Add(new KeyValuePair<string, string>(i.ToString(), "Success:" + item.IsSuccess + "," + "MessageId:"+ item.MessageId + "," +"Error:"+ item.Exception));
}
response.ErrorsList = errorsList;
return Ok(response);
}
response.Message = "No User found with the given username or the user you are trying to send the notification has not enabled the notification";
response.ResponseStatus = Core.Enums.ResponseStatus.Error;
return BadRequest(response);
}
catch (Exception e)
{
var response = new ResponseModel();
response.Message = "an error occurred while processing your request" + e.Message;
response.ResponseStatus = Core.Enums.ResponseStatus.Error;
return BadRequest(response); throw;
}
}
This is the response i get from swagger api when i call this api:
{
"responseStatus": 200,
"errorsList": [
{
"key": "0",
"value": "Success:True,MessageId:projects/aurora-10684/messages/ff9a5a3f-def7-4120-b23f- c9d871d25172,Error:"
}
],
"metaData": null,
"message": "Success",
"data": {
"message": "string",
"toUsername": "shahreyarbutt",
"tittle": "string"
}
}
i tried everything and everything is wokring on local but on the live project it sends the notification but fails to receive when sending from the swagger using my api but with firebase console it works fine.

Related

runtime.compilerservices.taskawaiter.throwfornonsuccess

I am running .net application which fetches data from SQL database and displays on the form screen.
When I run the application in UAT, it works fine but in PROD, I am getting below exception
Query run fine on database but I am getting this exception.
PricingClinet.cs -
public async Task<SaveResponse> SaveAsync(Sheet sheet)
{
SaveResponse result = null;
try
{
var response = await _client.PostAsJsonAsync("Pricing/Save", sheet);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var jsonResult = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<SaveResponse>(jsonResult);
}
else
{
var errorMessage = string.Format("StatusCode: {0}\r\n{1}", response.StatusCode.ToString(), response.ReasonPhrase);
Logger.LogError(errorMessage);
result = new SaveResponse()
{
Success = false,
ErrorMessage = errorMessage
};
}
}
catch (Exception error)
{
Logger.LogError(error);
result = new SaveResponse()
{
Success = false,
ErrorMessage = ExceptionManager.RenderErrorMessage(error)
};
}
return result;
}
This error is hapenning in PROD only, not in UAT.
This is a timeout in a await _client.PostAsJsonAsync.
You need to confirm that your PROD configuration is correct e.g. points to the correct server.
If your configuration is correct then you need to either increase the timeout
(e.g. _client.Timeout = ...) or make the remote call faster (if it's in your control obviously).

C# Send Push Notification Firebase Cloud Messaging

I'm trying to send a notification to Firebase Messaging according to the https://github.com/Firebase/firebase-admin-dotnet package.
I generated a private key in Firebase and added the project.
To send I am doing it as follows.
[HttpPost]
public async Task<dynamic> PostMensagem()
{
var message = new FirebaseAdmin.Messaging.Message()
{
Data = new Dictionary<string, string>()
{
["FirstName"] = "FirstName",
["LastName"] = "LastName"
},
Notification = new FirebaseAdmin.Messaging.Notification
{
Title = "Message Title",
Body = "Message Body"
},
Android = new FirebaseAdmin.Messaging.AndroidConfig()
{
Priority = Priority.Normal,
TimeToLive = TimeSpan.FromHours(1),
RestrictedPackageName = "com.example.test",
},
Topic = "Topic",
};
var result = await FirebaseMessaging.DefaultInstance.SendAsync(message);
Console.WriteLine(result); //projects/myapp/messages/2492588335721724324
return result;
}
In response, I receive a url something like "//projects/myapp/messages/2492588335721724324" but the notification does not reach the cloud and neither does android.
Am I forgetting something? What do I need to do to get notifications sent from my SDK project to appear in Firebase Cloud Messaging?

Continuous push message giving BadRequest from Azure

My service is register with azzure notification hub. And using my .net server API it push notification to particular device within particular time frame.
Everything goes right except when I try to send multiple push in same code it stuck with "BadRequest" except first one.
Below is the code
public static async void SendAzzurePushNotification()
{
for (int i = 0; i < 10; i++)
{
HttpStatusCode pushNotificationStatus = await CreateAndPushAsync("user_37");
Console.WriteLine(pushNotificationStatus);
}
}
static async Task<HttpStatusCode> CreateAndPushAsync(string tag)
{
HttpStatusCode pushNotificationStatus = HttpStatusCode.NotImplemented;
try
{
HttpResponseMessage response = null;
string uri = "<HUBURI>";
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("SharedAccessSignature", <SASTOKEN>);
client.DefaultRequestHeaders.Add("ServiceBusNotification-Format", "gcm");
client.DefaultRequestHeaders.Add("ServiceBusNotification-Tags", tag);
client.DefaultRequestHeaders.Add("x-ms-version", "2015-01");
response = await client.PostAsync(uri,
new StringContent("{\"data\":{\"message\":\"Notification Hub test notification\"}}", Encoding.UTF8, "application/json"));
pushNotificationStatus = response.StatusCode;
}
catch (Exception ex)
{
throw;
}
return pushNotificationStatus;
}
Above code give me Created status for first time and then BadRequest after that. If same api I call from client like postman. It work fine.
I also tried nuget package from azure notification hub, regarding which code is as below. Which solve my above issue but it won't return me any status code which I can have in my above code for success.
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("<CONNECTIONSTRING>", "<HUB>");
NotificationOutcome outcome = await hub.SendGcmNativeNotificationAsync("{\"data\":{\"message\":\"Notification Hub test notification\"}}", "user_37");
Call send method with your tags and your notification-data
private static readonly string Endpoint = #"Your End Point";
private static readonly string HubName = #"You Hub Name";
private static NotificationHubClient Hub { get { return NotificationHubClient.CreateClientFromConnectionString(Endpoint, HubName); } }
public static async Task Send(string[] tags, object data)
{
try
{
string payload = string.Empty;
string json_gcm = string.Empty;
if (data.GetType() != typeof(string))
{
//If your notification data is of type
payload = JsonConvert.SerializeObject(data);
json_gcm = "{ \"data\" : " + payload + "}";
}
else
{
//If your notification data is simply is in string
payload = Convert.ToString(data);
json_gcm = "{ \"data\" : {\"message\":\"" + payload + "\"}}";
}
// Android
NotificationOutcome gcmOutcome = null;
gcmOutcome = await Hub.SendGcmNativeNotificationAsync(json_gcm, tags);
if (gcmOutcome != null)
{
if (!((gcmOutcome.State == NotificationOutcomeState.Abandoned) || (gcmOutcome.State == NotificationOutcomeState.Unknown)))
{
//Do code when notification successfully send to Android
}
}
}
catch (Exception ex)
{
//Do code when any exception occurred while sending notification
}
}
NotificationOutcomeState: Gives you status code in the form of enum that represent your notification has been successfully sent or not.
You may ignore if-else block as your need.
Try once may it help you

Fire TriggeredSends from ExactTarget's API using HttpClient REST

I've read along the way that Salesforce (I'm extremely new to this 3rd party platform) has a FUEL SDK which one can use instead of the version (using HttpClient -- REST instead of SOAP).
Please correct me if using FUEL SDK is the only way to go about requesting Salesforce's endpoints. Currently I am attempting to hit ExactTargets's API endpoints using HttpClient. These are the tutorials I've been basing my code off of:
https://developer.salesforce.com/docs/atlas.en-us.mc-apis.meta/mc-apis/messageDefinitionSends.htm
https://developer.salesforce.com/docs/atlas.en-us.mc-getting-started.meta/mc-getting-started/get-access-token.htm
Wanted Result:
To be able to request a Triggered Send email based off a template inside of ExactTarget.
Problem:
The Salesforce endpoint continuously returns a 404. I am able to receive the authorization token successfully. The GetAccessToken method is omitted for brevity
https://www.exacttargetapis.com/messaging/v1/messageDefinitionSends/key:MyExternalKey/send
I do not understand why the 2nd POST request to //www.exacttargetapis.com/..... returns a 404 but the authorization works. This leads me to believe that I do not have to use the FUEL SDK to accomplish triggering a welcome email.
Code:
private const string requestTokenUrl = "https://auth.exacttargetapis.com/v1/requestToken";
private const string messagingSendUrl = "https://www.exacttargetapis.com/messaging/v1/messageDefinitionSends";
private string exactTargetClientId = ConfigurationManager.AppSettings["ExactTargetClientId"];
private string exactTargetClientSecret = ConfigurationManager.AppSettings["ExactTargetClientSecret"];
private string TriggerEmail(User model, string dbName)
{
var etExternalKeyAppSetting = ConfigurationManager.AppSettings.AllKeys.FirstOrDefault(x => x.Equals(dbName));
if (etExternalKeyAppSetting != null)
{
string etExternalKey = ConfigurationManager.AppSettings[etExternalKeyAppSetting];
HttpClient client = new HttpClient
{
BaseAddress = new Uri(string.Format(#"{0}/key:{1}/send", messagingSendUrl, etExternalKey)),
DefaultRequestHeaders =
{
Authorization = new AuthenticationHeaderValue("Bearer", this.GetAccessToken())
}
};
try
{
var postData = this.CreateExactTargetPostData(model.Email, etExternalKey);
var response = client.PostAsync(client.BaseAddress
, new StringContent(JsonConvert.SerializeObject(postData).ToString()
, Encoding.UTF8
, "application/json")).Result;
// get triggered email response
if (response.IsSuccessStatusCode)
{
dynamic result = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
}
}
catch (Exception ex)
{
string message = ex.Message;
}
}
return "testing";
}
private object CreateExactTargetPostData(string email, string extKey)
{
var fromData = new
{
Address = ConfigurationManager.AppSettings["AwsSenderEmail"],
Name = "Test"
};
var subscriberAttributes = new { };
var contactAttributes = new
{
SubscriberAttributes = subscriberAttributes
};
var toData = new
{
Address = email,
//SubscriberKey = extKey,
//ContactAttributes = contactAttributes
};
var postData = new
{
From = fromData,
To = toData
};
return postData;
}
I have also tried using Advanced REST Client using the following:
URL:
https://www.exacttargetapis.com/messaging/v1/messageDefinitionSends/key:MyExternalKey/send
POST
Raw Headers:
Content-Type: application/json
Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Raw Payload:
{
"From": {
"Address": "code#exacttarget.com",
"Name": "Code#"
},
"To": {
"Address": "example#example.com",
"SubscriberKey": "example#example.com",
"ContactAttributes": {
"SubscriberAttributes": {
"Region": "West",
"City": "Indianapolis",
"State": "IN"
}
}
},
"OPTIONS": {
"RequestType": "ASYNC"
}
}
Issue was my App in the AppCenter was pointing to the incorrect login for MarketingCloud =(

Google authentication using azure services

I authenticate Google account using azure services in visual studio (c#).
I got access token from Google account.
How can I fetch user information from that access token?
my server side code
var user = User as ServiceUser;
var identities = await user.GetIdentitiesAsync();
var googleCredential = identities[0] as Microsoft.WindowsAzure.Mobile.Service.Security.GoogleCredentials;
var accessToken = googleCredential.AccessToken;
You have to talk directly to the Google API with the customer token to get information about that user.
Here is a link to a blog post: http://blogs.msdn.com/b/carlosfigueira/archive/2012/10/25/getting-user-information-on-azure-mobile-services.aspx
Here is a link to the Google API: https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#windows-phone-81
Here is an example with a Node.js Backend:
function insert(item, user, request) {
item.UserName = "<unknown>"; // default
user.getIdentities({
success: function (identities) {
var req = require('request');
if (identities.google) {
var googleAccessToken = identities.google.accessToken;
var url = 'https://www.googleapis.com/oauth2/v3/userinfo?access_token=' + googleAccessToken;
req(url, function (err, resp, body) {
if (err || resp.statusCode !== 200) {
console.error('Error sending data to Google API: ', err);
request.respond(statusCodes.INTERNAL_SERVER_ERROR, body);
} else {
try {
var userData = JSON.parse(body);
item.UserName = userData.name;
request.execute();
} catch (ex) {
console.error('Error parsing response from Google API: ', ex);
request.respond(statusCodes.INTERNAL_SERVER_ERROR, ex);
}
}
});
} else {
// Insert with default user name
request.execute();
}
}
});
}

Categories