Can't receive any notification from AmazonSNS - c#

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.

Related

how to send firebase push notifcation to ios app

I want to use firebase to send push notification to ios ,
I implement the frontend part and retrieve the device token correctly..
when I try to send notification from Firebase console recceived the notification successffully on ios app.
I tried sending the from my Dotnet core C# APi but not received the notification on ios.
ANy one please share how to send push notification from C# code to ios using firebase.
Install FirebaseAdmin from https://www.nuget.org/packages/FirebaseAdmin/
more details here C# Send Push Notification Firebase Cloud Messaging
the notification content
FirebaseAdmin.Messaging.Notification notification = new FirebaseAdmin.Messaging.Notification();
notification.Body = Message;
notification.ImageUrl = ImageUrl ;
notification.Title = Title ;
FirebaseAdmin.Messaging.AndroidNotification androidNotification = new FirebaseAdmin.Messaging.AndroidNotification();
androidNotification.Body = Message;
androidNotification.Color = "#2D82FF";
androidNotification.ImageUrl = ImageUrl ;
androidNotification.Title = Title ;
androidNotification.ChannelId = "12";
androidNotification.Icon = "Icon" ;
androidNotification.Sound = "default";
FirebaseAdmin.Messaging.AndroidConfig androidConfig = new FirebaseAdmin.Messaging.AndroidConfig();
androidConfig.CollapseKey = CollapseKey Id;
androidConfig.Priority = FirebaseAdmin.Messaging.Priority.High;
androidConfig.Notification = androidNotification;
androidConfig.TimeToLive = new TimeSpan(24, 0, 0);
var msg = new FirebaseAdmin.Messaging.Message();
msg.Notification = notification;
msg.Android = androidConfig;
msg.Token = LastDeviceFCMToken;
try
{
await FirebaseAdmin.Messaging.FirebaseMessaging.DefaultInstance.SendAsync(msg);
}
catch (Exception e)
{
}
with this declaration of notification, anyway will be your target Android or Ios will revice the notification

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")

android push notification using gcm

I am developing wcf push notification service using google's GCM API. i created a service which sends to all the device which use my application but, i wanted to be specific to some device. i am thinking i have to use the token i get when i register for the GCM service. but i dont know where and how to implment it. most of the online posts are in PHP and i am kind of confused when i see the codes. Any one with C# implmentation advice or in general may be?
here is my code for all the devices:
public bool notify(string sender, string message)
{
var jGcmData = new JObject();
var jData = new JObject();
bool Value;
jData.Add("message", message);
jData.Add("name", sender);
jGcmData.Add("to", "/topics/global");
jGcmData.Add("data", jData);
var url = new Uri("https://gcm-http.googleapis.com/gcm/send");
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation(
"Authorization", "key=" + API_KEY);
Task.WaitAll(client.PostAsync(url,
new StringContent(jGcmData.ToString(), Encoding.Default, "application/json"))
.ContinueWith(response =>
{
Console.WriteLine(response);
Console.WriteLine("Message sent: check the client device notification tray.");
}));
}
Value = true;
}
catch (Exception e)
{
Console.WriteLine("Unable to send GCM message:");
Console.Error.WriteLine(e.StackTrace);
Value = false;
}
return Value;
}
thanks in advance!
1st of all I think you should not reinvent the wheel and include a Push messaging library to do all the redundant work.
I use PushSharp
Then everything is cake.
Declare the following handler class
Using the SendGCMNotification method just throw an object to serialize and a specific user's push messaging id .
public class PushNotificationHandler : IDisposable
{
private static readonly string googleApiKey;
private static PushBroker pushBrokerInstance;
static PushNotificationHandler()
{
googleApiKey = ConfigurationManager.AppSettings["GoogleAPIKey"].ToString();
pushBrokerInstance = new PushBroker();
pushBrokerInstance.RegisterGcmService(new GcmPushChannelSettings(googleApiKey));
}
public static void SendGCMNotification(Notification messageObj, String CloudMessagingId)
{
String Content = Newtonsoft.Json.JsonConvert.SerializeObject(messageObj);
pushBrokerInstance.QueueNotification(new GcmNotification().ForDeviceRegistrationId(CloudMessagingId).WithJson(Content));
}
}

WNS receive JSON data from AmazonSNS

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

Categories

Resources