SNS - JSON message body failed to parse - c#

I am trying to send to mobile devices a remote notification through Amazon SNS. I got a database which i store the JSON (payload) which needs to be given to PublishRequest of the SNS. I serialise the json in code and pass it to the request.
The issue is that SNS fails with an error: "MESSAGE STRUCTURE - JSON MESSAGE BODY FAILED TO PARSE"
As a requirement, the service (which is responsible to communicate with SNS and send the notification) has to retrieve from DB (MySQL) the json.
What I am missing?
The database is MySQL and the service is written in .Net Core
string messageFromDb = JsonConvert.SerializeObject(input.Payload);
var request = new PublishRequest
{
TargetArn = endpoint.EndpointArn,
MessageStructure = "json",
Message = messageFromDb
};
PublishResponse publishResponse = await _client.PublishAsync(request);
JSON from DB:
{"APNS": {"aps": {"alert": "Check out the new!", "sound": "default"}, "category": {"type": "sports"}}}
I tried also this without any luck:
{"default": "something", "APNS": {"aps": {"alert": "Check out the new games!", "sound": "default"}, "game": {"type": "Xbox"}}}

Finally I figured it out, maybe this answer will help someone. The JSON in the DB should be
{"aps": {"alert": "Check out the new!", "sound": "default"}, "category": {"type": "sports"}}
The .Net code should be:
AWSRoot obj = new AWSRoot(input.Payload);
var request = new PublishRequest
{
TargetArn = endpoint.EndpointArn,
MessageStructure = "json",
Message = JsonConvert.SerializeObject(obj)
};
PublishResponse publishResponse = await _client.PublishAsync(request);
AWSRoot is the root object that we create for SNS
public class AWSRoot
{
public string APNS { get; set; }
public AWSRoot(string payload)
{
APNS = payload;
}
}

Related

How to add contact in the list using sendgrid?

I'm trying to add contact in the list so i'm using this link below to Add a Single Recipient to a List :
click here
I have Advanced 100k plan and using full access api key but still getting forbidden error.
Please help me out in this.
My code
string data = #"[
{
'age': 25,
'email': 'example#example.com',
'first_name': '',
'last_name': 'User'
},
{
'age': 25,
'email': 'example2#example.com',
'first_name': 'Example',
'last_name': 'User'
}
]";
var client = new SendGridClient("#################");
var json = JsonConvert.DeserializeObject<Object>(data);
data = json.ToString();
var response = await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "contactdb/recipients", requestBody: data);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();
return response;
You can resolve this by editing your API Keys settings in Send Grid and enabling the permissions for the features you need access to for that API Key.
API Keys settings

UnknownError sending messages to Teams

I'm trying to send a message into a channel inside an organization's Teams.
I have deployed the app successfully, and I get an Authentication token.
When I do as stated here to send messages to a chat, via C# as follows:
_token = await _authenticationHelper.GetAuthenticationToken();
AccessToken = _token;
string teamId = "xxx-xxx-xxx-XX-Xxxxx";
string channelId = "...thread.skype";
var val = await HttpPost($"/teams/{teamId}/channels/{channelId}/messages",
"{ \"body\": { \"contentType\": \"html\", \"content\": \"Hello World\" } }", endpoint: "https://graph.microsoft.com/beta");
get an error from Microsoft Graph Stating:
System.Exception: {
"error": {
"code": "UnknownError",
"message": "",
"innerError": {
"request-id": "44b6397d-aae4-4f60-a2fd-200070c64908",
"date": "2019-04-18T12:30:02"
}
}
}
This error is not descriptive so I don't really know what went wrong.

Web push C# library function

I am currently working on web push notifications and am at the last stage of using the web push libraries to send the notification.
I am using the C# web push library here. However, I do not see a notification when on the page or when not on it.
I am attaching my code below:
I wrote the code in my store subscription method so it could be one of the issues.
[HttpPost]
public void StoreSubscription(string [] publicKey, string [] auth, string notificationEndPoint )
{
var pushEndpoint = notificationEndPoint;
var pushAuth = auth[0].ToString();
var pushP256DH = publicKey[0].ToString();
var subject = "mailTo:hhhhhhh#gmail.com";
var uPublicKey = "yyzzxx";
var privateKey = "xxyyzz";
System.IO.File.WriteAllText(#"\Desktop\Subscription.txt", pushEndpoint);
var subscription = new PushSubscription(pushEndpoint, pushP256DH, pushAuth);
var gcmAPIKey = "AAAA";
var vapidDetails = new VapidDetails(subject, uPublicKey, privateKey);
var webPushClient = new WebPushClient();
try
{
webPushClient.SetGCMAPIKey(gcmAPIKey);
webPushClient.SendNotification(subscription, "payload", gcmAPIKey);
}
catch (WebPushException exception)
{
Console.WriteLine("HTTP status Code:" + exception.StatusCode);
}
}
And my service worker code is as follows for handling the push:
self.addEventListener('push', function (event) {
debugger
var body;
if (event.data) {
body = event.data.text();
} else {
body = 'Push message no payload';
}
var options = {
body: body,/*'This message was generated from a push'*/
icon: '/Images/noun_Pushing_1823359.png',
vibrate: [100, 200, 100, 200, 400],
data: {
dateOfArrival: Date.now(),
primaryKey: '2'
},
actions: [
{
action: 'explore', title: 'Explore this new world',
icon: '/Images/noun_Check Mark_4870.png'
},
{
action: 'close', title: 'Close',
icon: '/Images/noun_Close_887590.png'
},
]
};
event.waitUntil(
self.registration.showNotification('Push Notification', options)
);
});
I have been stuck on this for almost a long time now and very new to promise, service worker and push and notification apis.
the function is getting hit and does not throw any exception. Also, when i put a debugger in the service worker, it does not get hit so apparently the push is not getting handles.I might be completely wrong on this.
I had the same issue. I base 64 encoded my auth and p256dh used to create the subscription.
If there is no exception it could mean the JSON payload is valid JSON but in the wrong format for the service worker. I Changed my payload to a valid JSON object for my service worker (Angular):
{ "notification": {"title": "message title", "body": "message body"} }
Please see docs... https://developer.mozilla.org/en-US/docs/Web/API/Notification/Notification
Sent notification and hit the service worker.
I was using Vapid Details not GCMApiKey.

Updating trigger frequency of Azure Logic App using API

I am trying to update the recurrence frequency and interval of a Logic App using Azure Logic SDK and it is failing with this error message
Microsoft.Rest.Azure.CloudException: The request to patch workflow 'kk-test-logic-app' is not supported.
None of the fields inside the properties object can be patched.
Here is a code snippet showing what I am trying to do.
var workflow = await _client.Value.Workflows.GetAsync(resourceGroupName, workflowName);
dynamic workflowDefinition = workflow.Definition;
workflowDefinition.triggers[triggerName]["recurrence"] = JToken.FromObject(new { frequency = triggerFrequency, interval = triggerInterval });
await _client.Value.Workflows.UpdateAsync(resourceGroupName, workflowName, workflow);
where _client is Lazy<LogicManagementClient>.
Here is the definition of the trigger I am trying to update (got using Fiddler):
"triggers": {
"When_a_new_email_arrives": {
"recurrence": {
"frequency": "Hour",
"interval": 2
},
"splitOn": "#triggerBody()?.value",
"type": "ApiConnection",
"inputs": {
"host": {
"api": {
"runtimeUrl": "https://logic-apis-southindia.azure-apim.net/apim/office365"
},
"connection": {
"name": "#parameters('$connections')['office365']['connectionId']"
}
},
"method": "get",
"path": "/Mail/OnNewEmail",
"queries": {
"folderPath": "Inbox",
"importance": "Any"
}
}
}
}
Note that I am able to successfully retrieve the workflows, workflowRuns, workflowTriggers etc. Only the update operation is failing. Any ideas on how to update properties of workflows using the SDK?
UPDATE:
As pointed out by Amor-MSFT in the comments below, this is a defect and as a workaround, I am currently using CreateOrUpdateAsync instead of UpdateAsync. A new defect has been created in GitHub to get this to the attention of the SDK development team.
The trigger currently executes every 30s checking if a new mail was received from a certain email address and is working well as expected. I'm trying to change the recurrence frequency from 30s to 2hours using the code I provided.
I created a mail trigger and I can reproduce the issue if I use invoke UpdateAsync method. According to the source code of Azure Logic C# SDK, it send a PATCH request which is not supported according the response message. After changed the HTTP method to PUT, I can update the workflow. Here is the sample code which I used to send the PUT request.
string triggerName = "When_a_new_email_arrives";
string resourceGroupName = "my resourcegroup name";
string workflowName = "my-LogicApp";
string subscriptionID = "my-subscriptionID";
var workflow = await _client.Workflows.GetAsync(resourceGroupName, workflowName);
string url = string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Logic/workflows/{2}?api-version=2016-06-01",
subscriptionID, resourceGroupName, workflowName);
HttpClient client = new HttpClient();
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Put, url);
message.Headers.Add("Authorization", "Bearer put your token here");
message.Headers.Add("Accept", "application/json");
message.Headers.Add("Expect", "100-continue");
dynamic workflowDefinition = workflow.Definition;
workflowDefinition.triggers[triggerName]["recurrence"] = JToken.FromObject(new { frequency = "Minute", interval = 20 });
string s = workflow.ToString();
string workflowString = JsonConvert.SerializeObject(workflow, _client.SerializationSettings);
message.Content = new StringContent(workflowString, Encoding.UTF8, "application/json");
await client.SendAsync(message);

Sending raw WNS notifications using message attributes

I am attempting to send a raw notification to WNS by setting message attributes, but it appears that a toast notification is being sent instead.
Here is the C# code I'm using to build the publish request.
var request = new PublishRequest()
{
TopicArn = TOPIC_ARN,
Message = "Test Message",
MessageAttributes = new Dictionary<string, MessageAttributeValue>()
{
{ "AWS.SNS.MOBILE.WNS.Type", new MessageAttributeValue() { StringValue = "wns/raw", DataType = "String" } }
}
};
From what I can tell, I am setting the X-WNS-Type correctly using SNS
Message Attributes, but the notification is still received as a toast on the client. Are there any examples of somebody doing this successfully?
I was able to get it working by using MessageStructure. Setting the value to json and updating Message to have a message specifically for WNS did the trick. My assumption is that the WNS value for MessageAttributes only applies if a message is defined specifically for WNS.
var request = new PublishRequest()
{
TopicArn = TOPIC_ARN,
Message = "{ \"default\": \"default message\", \"WNS\" : \"raw message\"}",
MessageAttributes = new Dictionary<string, MessageAttributeValue>()
{
{ "AWS.SNS.MOBILE.WNS.Type", new MessageAttributeValue() { StringValue = "wns/raw", DataType = "String" } }
},
MessageStructure = "json",
};

Categories