示例#1
0
        public async Task SendAWSNotification(AWSCredentials credentials, string topicArn, string message)
        {
            Console.WriteLine();
            Console.WriteLine("--SENDING-MESSAGE----------------------");
            var client = new AmazonSimpleNotificationServiceClient(credentials.AccessKey, credentials.SecretKey, credentials.Region);

            Console.WriteLine("Pushing message to topic: {0}", topicArn);
            var publishResponse = await client.PublishAsync(topicArn, message);

            Console.WriteLine("Message sent with HttpStatusCode: {0}", publishResponse.HttpStatusCode);
            Console.WriteLine("---------------------------------------");
            Console.WriteLine();
            Console.WriteLine("--SENDING-MESSAGE-USING-REQUEST--------");
            Console.WriteLine("Pushing message to topic: {0} using PublishRequest", topicArn);
            var publishRequest = new PublishRequest();

            publishRequest.Subject  = "Message subject";
            publishRequest.Message  = message;
            publishRequest.TopicArn = topicArn;
            publishResponse         = await client.PublishAsync(publishRequest);

            Console.WriteLine("Message sent with HttpStatusCode: {0}", publishResponse.HttpStatusCode);
            Console.WriteLine("---------------------------------------");
            Console.WriteLine();
            Console.WriteLine("--SENDING-MESSAGE-USING-PHONE-REQUEST--");
            Console.WriteLine("Pushing message to topic: {0} using PublishRequest", topicArn);
            var phonePublishRequest = new PublishRequest();

            phonePublishRequest.Message     = message;
            phonePublishRequest.PhoneNumber = "YOUR-PHONE-NUMBER";
            publishResponse = await client.PublishAsync(phonePublishRequest);

            Console.WriteLine("Message sent with HttpStatusCode: {0}", publishResponse.HttpStatusCode);
            Console.WriteLine("---------------------------------------");
        }
        public void ShouldPublishForEachWeatherEvent()
        {
            // Create mock object response from sampledata.json
            var s3ResponseWithSampleData = new GetObjectResponse
            {
                ResponseStream = File.OpenRead(Path.Combine(TEST_DATA_PATH, "sampledata.json"))
            };

            // Tell fake S3 to return to return the mock object response created above.
            A.CallTo(() =>
                     _fakeS3.GetObjectAsync(A <GetObjectRequest> .That.Matches(x => x.BucketName == _s3GetObjectRequest.BucketName && x.Key == _s3GetObjectRequest.Key), A <CancellationToken> ._))
            .Returns(Task.FromResult(s3ResponseWithSampleData));


            var bulkEventsLambda = new BulkEventsLambda(_fakeS3, _fakeSns, _snsTopic);

            bulkEventsLambda.S3EventHandler(_fakeS3Event);

            // 3 events in sampledata.json => expect 3 sns publish calls.
            A.CallTo(() =>
                     _fakeSns.PublishAsync(_snsTopic, A <string> ._, CancellationToken.None))
            .MustHaveHappened(3, Times.Exactly);


            var expectedMessage = "{\"LocationName\":\"New York, NY\",\"Temperature\":91,\"Timestamp\":1564428897,\"Longitude\":-73.99,\"Latitude\":40.7}";

            A.CallTo(() =>
                     _fakeSns.PublishAsync(_snsTopic, expectedMessage, CancellationToken.None))
            .MustHaveHappenedOnceExactly();
        }
示例#3
0
        public async void SendSMS(string msg)
        {
            AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.USEast1);
            PublishRequest pubRequest = new PublishRequest();

            pubRequest.Message     = msg;
            pubRequest.PhoneNumber = "+919888055959";
            // add optional messageattributes, for example:
            //pubRequest.messageattributes.add("aws.sns.sms.senderid", new messageattributevalue
            //{ stringvalue = "senderid", datatype = "string" });
            PublishResponse pubResponse = await snsClient.PublishAsync(pubRequest);

            Console.WriteLine(pubResponse.MessageId);
            //return msg;

            //var snsClient1 = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.USEast2);

            // Publish a message to an Amazon SNS topic.
            msg = "The object in your watch list has been found in the live stream with ‘90%’ confidence.";
            var topicArn = "arn:aws:sns:us-east-1:735092621658:NotifyMe";

            PublishRequest  publishRequest  = new PublishRequest(topicArn, msg);
            PublishResponse publishResponse = await snsClient.PublishAsync(publishRequest);

            // Print the MessageId of the published message.
            Console.WriteLine("MessageId: " + publishResponse.MessageId);
        }
        public async Task Publish_HasMessageTypeAttributeAndBody()
        {
            //Arrange
            var queueName    = Guid.NewGuid().ToString();
            var topicName    = Guid.NewGuid().ToString();
            var firstMessage = new FirstMessage {
                Value = "value1"
            };
            var secondMessage = new SecondMessage {
                Value = "value2"
            };

            var snsClient = new AmazonSimpleNotificationServiceClient(
                AppConfig.AccessKey,
                AppConfig.SecretKey,
                new AmazonSimpleNotificationServiceConfig {
                ServiceURL = AppConfig.ServiceUrl
            });

            var topicArn  = (await snsClient.CreateTopicAsync(topicName)).TopicArn;
            var sqsClient = new AmazonSQSClient(
                AppConfig.AccessKey,
                AppConfig.SecretKey,
                new AmazonSQSConfig {
                ServiceURL = AppConfig.ServiceUrl
            });
            await sqsClient.CreateQueueAsync(queueName);

            var queueUrl = (await sqsClient.GetQueueUrlAsync(queueName)).QueueUrl;

            await snsClient.SubscribeQueueAsync(topicArn, sqsClient, queueUrl);

            //Act
            await snsClient.PublishAsync(topicArn, firstMessage);

            await snsClient.PublishAsync(topicArn, secondMessage);

            var response = await sqsClient.ReceiveMessageAsync(new ReceiveMessageRequest
            {
                QueueUrl              = queueUrl,
                MaxNumberOfMessages   = 2,
                MessageAttributeNames = new List <string> {
                    "All"
                }
            });

            var messageTypes = response.Messages
                               .Select(message => JsonConvert.DeserializeObject <MessageBody>(message.Body))
                               .Select(body => body.MessageAttributes.Single(pair => pair.Key == "MessageType").Value.Value)
                               .ToList();

            //Assert
            new[] { nameof(FirstMessage), nameof(SecondMessage) }
            .ShouldAllBe(s => messageTypes.Contains(s));
            new [] { firstMessage.Value, secondMessage.Value }
            .ShouldAllBe(s => response.Messages.Any(message => message.Body.Contains(s)));
        }
示例#5
0
        public async Task SendSMSMessage(string message,
                                         string phoneNumber, Dictionary <string, MessageAttributeValue> smsAttributes, ILambdaContext context)
        {
            PublishRequest request = new PublishRequest();

            request.Message           = message;
            request.PhoneNumber       = phoneNumber;
            request.MessageAttributes = smsAttributes;

            await snsClient.PublishAsync(request);
        }
示例#6
0
        public async Task publisasms(string phonenumber)
        {
            string number  = phonenumber;
            string message = "ladki beautiful kar gyi chull";

            string key   = "AKIAX6CXUVKFU3R6RJOH";
            string scret = "gaidXXmW6scTqvPCZUfuouQdpaQizyZqH7sY8FWf";

            var client  = new AmazonSimpleNotificationServiceClient(key, scret, Amazon.RegionEndpoint.APSoutheast1);
            var request = new PublishRequest
            {
                Message     = message,
                PhoneNumber = number,
            };

            request.MessageAttributes["AWS.SNS.SMS.SMSType"] =
                new MessageAttributeValue {
                StringValue = "Transactional", DataType = "String"
            };
            //request.MessageAttributes.Add("aws.sns.sms.smstype".ToUpper(), new MessageAttributeValue { StringValue="transactional" ,DataType= "string"});
            try
            {
                var response = await client.PublishAsync(request);
            }
            catch (Exception ex)
            {
            }
        }
示例#7
0
        /// <summary>
        /// Function to send student email about their next scheduled exam.
        /// </summary>
        /// <param name="state"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public State FunctionHandler(State state, ILambdaContext context)
        {
            var nextExam = state.Exams.LastOrDefault();

            if (nextExam != null)
            {
                var message = $"Dear Student ID {state.StudentId}, you have until {nextExam.ExamDate} to complete you Plagiarism Violation test. Thank you.";
                var subject = $"Exam Notification for {state.StudentId}";

                _client.PublishAsync(new PublishRequest
                {
                    Subject  = subject,
                    Message  = message,
                    TopicArn = _topicArn
                });
            }
            else
            {
                throw new ExamNotFoundException();
            }



            return(state);
        }
示例#8
0
        public async Task NotifySubscribersAboutNewForroLevel(ForroLevel forroLevel)
        {
            var clientSNS = new AmazonSimpleNotificationServiceClient(_awsRegionEndpoint);

            var message = $"The name of new Forró Level is {forroLevel.Name} and ID {forroLevel.ForroLevelId}";

            var publish = new PublishRequest
            {
                TopicArn = _forroLevelSNSTopicArn,
                Subject  = "New Forró Level has been created",
                Message  = message
            };

            _loggerManager.LogInfo($"SNS Topic ARN is {_forroLevelSNSTopicArn}");

            var result = await clientSNS.PublishAsync(publish);

            if (IsSuccessStatusCode(result.HttpStatusCode))
            {
                _loggerManager.LogInfo($"Successfully sent a message to SNS Topic {_forroLevelSNSTopicArn}");
            }
            else
            {
                throw new Exception($"Error trying to publish on SNS topic " +
                                    $"{_forroLevelSNSTopicArn}. HttpStatus returned is {result.HttpStatusCode}");
            }
        }
        /// <summary>
        /// Sends a notification message to the AWS SNS service asynchronously.
        /// </summary>
        /// <param name="msg">Message to send.</param>
        /// <returns>Unique identifier assigned to the message sent.</returns>
        public async Task <string> SendNotificationAsync(string msg)
        {
            var pubRequest = new PublishRequest
            {
                PhoneNumber       = _phoneNumber,
                Message           = msg,
                MessageAttributes =
                {
                    ["AWS.SNS.SMS.SMSType"] =
                        new MessageAttributeValue {
                        StringValue = _smsType, DataType = "String"
                    },
                    ["AWS.SNS.SMS.MaxPrice"] =
                        new MessageAttributeValue {
                        StringValue = _smsMaxPrice, DataType = "Number"
                    }
                }
            };

            if (!_smsSenderId.Equals("default", StringComparison.InvariantCultureIgnoreCase))
            {
                pubRequest.MessageAttributes["AWS.SNS.SMS.SenderID"] =
                    new MessageAttributeValue {
                    StringValue = _smsSenderId, DataType = "String"
                };
            }

            await SetDefaultSmsAttributesAsync().ConfigureAwait(false);

            var response = await _snsClient.PublishAsync(pubRequest);

            return(response.MessageId);
        }
示例#10
0
        /// <summary>
        /// Sends the SMS.
        /// </summary>
        /// <returns>void</returns>
        /// <param name="to">.</param>
        /// <param name="message">The type.</param>
        /// <param name="countryCode">Country Code</param>
        public async Task SendSms(string to, string message, string countryCode = "+91")
        {
            try
            {
                var client = new AmazonSimpleNotificationServiceClient(
                    this.configuration.GetValue <string>("AWSSNS:AccessKey"),
                    this.configuration.GetValue <string>("AWSSNS:Secret"),
                    RegionEndpoint.USEast1);
                PublishRequest publishRequest = new PublishRequest
                {
                    Message     = message,
                    PhoneNumber = countryCode + to
                };
                publishRequest.MessageAttributes["AWS.SNS.SMS.SenderID"] = new MessageAttributeValue {
                    StringValue = "LTD", DataType = "String"
                };
                publishRequest.MessageAttributes["AWS.SNS.SMS.SMSType"] = new MessageAttributeValue {
                    StringValue = "Transactional", DataType = "String"
                };

                var response = await client.PublishAsync(publishRequest);
            }
            catch
            {
            }
        }
示例#11
0
        public async Task SendNotificationAsync(string deviceName, string timestamp)
        {
            var message = $"{deviceName} saw a person @ {timestamp}";
            var result  = await _snsClient.PublishAsync(new PublishRequest(_topicArn, message)).ConfigureAwait(false);

            Console.WriteLine($"Message published with result code: {result.HttpStatusCode}");
        }
示例#12
0
        public PublishResponse SendText(string phone, string message, double MaxPrice = 0.0065, Urgency urgency = Urgency.Promotional, SenderID senderID = null)
        {
            AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient(accessKey, secretKey, Amazon.RegionEndpoint.USEast1);
            PublishRequest pubRequest = new PublishRequest();

            pubRequest.Message     = message;
            pubRequest.PhoneNumber = phone;

            if (senderID != null && senderID.HasValue())
            {
                pubRequest.MessageAttributes["AWS.SNS.SMS.SenderID"] =
                    new MessageAttributeValue {
                    StringValue = senderID.Value, DataType = "String"
                };
            }
            pubRequest.MessageAttributes["AWS.SNS.SMS.MaxPrice"] =
                new MessageAttributeValue {
                StringValue = MaxPrice.ToString(), DataType = "Number"
            };
            pubRequest.MessageAttributes["AWS.SNS.SMS.SMSType"] =
                new MessageAttributeValue {
                StringValue = urgency.ToString(), DataType = "String"
            };
            // add optional MessageAttributes, for example:
            //   pubRequest.MessageAttributes.Add("AWS.SNS.SMS.SenderID", new MessageAttributeValue
            //      { StringValue = "SenderId", DataType = "String" });
            PublishResponse pubResponse = snsClient.PublishAsync(pubRequest).Result;

            return(pubResponse);
        }
示例#13
0
        public static async Task TryPublishNotification(string objectsKey)
        {
            string topicArn = Environment.GetEnvironmentVariable("TOPICARN");

            using var client = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.USEast1);
            var request = new PublishRequest
            {
                TopicArn = topicArn,
                Message  = "User sent too many logs today, objectKey" +
                           " ({userId}-{TodaysDate}-{#of log sent today}.log)=" + objectsKey,
                Subject = "Access.analyser - too many logs"
            };

            try
            {
                await client.PublishAsync(request).ConfigureAwait(false);

                Console.WriteLine("Successfully published notification");
            }
            catch (AmazonClientException e)
            {
                Console.WriteLine("failed to send message" + e);
            }
            catch (AmazonSimpleNotificationServiceException e)
            {
                Console.WriteLine("failed to send message" + e);
            }
        }
示例#14
0
 public static async Task PublishMessage(string topicArn, string message, string subject = null)
 {
     using (var client = new AmazonSimpleNotificationServiceClient(ConfigManager.ConfigSettings.AccessKey, ConfigManager.ConfigSettings.Secret, Amazon.RegionEndpoint.USWest2))
     {
         await client.PublishAsync(topicArn, message, subject);
     }
 }
示例#15
0
        public async Task FunctionHandler(IotButtonPayload @event, ILambdaContext context)
        {
            context.Logger.LogLine($"Received event: {JsonConvert.SerializeObject(@event)}");

            var publishRequest = new PublishRequest
            {
                TopicArn = TOPIC_ARN,
                Subject  = "Greetings from IoT Button",
                Message  = $"Pressed: {@event.ClickType}",
            };

            string topicArn = Environment.GetEnvironmentVariable("TopicArn");

            context.Logger.LogLine($"TopicArn: {topicArn.Substring(0, 30)}...");
            string accessKey = Environment.GetEnvironmentVariable("AccessKey");

            context.Logger.LogLine($"AccessKey: {accessKey.Substring(0, 5)}...");
            string secretKey = Environment.GetEnvironmentVariable("SecretKey");

            context.Logger.LogLine($"SecretKey: {secretKey.Substring(0, 5)}...");

            var client = new AmazonSimpleNotificationServiceClient(accessKey, secretKey, RegionEndpoint.EUWest1);
            await client.PublishAsync(publishRequest).ConfigureAwait(false);

            context.Logger.LogLine("Event published successfully");
        }
示例#16
0
        public async Task <JsonResult> Post(string commentText)
        {
            try
            {
                using (var comprehendClient = new AmazonComprehendClient(Amazon.RegionEndpoint.USEast1))
                {
                    var sentimentResults = await comprehendClient.DetectSentimentAsync(
                        new DetectSentimentRequest()
                    {
                        Text         = commentText,
                        LanguageCode = LanguageCode.En
                    });

                    if (sentimentResults.Sentiment.Value == "NEGATIVE")
                    {
                        using (var snsClient = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.USEast1))
                        {
                            var response = await snsClient.PublishAsync(new PublishRequest()
                            {
                                Subject   = "Negative Comment",
                                Message   = $"Someone posted this negative comment on your blog. Check it out - {Environment.NewLine} ***** {Environment.NewLine} {commentText} {Environment.NewLine} ***** ",
                                TargetArn = "arn:aws:sns:us-east-1:831210339789:CommentNotifier"
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(new JsonResult(ex.Message));
            }

            return(new JsonResult("Post Successful"));
        }
示例#17
0
        public override async Task <Response> HandlerFunction(Request request, ILambdaContext context)
        {
            string topicArn = System.Environment.GetEnvironmentVariable("TOPIC_ARN");

            Console.WriteLine("topicArn = ");
            Console.WriteLine(topicArn);
            string message = "Hello at " + DateTime.Now.ToShortTimeString();

            var client = new AmazonSimpleNotificationServiceClient(region: Amazon.RegionEndpoint.USEast1);

            var snsRequest = new PublishRequest
            {
                Message  = message,
                TopicArn = topicArn
            };

            try
            {
                var response = await client.PublishAsync(snsRequest);

                Console.WriteLine("Message sent to topic:");
                Console.WriteLine(message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Caught exception publishing request:");
                Console.WriteLine(ex.Message);
            }

            return(new Response("SNS Message sent", request));
        }
        public PublishResponse WriteMessage <T>(T targetype)
        {
            try
            {
                var message = JsonConvert.SerializeObject(targetype);

                if (message != null)
                {
                    var snsClient = new AmazonSimpleNotificationServiceClient();

                    var response = snsClient.PublishAsync(new PublishRequest()
                    {
                        TopicArn = OrderArn,
                        Message  = message
                    });

                    return(response.Result);
                }
            }
            catch (System.Exception)
            {
                throw;
            }
            return(null);
        }
示例#19
0
        /// <summary>
        /// Sends the message.
        /// </summary>
        /// <param name="toPhoneNumber">To phone number.</param>
        /// <param name="message">The message.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentException">
        /// toPhoneNumber
        /// or
        /// message
        /// </exception>
        public async Task <(bool, string?)> SendMessage(string toPhoneNumber, string message)
        {
            if (string.IsNullOrWhiteSpace(toPhoneNumber))
            {
                throw new ArgumentException(nameof(toPhoneNumber));
            }

            if (string.IsNullOrWhiteSpace(message))
            {
                throw new ArgumentException(nameof(message));
            }

            var pubRequest = new PublishRequest
            {
                Message           = message,
                PhoneNumber       = toPhoneNumber,
                MessageAttributes =
                {
                    ["AWS.SNS.SMS.SenderID"] =
                        new MessageAttributeValue {
                        StringValue = _sender, DataType = "String"
                    },
                    ["AWS.SNS.SMS.SMSType"] =
                        new MessageAttributeValue {
                        StringValue = "Transactional", DataType = "String"
                    }
                }
            };

            var pubResponse = await _client.PublishAsync(pubRequest).ConfigureAwait(false);

            return((int)pubResponse.HttpStatusCode < 400, pubResponse.MessageId);
        }
        // TODO: move this method to service
        private async Task RaiseAdvertConfirmedMessageAsync(ConfirmAdvertDto confirmModel)
        {
            var topicArn = _configuration.GetValue <string>("TopicArn");

            // To get the title we fetch the advert from db,
            // or in another way you can pass Title with ConfirmAdvertDto
            var advert = await _advertStorageService.GetByIdAsync(confirmModel.Id);

            if (advert == null)
            {
                throw new KeyNotFoundException($"Record with Id: {confirmModel.Id} was not found.");
            }

            using (var snsClient = new AmazonSimpleNotificationServiceClient())
            {
                var message = new AdvertConfirmedMessage
                {
                    Id    = confirmModel.Id,
                    Title = advert.Title
                };

                var messageJson = JsonConvert.SerializeObject(message);

                await snsClient.PublishAsync(topicArn, messageJson);
            }
        }
示例#21
0
        private async Task RaiseAdvertConfirmedMessage(ConfirmAdvertModel model)
        {
            var topicArn = Configuration.GetValue <string>("TopicArn");
            var dbModel  = await _advertStorageService.GetById(model.Id);

            try
            {
                using (var client = new AmazonSimpleNotificationServiceClient())
                {
                    var message = new AdvertConfirmedMessage
                    {
                        Id    = model.Id,
                        Title = dbModel.Title
                    };

                    var messageJson = JsonConvert.SerializeObject(message);
                    await client.PublishAsync(topicArn, messageJson);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }
        // Notify through sms (or email)
        private static void snsPublish(string contact, string message)
        {
            AmazonSimpleNotificationServiceClient client = new AmazonSimpleNotificationServiceClient(RegionEndpoint.USEast1);
            string arn = "arn:aws:sns:xxxxxxxx:TrafficTicket";

            // subscribe user to the ticketing policy
            SubscribeRequest request = new SubscribeRequest(arn, "sms", contact); // ("sms" can be replaced by "email)
            var task = client.SubscribeAsync(request, new System.Threading.CancellationToken());

            task.Wait();

            // Publish the message
            PublishRequest p = new PublishRequest
                               (
                message: message,
                topicArn: arn
                               );
            var task2 = client.PublishAsync(p, new System.Threading.CancellationToken());

            task2.Wait();
            PublishResponse r = task2.Result;

            Console.WriteLine("PublishRequest: " + r.ResponseMetadata.RequestId);
            Console.WriteLine("Message sent succesfully.");
        }
示例#23
0
        public async Task SendMessage(string message)
        {
            AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient(_settings.Key, _settings.SecretKey, Amazon.RegionEndpoint.EUWest1);
            PublishRequest pubRequest = new PublishRequest
            {
                Message     = message,
                PhoneNumber = _settings.Phone
            };

            pubRequest.MessageAttributes["AWS.SNS.SMS.SenderID"] =
                new MessageAttributeValue {
                StringValue = "NOTICE", DataType = "String"
            };
            pubRequest.MessageAttributes["AWS.SNS.SMS.MaxPrice"] =
                new MessageAttributeValue {
                StringValue = "0.10", DataType = "Number"
            };
            pubRequest.MessageAttributes["AWS.SNS.SMS.SMSType"] =
                new MessageAttributeValue {
                StringValue = "Promotional", DataType = "String"
            };

            try
            {
                PublishResponse pubResponse = await snsClient.PublishAsync(pubRequest);

                Console.WriteLine("Successfully sent message " + pubResponse.MessageId);
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught error in Messenger.cs");
                Console.WriteLine(e);
            }
        }
示例#24
0
        public async void passwordreset([FromBody] Users u)
        {
            Users a = _context.Users.Find(u.Email);

            _log.LogInformation("Listing all items");

            Console.WriteLine("Hello inside the reset");
            if (a != null)
            {
                var client   = new AmazonSimpleNotificationServiceClient(RegionEndpoint.USEast1);
                var request  = new ListTopicsRequest();
                var response = new ListTopicsResponse();
                _log.LogInformation("going inside for");

                response = await client.ListTopicsAsync();

                foreach (var topic in response.Topics)
                {
                    _log.LogInformation(topic.TopicArn);
                    if (topic.TopicArn.EndsWith("SNSTopicResetPassword"))
                    {
                        _log.LogInformation(topic.TopicArn);
                        var respose = new PublishRequest
                        {
                            TopicArn = topic.TopicArn,
                            Message  = a.Email
                        };

                        await client.PublishAsync(respose);
                    }
                }
            }
        }
示例#25
0
        public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context)
        {
            context.Logger.LogLine(">FunctionHandler\n");

            var config = new AmazonSimpleNotificationServiceConfig();

            config.ServiceURL = Environment.ExpandEnvironmentVariables("%SNSENDPOINT%");

            var client = new AmazonSimpleNotificationServiceClient(config);

            context.Logger.LogLine("AmazonSNSClient created\n");

            var request = new PublishRequest
            {
                TopicArn = Environment.ExpandEnvironmentVariables("%TOPICARN%"),
                Message  = input.Body,
            };

            client.PublishAsync(request).Wait();

            context.Logger.LogLine("PublishAsync completed\n");

            var response = new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body       = input.Body,
                Headers    = new Dictionary <string, string> {
                    { "Content-Type", "text/plain" }
                },
            };

            context.Logger.LogLine("<FunctionHandler\n");

            return(response);
        }
示例#26
0
        /// <summary>
        /// Push a notification to the topic
        /// </summary>
        /// <param name="message"> The message to publish </param>
        /// <returns> The publish response </returns>
        public static PublishResponse PushNotification(string message)
        {
            var client = new AmazonSimpleNotificationServiceClient();
            var res    = client.PublishAsync(TopicArn, message).Result;

            return(res);
        }
示例#27
0
        static async Task Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                         .AddUserSecrets <AmazonSnsSettings>()
                         .Build();

            var settings = config.GetSection("AmazonSNS").Get <AmazonSnsSettings>();

            Console.WriteLine($"TopicArn : '{settings.TopicArn}'.");

            string message = $"This test message was sent at {DateTime.Now}.";

            Console.WriteLine($"Message  : '{message}'.");

            var client = new AmazonSimpleNotificationServiceClient(region: RegionEndpoint.USWest1);

            Console.WriteLine();

            try
            {
                var response = await client.PublishAsync(new PublishRequest
                {
                    Message  = message,
                    TopicArn = settings.TopicArn
                });

                Console.WriteLine($"Message has been sent to topic.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        public async Task <bool> PublishAsync(string eventName, Message message)
        {
            var topicArn        = topics[eventName];
            var json            = this.jsonSerializer.Serialize(message);
            var publishResponse = await snsClient.PublishAsync(topicArn, json);

            return(publishResponse.HttpStatusCode == System.Net.HttpStatusCode.OK);
        }
示例#29
0
        private async Task ProcessMessageAsync(SQSEvent.SQSMessage message, ILambdaContext context)
        {
            context.Logger.LogLine($"Processed message {message.Body}");

            var response = await snsClient.PublishAsync(AWS_SNS_TOPIC, message.Body);

            context.Logger.LogLine($"Processed SNS: {response.HttpStatusCode}, MessageId: {response.MessageId}");
        }
 public async Task NotifyAsync(AlexaMessage message)
 {
     await _snsClient.PublishAsync(new PublishRequest
     {
         Message  = JsonConvert.SerializeObject(message),
         TopicArn = _topicArn
     });
 }