Publish() public method

Sends a message to all of a topic's subscribed endpoints. When a messageId is returned, the message has been saved and Amazon SNS will attempt to deliver it to the topic's subscribers shortly. The format of the outgoing message to each subscribed endpoint depends on the notification protocol.

To use the Publish action for sending a message to a mobile endpoint, such as an app on a Kindle device or mobile phone, you must specify the EndpointArn for the TargetArn parameter. The EndpointArn is returned when making a call with the CreatePlatformEndpoint action.

For more information about formatting messages, see Send Custom Platform-Specific Payloads in Messages to Mobile Devices.

/// Indicates that the user has been denied access to the requested resource. /// /// Exception error indicating endpoint disabled. /// /// Indicates an internal service error. /// /// Indicates that a request parameter does not comply with the associated constraints. /// /// Indicates that a request parameter does not comply with the associated constraints. /// /// Indicates that the requested resource does not exist. /// /// Exception error indicating platform application disabled. ///
public Publish ( PublishRequest request ) : PublishResponse
request PublishRequest Container for the necessary parameters to execute the Publish service method.
return PublishResponse
コード例 #1
0
 public static void PublishMessage(string topicArn, string message, string subject = null)
 {
     using (var client = new AmazonSimpleNotificationServiceClient(Settings.AccessKey, Settings.Secret))
     {
         client.Publish(topicArn, message, subject);
     }
 }
コード例 #2
0
        /// <summary>
        /// Sends the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        public void Send(Message message)
        {
            var messageString = JsonConvert.SerializeObject(message);
            _logger.DebugFormat("SQSMessageProducer: Publishing message with topic {0} and id {1} and message: {2}", message.Header.Topic, message.Id, messageString);
            
            using (var client = new AmazonSimpleNotificationServiceClient())
            {
                var topicArn = EnsureTopic(message.Header.Topic, client);

                var publishRequest = new PublishRequest(topicArn, messageString);
                client.Publish(publishRequest);
            }
        }
コード例 #3
0
        public void PushSNSNotification(string topicARN, string subject, string message)
        {
            AmazonSimpleNotificationServiceClient client = new AmazonSimpleNotificationServiceClient();

            try
            {
                _logger.Log(LogLevel.Info, String.Format("Pushing Message {0} to Amazon SNS", message));

                client.Publish(new PublishRequest()
                {
                    Message = message,
                    TopicArn = topicARN,
                    Subject = subject
                });
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Fatal, String.Format("Exception Pusing Message {0} to Amazon SNS. {1}", message, ex.Message));
            }
        }
コード例 #4
0
        public void publish(FolderVaultMapping mapping, bool publishToEmailTopic)
        {
            StringBuilder message = new StringBuilder("{\"Action\":");
            message.Append(safeString(Action));
            foreach (KeyValuePair<string, string> pair in Properties)
            {
                message.Append(',');
                message.Append(safeString(pair.Key));
                message.Append(':');
                message.Append(safeString(pair.Value));
            }
            message.Append("}");

            using (AmazonSimpleNotificationServiceClient client = new AmazonSimpleNotificationServiceClient(mapping.AccessKey, mapping.SecretKey, mapping.Endpoint))
            {
                PublishRequest req = new PublishRequest();
                req.TopicArn = publishToEmailTopic ? mapping.EmailTopicARN : mapping.NotificationTopicARN;
                req.Message = message.ToString();
                MessageId = client.Publish(req).PublishResult.MessageId;
            }
        }
        public bool SendPersonUpdatedNotification(int personId, string message)
        {
            var topicArn = ConfigurationManager.AppSettings["AWSSNSTopicArn"];

            var snsClient = new AmazonSimpleNotificationServiceClient(RegionEndpoint.USEast1);
          
            try
            {                
                var publishRequest = new Amazon.SimpleNotificationService.Model.PublishRequest();
                publishRequest.TopicArn = topicArn;
                publishRequest.Message = message;
                publishRequest.Subject = personId.ToString();

                snsClient.Publish(publishRequest);

                return true;
            }
            catch (Exception ex)
            {
                // TODO Log exception
                return false;
            }                       
        }
コード例 #6
0
        public virtual void PublishTopicMessage(AmazonSimpleNotificationServiceClient snsClient, string topicArn,
            string subject, string message)
        {
            // Create the request
            var publishRequest = new PublishRequest
            {
                Subject = subject,
                Message = message,
                TopicArn = topicArn
            };

            // Submit the request
            snsClient.Publish(publishRequest);
        }
コード例 #7
0
        public bool ConfirmUser(string accountConfirmationToken)
        {
            var confirmed = false;
            User user;

            logger.Log(LogLevel.Info, string.Format("Confirming User Registration with Email Token {0}. Starting.", accountConfirmationToken));

            if (string.IsNullOrEmpty(accountConfirmationToken))
            {
                logger.Log(LogLevel.Error, string.Format("Confirming User Registration with Email Token {0}. No confirmation token.", accountConfirmationToken));

                throw CreateArgumentNullOrEmptyException("accountConfirmationToken");
            }
            using (Context context = new Context())
            {
                user = _ctx.Users.FirstOrDefault(Usr => Usr.ConfirmationToken.Equals(accountConfirmationToken));

                if (user == null)
                {
                    logger.Log(LogLevel.Error, string.Format("Confirming User Registration with Email Token {0}. Unable to find user associated with account token.", accountConfirmationToken));

                    return false;
                }

                confirmed = true;
                user.IsConfirmed = true;
                _ctx.SaveChanges();
            }
            if (!confirmed)
                return false;

            logger.Log(LogLevel.Info, string.Format("Confirming User Registration with Email Token {0}. Calling Workflow.", accountConfirmationToken));

            try
            {
                logger.Log(LogLevel.Info, string.Format("Confirming User Registration with Email Token {0}. Calling Amazon SNS.", accountConfirmationToken));

                AmazonSimpleNotificationServiceClient client = new AmazonSimpleNotificationServiceClient();

                client.Publish(new PublishRequest()
                {
                    Message = user.UserId.ToString(),
                    TopicArn = ConfigurationManager.AppSettings["UserPostedTopicARN"],
                    Subject = "New User Registration"
                });
            }
            catch (Exception ex)
            {
                logger.Log(LogLevel.Info, string.Format("Confirming User Registration with Email Token {0}. Exception {1}.", accountConfirmationToken, ex.Message));
                return false;
            }

            logger.Log(LogLevel.Info, string.Format("Confirming User Registration with Email Token {0}. Ending.", accountConfirmationToken));

            return true;
        }
コード例 #8
0
        protected void Send()
        {
            try
            {

                using (AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient("AKIAJHGOA5MAPPB3JCTA", "/EqP+uv+q+T7b3TkfBA/Xn7f4finoQEZgwSKOZ1K", RegionEndpoint.USEast1))
                {

                    snsClient.Publish(new PublishRequest()
                    {
                        Subject = message.Subject,
                        Message = message.Message,
                        TopicArn = message.ARN
                    });
                    LastSent = DateTime.UtcNow;
                    string insert = String.Format("INSERT INTO Notification (Id, GameId, Subject, Message, Topic, Level, ARN, CreatedAt) VALUES ({0},'{1}','{2}','{3}','{4}','{5}','{6}','{7}');", 0, GameId, message.Subject, message.Message, Topic.ToString(), Level.ToString(), message.ARN, LastSent.ToString("yyyy-MM-dd HH:mm:ss"));
                    DBManager.Instance.Insert(Datastore.Monitoring, insert);
                }
            }
            catch (Exception ex)
            {

                Console.WriteLine(String.Format("Notification Error <> {0}", ex.Message));
                Logger.Instance.Exception(String.Format("Notification Error <> {0}", ex.Message), ex.StackTrace);
            }
        }
コード例 #9
0
        private int PublishEndpoint(string endpointarn, string msg)
        {
            try
            {

                using (var snsclient = new AmazonSimpleNotificationServiceClient(_accesskey, _secretkey))
                {

                    var publish = new PublishRequest()
                    {
                        TargetArn = endpointarn,
                        Message = msg,
                        MessageStructure = "json"
                    };
                    snsclient.Publish(publish);

                    return 0;

                }
            }
            catch (Exception)
            {
                return -1;
            }
        }
コード例 #10
0
        /// <summary>
        /// Uses SNS to send an SMS to a user.
        /// </summary>
        /// <param name="userID">The user being sent an SMS</param>
        /// <param name="inputBody">The body of the SMS</param>
        public static void SendSMS(int userID, string inputBody)
        {
            String userName = (from userprofiles in userDb.UserProfiles
                               where userprofiles.UserId == userID
                               select userprofiles.UserName).FirstOrDefault(); //Resolve username from userID

            if (inputBody == "")
                inputBody = "Hello. You have received a new notification. Visit The Cookbook for more information.";

            AmazonSimpleNotificationServiceClient client = new AmazonSimpleNotificationServiceClient();
            PublishRequest request = new PublishRequest
            {
                TopicArn = "arn:aws:sns:us-east-1:727060774285:" + userName,
                Message = inputBody
            };

            try
            {
                PublishResponse response = client.Publish(request);
                PublishResult result = response.PublishResult;

                String[] strings = new String[1];

                for (int i = 0; i < strings.GetLength(0); i++)
                {
                    strings[i] = "Success! Message ID is: " + result.MessageId;
                }

                Console.WriteLine(strings[0]); ;

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
コード例 #11
0
ファイル: SNSSamples.cs プロジェクト: rajdotnet/aws-sdk-net
    public static void SNSCreateSubscribePublish()
    {
      #region SNSCreateSubscribePublish
      var snsClient = new AmazonSimpleNotificationServiceClient();

      var topicRequest = new CreateTopicRequest
      {
        Name = "CodingTestResults"
      };

      var topicResponse = snsClient.CreateTopic(topicRequest);

      var topicAttrRequest = new SetTopicAttributesRequest
      {
        TopicArn = topicResponse.TopicArn,
        AttributeName = "DisplayName",
        AttributeValue = "Coding Test Results"
      };

      snsClient.SetTopicAttributes(topicAttrRequest);

      snsClient.Subscribe(new SubscribeRequest
      {
        Endpoint = "*****@*****.**",
        Protocol = "email",
        TopicArn = topicResponse.TopicArn
      });

      // Wait for up to 2 minutes for the user to confirm the subscription.
      DateTime latest = DateTime.Now + TimeSpan.FromMinutes(2);

      while (DateTime.Now < latest)
      {
        var subsRequest = new ListSubscriptionsByTopicRequest
        {
          TopicArn = topicResponse.TopicArn
        };

        var subs = snsClient.ListSubscriptionsByTopic(subsRequest).Subscriptions;

        var sub = subs[0];

        if (!string.Equals(sub.SubscriptionArn,
          "PendingConfirmation", StringComparison.Ordinal))
        {
          break;
        }

        // Wait 15 seconds before trying again.
        System.Threading.Thread.Sleep(TimeSpan.FromSeconds(15));
      }

      snsClient.Publish(new PublishRequest
      {
        Subject = "Coding Test Results for " +
          DateTime.Today.ToShortDateString(),
        Message = "All of today's coding tests passed.",
        TopicArn = topicResponse.TopicArn
      });
      #endregion
    }
コード例 #12
0
        /// <summary>
        /// This is the main function for sending notification
        /// </summary>
        public void sendNotification()
        {
            foreach (Client client in clients)
            {
                int clientID = client.getClientID();

                #region AWS connection - This code block is same for every push message type - This is the basic block.

                _client = new AmazonSimpleNotificationServiceClient("XXXXXXX", "XXXXXXXXXX", Amazon.RegionEndpoint.EUCentral1);
                string    token       = client.getPushToken();
                Platfroms mobilOsType = client.getMobileType() == 0 ? Platfroms.IOS_PATFORM : Platfroms.ANDROID_PLATFORM;

                try
                {
                    string applicationArn = "";

                    try
                    {
                        applicationArn = applications[(int)mobilOsType].getArn();
                    }
                    catch
                    {
                        continue;
                    }

                    string endPointArn = createEndPointArn(token, applicationArn);

                    if (string.IsNullOrEmpty(endPointArn))
                    {
                        continue;
                    }
                    else
                    {
                        PublishRequest publishRequest          = new PublishRequest();
                        Dictionary <string, string> messageMap = new Dictionary <string, string>();
                        messageMap.Add("default", "default message");
                        string platform = mobilOsType == 0 ? "APNS_SANDBOX" : "GCM";

                        // This application developed for IOS and Android
                        if (mobilOsType != Platfroms.IOS_PATFORM && mobilOsType != Platfroms.ANDROID_PLATFORM)
                        {
                            continue;
                        }

                        int    clientsID = client.getClientID();
                        Guid   pushesID  = client.getPushID();
                        string message   = mobilOsType == 0 ? getAPNSMessage(notification, title, pushesID, clientsID) : getGCMMessage(notification, title, pushesID, clientsID);
                        messageMap.Add(platform, message);

                        publishRequest.TargetArn        = endPointArn;
                        publishRequest.MessageStructure = "json";

                        string messageJSON = "";

                        try
                        {
                            messageJSON = JsonConvert.SerializeObject(messageMap);
                        }
                        catch
                        {
                            continue;
                        }

                        try
                        {
                            publishRequest.Message = messageJSON;
                            _client.Publish(publishRequest);
                        }
                        catch
                        {
                            continue;
                        }

                        try
                        {
                            // for deleting endPointArn
                            DeleteEndpointRequest _request = new DeleteEndpointRequest();
                            _request.EndpointArn = endPointArn;
                            _client.DeleteEndpoint(_request);
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }
                catch
                {
                    continue;
                }

                #endregion
            }
        }