WNS receive JSON data from AmazonSNS - c#

I want to link this question to my previous question
Can't receive any notification from AmazonSNS
that question is actually working now after enabling Toast on .appxmanifest. I get notified when I publish a RAW message type but not JSON which is I actually need. The code is provided there but let me repost it here
d("init AmazonSimpleNotificationServiceClient");
AmazonSimpleNotificationServiceClient sns = new AmazonSimpleNotificationServiceClient("secret", "secret", RegionEndpoint.EUWest1);
d("get notification channel uri");
string channel = string.Empty;
var channelOperation = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
channelOperation.PushNotificationReceived += ChannelOperation_PushNotificationReceived;
d("creating platform endpoint request");
CreatePlatformEndpointRequest epReq = new CreatePlatformEndpointRequest();
epReq.PlatformApplicationArn = "arn:aws:sns:eu-west-1:X413XXXX310X:app/WNS/Device";
d("token: " + channelOperation.Uri.ToString());
epReq.Token = channelOperation.Uri.ToString();
d("creat plateform endpoint");
CreatePlatformEndpointResponse epRes = await sns.CreatePlatformEndpointAsync(epReq);
d("endpoint arn: " + epRes.EndpointArn);
d("subscribe to topic");
SubscribeResponse subsResp = await sns.SubscribeAsync(new SubscribeRequest()
{
TopicArn = "arn:aws:sns:eu-west-1:X413XXXX310X:Topic",
Protocol = "application",
Endpoint = epRes.EndpointArn
});
private void ChannelOperation_PushNotificationReceived(Windows.Networking.PushNotifications.PushNotificationChannel sender, Windows.Networking.PushNotifications.PushNotificationReceivedEventArgs args)
{
Debug.WriteLine("receiving something");
}
I get notified when a publish a RAW message but I need to get notified when I publish in JSON message type. I am not sure why I don't get notified when I use that message type? What else I am missing there?
thanks

Related

How to publish a message to pubsub emulator using C#

I have managed to create a c# tool to push messages to google cloud pubsub. I can't seem to find anywhere how to pubslish the message to the emulator. From what I've read the following should work by passing in the endpoint to the ClientCreationSettings. But I get a bad request response back from the emulator...
public static async Task PublishMessage()
{
var endpoint = new ServiceEndpoint("localhost", 8085);
ClientCreationSettings clientSettings = new ClientCreationSettings(1, null, null, endpoint);
string message = "hello world";
publisherClient = await PublisherClient.CreateAsync(new TopicName("project1", "topic1"), clientSettings);
await publisherClient.PublishAsync(message);
await publisherClient.ShutdownAsync(TimeSpan.FromSeconds(15));
}
Any insight appreciated
For C#, after starting the emulator with gcloud beta emulators pubsub start --project=PUBSUB_PROJECT_ID [options] and setting the environment variable for PUBSUB_EMULATOR_HOST with a handy CLI as shown here, you need to update your application code as shown in this sample:
string emulatorHostAndPort = Environment.GetEnvironmentVariable("PUBSUB_EMULATOR_HOST");
PublisherServiceApiClient client = new PublisherServiceApiClientBuilder
{
Endpoint = emulatorHostAndPort,
ChannelCredentials = ChannelCredentials.Insecure
}.Build();
// do things using client..
You need to send the PubSubMessage object instead of the string.
var message = new PubsubMessage(){ Data = "hello world" };
Your code should be like:
public static async Task PublishMessage()
{
var clientSettings = new PublisherClient.ClientCreationSettings(
null,
PublisherServiceApiSettings.GetDefault(),
ChannelCredentials.Insecure,
"localhost:8085");
var message = new PubsubMessage(){ Data = "hello world" };
publisherClient = await PublisherClient.CreateAsync(new TopicName("project1", "topic1"), clientSettings);
await publisherClient.PublishAsync(message};
await publisherClient.ShutdownAsync(TimeSpan.FromSeconds(15));
}
Source: https://googleapis.github.io/google-cloud-dotnet/docs/Google.Cloud.PubSub.V1/

Sending a message to my bot using the Direct Line v3.0 NuGet package

I am trying to use the Direct Line v3.0 NuGet package to send a message to my bot. I am following the sample on Github, but I'm not getting the behavior I expect.
Here is the sample code:
DirectLineClient client = new DirectLineClient(directLineSecret);
var conversation = await client.Conversations.StartConversationAsync();
while (true)
{
string input = Console.ReadLine().Trim();
if (input.ToLower() == "exit")
{
break;
}
else
{
if (input.Length > 0)
{
Activity userMessage = new Activity
{
From = new ChannelAccount(fromUser),
Text = input,
Type = ActivityTypes.Message
};
await client.Conversations.PostActivityAsync(conversation.ConversationId, userMessage);
}
}
}
And here is my code:
var directLineSecret = "MY_SECRET";
var client = new DirectLineClient(directLineSecret);
var conversation = await client.Conversations.StartConversationAsync();
var testActivity = new Activity
{
From = new ChannelAccount(name: "Proactive-Engine"),
Type = ActivityTypes.Message,
Text = "Hello from the PCE!"
};
var response = await client.Conversations.PostActivityAsync(conversation.ConversationId, testActivity);
I'm logging all the messages my bot receives. I can talk to the bot at its endpoint on Azure using the Bot Emulator, so I have confidence that it's working through the web chat API. However when I run the code above, the bot logs only a conversationUpdate message. The message I send does not get logged, and the value of response is null.
I'm hoping someone can help me find out where I'm going wrong here. Thanks!
Look at how the demo instantiates ChannelAccount:
new ChannelAccount(fromUser)
Then look at the ChannelAccount constructor signature:
public ChannelAccount(string id = null, string name = null)
This means that fromUser is passed as id. But look at how you instantiated ChannelAccount:
new ChannelAccount(name: "Proactive-Engine")
That code doesn't pass an id, it passes a name. So, you can change it like this:
new ChannelAccount("Proactive-Engine")
If your chatbot needs the name, then instantiate like this:
new ChannelAccount("MyChatbotID", "MyChatbotName")

ISSUE With PushSharp Apple Notification From Version 4.0.10.0 To Testflight

I have created a production version .p12 file to send the notifications to iPhone and installed the app using testflight.
When sending notification from my sample console app I am always getting notification sent callback, but no notification is coming to the device.
My Pushsharp version is 4.0.10.0
and code for sending notification looks something like this:
public static void SendAppleNotification()
{
// Configuration (NOTE: .pfx can also be used here)
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, "C:\\Users\\MancMiniUser\\Documents\\visual studio 2013\\Projects\\PushSharpDemo\\PushSharpDemo\\Resources\\P12CertifyPIE.p12", "1234");
// Create a new broker
var apnsBroker = new ApnsServiceBroker(config);
// Wire up events
apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
{
aggregateEx.Handle(ex =>
{
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
var notificationException = (ApnsNotificationException)ex;
// Deal with the failed notification
var apnsNotification = notificationException.Notification;
var statusCode = notificationException.ErrorStatusCode;
Console.WriteLine("Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}");
}
else
{
// Inner exception might hold more useful information like an ApnsConnectionException
Console.WriteLine("Apple Notification Failed for some unknown reason : {ex.InnerException}");
}
// Mark it as handled
return true;
});
};
apnsBroker.OnNotificationSucceeded += (notification) =>
{
Console.WriteLine("Apple Notification Sent!");
};
// Start the broker
apnsBroker.Start();
// Queue a notification to send
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = "3cfcc2ceefe6675d89b063e2e39d03503b3917250e6743d185c755e9e2c3579d",
Payload = JObject.Parse("{\"aps\":{\"alert\":\"Hello from sourabh v.4.0 Tester.\",\"badge\":\"1\"}}")
});
// Stop the broker, wait for it to finish
// This isn't done after every message, but after you're
// done with the broker
apnsBroker.Stop();
}
Can anyone help me with this, why notification is not being received even though the notification sent callback is coming?
You created production certificate then you use as
ApnsConfiguration.ApnsServerEnvironment.Production
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, "C:\Users\MancMiniUser\Documents\visual studio 2013\Projects\PushSharpDemo\PushSharpDemo\Resources\P12CertifyPIE.p12", "1234");

Understanding Toast push notifications and how to display text on them and launch app by pressing on them. Windows Phone 8.1

I am trying to set my application to receive toast push notifications from a server.
Since this server in handled by someone else and he did not request the token to the WSN, I followed an example and I am sending the notifications using a "local web page"
protected void ButtonSendToast_Click(object sender, EventArgs e)
{
try
{
// Get the URI that the Microsoft Push Notification Service returns to the push client when creating a notification channel.
// Normally, a web service would listen for URIs coming from the web client and maintain a list of URIs to send
// notifications out to.
string subscriptionUri = TextBoxUri.Text.ToString();
HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri) as HttpWebRequest;
// Create an HTTPWebRequest that posts the toast notification to the Microsoft Push Notification Service.
// HTTP POST is the only method allowed to send the notification.
sendNotificationRequest.Method = "POST";
// The optional custom header X-MessageID uniquely identifies a notification message.
// If it is present, the same value is returned in the notification response. It must be a string that contains a UUID.
// sendNotificationRequest.Headers.Add("X-MessageID", "<UUID>");
// Create the toast message.
string toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>" + TextBoxTitle.Text.ToString() + "</wp:Text1>" +
"<wp:Text2>" + TextBoxSubTitle.Text.ToString() + "</wp:Text2>" +
"<wp:Param>/Page2.xaml?NavigatedFrom=Toast Notification</wp:Param>" +
"</wp:Toast> " +
"</wp:Notification>";
// Set the notification payload to send.
byte[] notificationMessage = Encoding.Default.GetBytes(toastMessage);
// Set the web request content length.
sendNotificationRequest.Headers.Add("Authorization", String.Format("Bearer {0}", "EgAdAQMAAAAEgAAAC4AATIYp8fmpjFpbdnRTjf2qfP/GqZ8Bbb62bH6N+0MhSztcV/wXfv9aVjiwbVgF5EX0fgBXC6LvJCpl1+ze7ts9h5je4e1QekryEFqfWl36BtTBnmWqBFk0WmwxpdIgGqhVjAtRdnJ3ODnFSBCfd7dq8nFiFTFDxPcTXhdDbu9W3BKMAFoAjAAAAAAAHFAXTMH+bVbB/m1W60gEAA8AMTkwLjE5My42OS4yMzMAAAAAAF0AbXMtYXBwOi8vcy0xLTE1LTItMTU5OTEyNjk1NS0zODAwNDMxNzQ0LTk2OTg4NTEzNi0xNjkxMDU1MjI4LTcwOTcyNTQ0NC00MDYxNzA4MDczLTI0Mzg0MzM1MzQA"));
sendNotificationRequest.ContentLength = notificationMessage.Length;
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers.Add("X-WNS-Type", "wns/toast");
using (Stream requestStream = sendNotificationRequest.GetRequestStream())
{
requestStream.Write(notificationMessage, 0, notificationMessage.Length);
}
// Send the notification and get the response.
HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
string notificationStatus = response.Headers["X-NotificationStatus"];
string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
// Display the response from the Microsoft Push Notification Service.
// Normally, error handling code would be here. In the real world, because data connections are not always available,
// notifications may need to be throttled back if the device cannot be reached.
TextBoxResponse.Text = notificationStatus + " | " + deviceConnectionStatus + " | " + notificationChannelStatus;
}
catch (Exception ex)
{
TextBoxResponse.Text = "Exception caught sending update: " + ex.ToString();
}
}
Now, in my app, I have requested the channel uri and a handler that is called when this channel receives a push
PushNotificationChannel channel = null;
try
{
channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
Debug.WriteLine(channel.Uri);
if (channel.Uri != null)
{
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
localSettings.Values.Remove("PushToken");
localSettings.Values["PushToken"] = channel.Uri;
channel.PushNotificationReceived += channel_PushNotificationReceived;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
async void channel_PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs e)
{
String notificationContent = String.Empty;
notificationContent = e.ToastNotification.Content.GetXml();
Debug.WriteLine(notificationContent);
}
So far, so good: I receive a notification when my app is running and when my app is closed. But it only says "New notification" and nothing happens when I click on it.
I have tried to add an event
e.ToastNotification.Activated += ToastNotification_Activated;
But that does not work and after reading like 20 documents I am very confused about the toast templates and how can I use it to display what I receive from the server
So, what is the real way to do this, to display in the toast some of the data received in the push, and to make the app to "launch / go to a certain page" when the user clicks on it?
For app to go to a certain page
Since Windows 8/8.1, applications has always been expected to handle activations in response to a user clicking on a toast notification from this app – the app should respond by performing navigation and displaying UI specific to the toast. This is accomplished through an activation string that you include in the toast payload, which is then passed to your app as an argument in the activation event.
for Navigation to certain page you need to override OnActivated event in App.Xaml.cs and and handle to string parameter.
For Display toast
If you want to show text in tiles then it try Badge notifications or only data received through toast then handle it on page after navigation from onactivated event. Also Check this link. It shows standard templates for different notifications. Hope it helps.
You'll get a "New notification" when the system doesn't recognize your toast notification payload. That's because you used the MPNS quickstart, not the WNS quickstart and got most of the stuff moved to WNS except for your toast notification format. You want your toast content to look something like this:
<toast launch="">
<visual lang="en-US">
<binding template="ToastImageAndText01">
<image id="1" src="World" />
<text id="1">Hello</text>
</binding>
</visual>
</toast>
Here's the WNS quickstart guide: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868252.aspx
As well as the WNS toast schema: https://msdn.microsoft.com/en-us/library/windows/apps/br230849.aspx

Can't receive any notification from AmazonSNS

I am not sure why I can't receive any notification from AmazonSNS. Am I missing something in my code? I am using the latest version of AWSSDK for Windows Store App by the way.
Here's my code so far.
d("init AmazonSimpleNotificationServiceClient");
AmazonSimpleNotificationServiceClient sns = new AmazonSimpleNotificationServiceClient("secret", "secret", RegionEndpoint.EUWest1);
d("get notification channel uri");
string channel = string.Empty;
var channelOperation = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
channelOperation.PushNotificationReceived += ChannelOperation_PushNotificationReceived;
d("creating platform endpoint request");
CreatePlatformEndpointRequest epReq = new CreatePlatformEndpointRequest();
epReq.PlatformApplicationArn = "arn:aws:sns:eu-west-1:X413XXXX310X:app/WNS/Device";
d("token: " + channelOperation.Uri.ToString());
epReq.Token = channelOperation.Uri.ToString();
d("creat plateform endpoint");
CreatePlatformEndpointResponse epRes = await sns.CreatePlatformEndpointAsync(epReq);
d("endpoint arn: " + epRes.EndpointArn);
d("subscribe to topic");
SubscribeResponse subsResp = await sns.SubscribeAsync(new SubscribeRequest()
{
TopicArn = "arn:aws:sns:eu-west-1:X413XXXX310X:Topic",
Protocol = "application",
Endpoint = epRes.EndpointArn
});
private void ChannelOperation_PushNotificationReceived(Windows.Networking.PushNotifications.PushNotificationChannel sender, Windows.Networking.PushNotifications.PushNotificationReceivedEventArgs args)
{
Debug.WriteLine("receiving something");
}
this is actually working after enabling Toast on .appxmanifest
I get notified everytime I publish a RAW message from Amazon SNS console. I am not receiving a JSON though which I actually need.

Categories

Resources