Container for the parameters to the Publish operation.

The Publish action 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 selected.

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. The EndpointArn is returned when making a call with the CreatePlatformEndpoint action. The second example below shows a request and response for publishing to a mobile endpoint.

Наследование: AmazonSimpleNotificationServiceRequest
Пример #1
0
        public object Execute(ExecutorContext context)
        {
            var cmdletContext = context as CmdletContext;
            // create request
            var request = new Amazon.SimpleNotificationService.Model.PublishRequest();

            if (cmdletContext.Message != null)
            {
                request.Message = cmdletContext.Message;
            }
            if (cmdletContext.MessageAttribute != null)
            {
                request.MessageAttributes = cmdletContext.MessageAttribute;
            }
            if (cmdletContext.MessageStructure != null)
            {
                request.MessageStructure = cmdletContext.MessageStructure;
            }
            if (cmdletContext.PhoneNumber != null)
            {
                request.PhoneNumber = cmdletContext.PhoneNumber;
            }
            if (cmdletContext.Subject != null)
            {
                request.Subject = cmdletContext.Subject;
            }
            if (cmdletContext.TargetArn != null)
            {
                request.TargetArn = cmdletContext.TargetArn;
            }
            if (cmdletContext.TopicArn != null)
            {
                request.TopicArn = cmdletContext.TopicArn;
            }

            CmdletOutput output;

            // issue call
            var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);

            try
            {
                var    response       = CallAWSServiceOperation(client, request);
                object pipelineOutput = null;
                pipelineOutput = cmdletContext.Select(response, this);
                output         = new CmdletOutput
                {
                    PipelineOutput  = pipelineOutput,
                    ServiceResponse = response
                };
            }
            catch (Exception e)
            {
                output = new CmdletOutput {
                    ErrorResponse = e
                };
            }

            return(output);
        }
        protected async Task <PublishToSNSResult> PublishToTopicAsync(string topicArn, string message)
        {
            Amazon.SimpleNotificationService.Model.PublishRequest pReq = new Amazon.SimpleNotificationService.Model.PublishRequest();
            pReq.TopicArn         = topicArn;
            pReq.MessageStructure = "json";
            pReq.Message          = message;

            try
            {
                PublishResponse pRes = await snsClient.PublishAsync(pReq);

                return(new PublishToSNSSuccessfulResult(pRes.MessageId));
            }
            catch (EndpointDisabledException)
            {
                return(new PublishToSNSEndpointDisabledResult());
            }
            catch (InvalidParameterException exception)
            {
                if (exception.Message.Contains("No endpoint found for the target arn specified"))
                {
                    return(new PublishToSNSEndpointNotFoundResult());
                }
                throw exception;
            }
        }
Пример #3
0
        public async Task<PublishResponse> DespatchAsync(string topicArn, string message)
        {
            if (string.IsNullOrEmpty(topicArn) || string.IsNullOrEmpty(message))
            {
                return new PublishResponse(); //do not proceed
            }

            var request = new PublishRequest(topicArn, message);
            var response = await _client.PublishAsync(request);
            return response;
        }
Пример #4
0
        /// <summary>
        /// Sends the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        public void Send(Message message)
        {
            var messageString = JsonConvert.SerializeObject(message);
            _logger.Value.DebugFormat("SQSMessageProducer: Publishing message with topic {0} and id {1} and message: {2}", message.Header.Topic, message.Id, messageString);

            using (var client = new AmazonSimpleNotificationServiceClient(_credentials))
            {
                var topicArn = EnsureTopic(message.Header.Topic, client);
                var publishRequest = new PublishRequest(topicArn, messageString);
                client.PublishAsync(publishRequest).Wait();
            }
        }
        protected async Task <PublishToSNSResult> PublishToEndpointAsync(string endpointArn, string message)
        {
            Amazon.SimpleNotificationService.Model.PublishRequest pReq = new Amazon.SimpleNotificationService.Model.PublishRequest();

            if ((model.TimeToLive ?? 0) > 0)
            {
                string ttlAttrKeyAPNS = "";
                switch (model.TargetEnvironment)
                {
                case TargetEnvironmentType.Sandbox:
                    ttlAttrKeyAPNS = "AWS.SNS.MOBILE.APNS_SANDBOX.TTL";
                    break;

                default:
                    ttlAttrKeyAPNS = "AWS.SNS.MOBILE.APNS.TTL";
                    break;
                }
                string ttlAttrKeyGCM = "AWS.SNS.MOBILE.GCM.TTL";

                Dictionary <String, MessageAttributeValue> messageAttributes = new Dictionary <String, MessageAttributeValue>();
                MessageAttributeValue value = new MessageAttributeValue();
                value.DataType    = "String";
                value.StringValue = model.TimeToLive.ToString();

                messageAttributes[ttlAttrKeyAPNS] = value;
                messageAttributes[ttlAttrKeyGCM]  = value;
                pReq.MessageAttributes            = messageAttributes;
            }

            pReq.TargetArn        = endpointArn;
            pReq.MessageStructure = "json";
            pReq.Message          = message;

            try
            {
                PublishResponse pRes = await snsClient.PublishAsync(pReq);

                return(new PublishToSNSSuccessfulResult(pRes.MessageId));
            }
            catch (EndpointDisabledException)
            {
                return(new PublishToSNSEndpointDisabledResult());
            }
            catch (InvalidParameterException exception)
            {
                if (exception.Message.Contains("No endpoint found for the target arn specified"))
                {
                    return(new PublishToSNSEndpointNotFoundResult());
                }
                throw exception;
            }
        }
        public string PublishMessageToTopic(string topicArn, string subject, string message)
        {
            topicArn.Requires("topicArn").IsNotNullOrWhiteSpace();
            subject.Requires("subject").IsNotNullOrWhiteSpace();
            message.Requires("message").IsNotNullOrWhiteSpace();

            var publishRequest = new PublishRequest(topicArn, message, subject);
            using (var sns = amazonSnsFactory())
            {
                var result = sns.Publish(publishRequest);
                return result?.MessageId;
            }
        }
Пример #7
0
        public string PublishMessageToTopic(string topicArn, string subject, string message)
        {
            Validate.That(topicArn).IsNotNullOrEmpty();
            Validate.That(subject).IsNotNullOrEmpty();
            Validate.That(message).IsNotNullOrEmpty();

            var publishRequest = new PublishRequest()
                .WithSubject(subject)
                .WithMessage(message)
                .WithTopicArn(topicArn);
            using (var sns = amazonSnsFactory())
            {
                var result = sns.Publish(publishRequest);
                return result.PublishResult.MessageId;
            }
        }
Пример #8
0
        public static ServiceResponse Send(Message message)
        {
            ServiceResponse response = new ServiceResponse();

            if (message.IsValid())
            {
                var snsService = new Amazon.SimpleNotificationService.AmazonSimpleNotificationServiceClient(AWSCredentials.AccessKey, AWSCredentials.SecretKey, RegionEndpoint.USEast1);

                var attributes = new Dictionary <string, MessageAttributeValue>();
                attributes.Add("AWS.SNS.SMS.SenderID", new MessageAttributeValue()
                {
                    StringValue = message.SenderId, DataType = "String"
                });
                attributes.Add("AWS.SNS.SMS.SMSType", new MessageAttributeValue()
                {
                    StringValue = message.Type.GetDescription(), DataType = "String"
                });

                var request = new Amazon.SimpleNotificationService.Model.PublishRequest();
                request.PhoneNumber       = $"+{message.PhoneNumber}";
                request.Message           = message.TextMessage;
                request.MessageAttributes = attributes;

                var result = snsService.PublishAsync(request).Result;
                if (result.HttpStatusCode == System.Net.HttpStatusCode.OK)
                {
                    response.IsValid = true;
                }
                else
                {
                    response.Errors.Add("SMS failed!");
                    response.IsValid = false;
                }
            }
            else
            {
                response.Errors  = message.Errors;
                response.IsValid = false;
            }
            return(response);
        }
Пример #9
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;
            }
        }
Пример #10
0
        public static PublishRequest SetAttribute(this PublishRequest request, string key, string value)
        {
            if (request is null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentException($"'{nameof(key)}' cannot be null or whitespace", nameof(key));
            }

            // set the value when not null or empty
            if (!string.IsNullOrWhiteSpace(value))
            {
                request.MessageAttributes[key] = new MessageAttributeValue {
                    DataType = "String", StringValue = value
                };
                return(request);
            }

            return(request);
        }
Пример #11
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);
        }
Пример #12
0
        /// <summary>
        /// Publish a notification
        /// </summary>
        /// <param name="topicArn"></param>
        /// <param name="subject"></param>
        /// <param name="message"></param>
        public string Publish(string topicArn, string subject, string message)
        {
            var request = new PublishRequest { TopicArn = topicArn, Subject = subject, Message = message };

            PublishResponse response = Client.Publish(request);

            return response.PublishResult.MessageId;
        }
 IAsyncResult invokePublish(PublishRequest publishRequest, AsyncCallback callback, object state, bool synchronized)
 {
     IRequest irequest = new PublishRequestMarshaller().Marshall(publishRequest);
     var unmarshaller = PublishResponseUnmarshaller.GetInstance();
     AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
     Invoke(result);
     return result;
 }
 /// <summary>
 /// Initiates the asynchronous execution of the Publish operation.
 /// <seealso cref="Amazon.SimpleNotificationService.IAmazonSimpleNotificationService.Publish"/>
 /// </summary>
 /// 
 /// <param name="publishRequest">Container for the necessary parameters to execute the Publish operation on
 ///          AmazonSimpleNotificationService.</param>
 /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
 /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
 ///          procedure using the AsyncState property.</param>
 /// 
 /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPublish
 ///         operation.</returns>
 public IAsyncResult BeginPublish(PublishRequest publishRequest, AsyncCallback callback, object state)
 {
     return invokePublish(publishRequest, callback, state, false);
 }
Пример #15
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);
            }
        }
        /// <summary>
        /// Initiates the asynchronous execution of the Publish operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the Publish operation on AmazonSimpleNotificationServiceClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        /// 
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPublish
        ///         operation.</returns>
        public IAsyncResult BeginPublish(PublishRequest request, AsyncCallback callback, object state)
        {
            var marshaller = new PublishRequestMarshaller();
            var unmarshaller = PublishResponseUnmarshaller.Instance;

            return BeginInvoke<PublishRequest>(request, marshaller, unmarshaller,
                callback, state);
        }
 /// <summary>
 /// Sends a message to all of a topic's subscribed endpoints. When a    <code>messageId</code>
 /// 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 selected.
 /// 
 ///     
 /// <para>
 /// To use the <code>Publish</code> 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.
 /// The EndpointArn is returned when making a call with the <code>CreatePlatformEndpoint</code>
 /// action.       The second example below shows a request and response for publishing
 /// to a mobile endpoint.    
 /// </para>
 /// </summary>
 /// <param name="topicArn">The topic you want to publish to.</param>
 /// <param name="message">The message you want to send to the topic. If you want to send the same message to all transport protocols,    include the text of the message as a String value. If you want to send different messages for each transport protocol,    set the value of the <code>MessageStructure</code> parameter to <code>json</code>    and use a JSON object for the <code>Message</code> parameter.    See the Examples section for the format of the JSON object.  Constraints: Messages must be UTF-8 encoded   strings at most 256 KB in size (262144 bytes, not 262144 characters). JSON-specific constraints:   <ul>  <li>Keys in the JSON object that correspond to supported transport   protocols must have simple JSON string values. </li>  <li>The values will be parsed (unescaped)  before they are used in outgoing messages.</li>  <li>Outbound notifications are JSON  encoded (meaning that the characters will be reescaped for sending).</li>  <li>Values have a minimum length of 0 (the empty string, "", is allowed).</li>  <li>Values have a maximum length bounded by the overall message size (so, including  multiple protocols may limit message sizes).</li>  <li>Non-string values will cause the key  to be ignored.</li>  <li>Keys that do not correspond to supported transport protocols are ignored.</li>  <li>Duplicate keys are not allowed.</li>  <li>Failure to parse or validate any key or    value in the message will cause the <code>Publish</code> call to return an error (no partial   delivery).</li>   </ul>  </param>
 /// <param name="subject">Optional parameter to be used as the "Subject" line when the message is   delivered to email endpoints. This field will also be included, if present,    in the standard JSON messages delivered to other endpoints. Constraints: Subjects must be ASCII text that begins with a letter, number,    or punctuation mark; must not include line breaks or control characters; and    must be less than 100 characters long.</param>
 /// 
 /// <returns>The response from the Publish service method, as returned by SimpleNotificationService.</returns>
 /// <exception cref="Amazon.SimpleNotificationService.Model.AuthorizationErrorException">
 /// Indicates that the user has been denied access to the requested resource.
 /// </exception>
 /// <exception cref="Amazon.SimpleNotificationService.Model.EndpointDisabledException">
 /// Exception error indicating endpoint disabled.
 /// </exception>
 /// <exception cref="Amazon.SimpleNotificationService.Model.InternalErrorException">
 /// Indicates an internal service error.
 /// </exception>
 /// <exception cref="Amazon.SimpleNotificationService.Model.InvalidParameterException">
 /// Indicates that a request parameter does not comply with the associated constraints.
 /// </exception>
 /// <exception cref="Amazon.SimpleNotificationService.Model.InvalidParameterValueException">
 /// 
 /// </exception>
 /// <exception cref="Amazon.SimpleNotificationService.Model.NotFoundException">
 /// Indicates that the requested resource does not exist.
 /// </exception>
 /// <exception cref="Amazon.SimpleNotificationService.Model.PlatformApplicationDisabledException">
 /// Exception error indicating platform application disabled.
 /// </exception>
 public PublishResponse Publish(string topicArn, string message, string subject)
 {
     var request = new PublishRequest();
     request.TopicArn = topicArn;
     request.Message = message;
     request.Subject = subject;
     return Publish(request);
 }
        /// <summary>
        /// Initiates the asynchronous execution of the Publish operation.
        /// <seealso cref="Amazon.SimpleNotificationService.IAmazonSimpleNotificationService"/>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the Publish operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<PublishResponse> PublishAsync(PublishRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new PublishRequestMarshaller();
            var unmarshaller = PublishResponseUnmarshaller.Instance;

            return InvokeAsync<PublishRequest,PublishResponse>(request, marshaller,
                unmarshaller, cancellationToken);
        }
 /// <summary>
 /// Initiates the asynchronous execution of the Publish operation.
 /// </summary>
 /// 
 /// <param name="request">Container for the necessary parameters to execute the Publish operation on AmazonSimpleNotificationServiceClient.</param>
 /// <param name="callback">An Action delegate that is invoked when the operation completes.</param>
 /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
 ///          procedure using the AsyncState property.</param>
 public void PublishAsync(PublishRequest request, AmazonServiceCallback<PublishRequest, PublishResponse> callback, AsyncOptions options = null)
 {
     options = options == null?new AsyncOptions():options;
     var marshaller = new PublishRequestMarshaller();
     var unmarshaller = PublishResponseUnmarshaller.Instance;
     Action<AmazonWebServiceRequest, AmazonWebServiceResponse, Exception, AsyncOptions> callbackHelper = null;
     if(callback !=null )
         callbackHelper = (AmazonWebServiceRequest req, AmazonWebServiceResponse res, Exception ex, AsyncOptions ao) => { 
             AmazonServiceResult<PublishRequest,PublishResponse> responseObject 
                     = new AmazonServiceResult<PublishRequest,PublishResponse>((PublishRequest)req, (PublishResponse)res, ex , ao.State);    
                 callback(responseObject); 
         };
     BeginInvoke<PublishRequest>(request, marshaller, unmarshaller, options, callbackHelper);
 }
 /// <summary>
 /// Sends a message to all of a topic's subscribed endpoints. When a <code>messageId</code>
 /// 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.
 /// 
 ///  
 /// <para>
 /// To use the <code>Publish</code> 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
 /// <code>CreatePlatformEndpoint</code> action. 
 /// </para>
 ///  
 /// <para>
 /// For more information about formatting messages, see <a href="http://docs.aws.amazon.com/sns/latest/dg/mobile-push-send-custommessage.html">Send
 /// Custom Platform-Specific Payloads in Messages to Mobile Devices</a>. 
 /// </para>
 /// </summary>
 /// <param name="topicArn">The topic you want to publish to. If you don't specify a value for the <code>TopicArn</code> parameter, you must specify a value for the <code>PhoneNumber</code> or <code>TargetArn</code> parameters.</param>
 /// <param name="message">The message you want to send to the topic. If you want to send the same message to all transport protocols, include the text of the message as a String value. If you want to send different messages for each transport protocol, set the value of the <code>MessageStructure</code> parameter to <code>json</code> and use a JSON object for the <code>Message</code> parameter.  Constraints: Messages must be UTF-8 encoded strings at most 256 KB in size (262144 bytes, not 262144 characters). JSON-specific constraints: <ul> <li> Keys in the JSON object that correspond to supported transport protocols must have simple JSON string values. </li> <li> The values will be parsed (unescaped) before they are used in outgoing messages. </li> <li> Outbound notifications are JSON encoded (meaning that the characters will be reescaped for sending). </li> <li> Values have a minimum length of 0 (the empty string, "", is allowed). </li> <li> Values have a maximum length bounded by the overall message size (so, including multiple protocols may limit message sizes). </li> <li> Non-string values will cause the key to be ignored. </li> <li> Keys that do not correspond to supported transport protocols are ignored. </li> <li> Duplicate keys are not allowed. </li> <li> Failure to parse or validate any key or value in the message will cause the <code>Publish</code> call to return an error (no partial delivery). </li> </ul></param>
 /// <param name="subject">Optional parameter to be used as the "Subject" line when the message is delivered to email endpoints. This field will also be included, if present, in the standard JSON messages delivered to other endpoints. Constraints: Subjects must be ASCII text that begins with a letter, number, or punctuation mark; must not include line breaks or control characters; and must be less than 100 characters long.</param>
 /// <param name="callback">An Action delegate that is invoked when the operation completes.</param>
 /// <param name="options">
 ///     A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
 ///     procedure using the AsyncState property.
 /// </param>
 /// 
 /// <returns>The response from the Publish service method, as returned by SimpleNotificationService.</returns>
 /// <exception cref="Amazon.SimpleNotificationService.Model.AuthorizationErrorException">
 /// Indicates that the user has been denied access to the requested resource.
 /// </exception>
 /// <exception cref="Amazon.SimpleNotificationService.Model.EndpointDisabledException">
 /// Exception error indicating endpoint disabled.
 /// </exception>
 /// <exception cref="Amazon.SimpleNotificationService.Model.InternalErrorException">
 /// Indicates an internal service error.
 /// </exception>
 /// <exception cref="Amazon.SimpleNotificationService.Model.InvalidParameterException">
 /// Indicates that a request parameter does not comply with the associated constraints.
 /// </exception>
 /// <exception cref="Amazon.SimpleNotificationService.Model.InvalidParameterValueException">
 /// Indicates that a request parameter does not comply with the associated constraints.
 /// </exception>
 /// <exception cref="Amazon.SimpleNotificationService.Model.NotFoundException">
 /// Indicates that the requested resource does not exist.
 /// </exception>
 /// <exception cref="Amazon.SimpleNotificationService.Model.PlatformApplicationDisabledException">
 /// Exception error indicating platform application disabled.
 /// </exception>
 public void PublishAsync(string topicArn, string message, string subject,  AmazonServiceCallback<PublishRequest, PublishResponse> callback, AsyncOptions options = null)
 {
     var request = new PublishRequest();
     request.TopicArn = topicArn;
     request.Message = message;
     request.Subject = subject;
     PublishAsync(request, callback, options);
 }
Пример #21
0
 private Amazon.SimpleNotificationService.Model.PublishResponse CallAWSServiceOperation(IAmazonSimpleNotificationService client, Amazon.SimpleNotificationService.Model.PublishRequest request)
 {
     Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Simple Notification Service (SNS)", "Publish");
     try
     {
         #if DESKTOP
         return(client.Publish(request));
         #elif CORECLR
         return(client.PublishAsync(request).GetAwaiter().GetResult());
         #else
                 #error "Unknown build edition"
         #endif
     }
     catch (AmazonServiceException exc)
     {
         var webException = exc.InnerException as System.Net.WebException;
         if (webException != null)
         {
             throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
         }
         throw;
     }
 }
        /// <summary>
        /// Initiates the asynchronous execution of the Publish operation.
        /// <seealso cref="Amazon.SimpleNotificationService.IAmazonSimpleNotificationService.Publish"/>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the Publish operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
		public Task<PublishResponse> PublishAsync(PublishRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new PublishRequestMarshaller();
            var unmarshaller = PublishResponseUnmarshaller.GetInstance();
            return Invoke<IRequest, PublishRequest, PublishResponse>(request, marshaller, unmarshaller, signer, cancellationToken);
        }
Пример #23
0
 public void publish_a_message()
 {
     GetUserNameAndPassword();
     var snsClient = Amazon.AWSClientFactory.CreateAmazonSNSClient(_key, _secret);
     var listTopicsRequest = new ListTopicsRequest();
     var listTopicsResponse = snsClient.ListTopics(listTopicsRequest);
     var topicArn = string.Empty;
     foreach (var result in listTopicsResponse.ListTopicsResult.Topics)
     {
         if (result.TopicArn.EndsWith("Elliott-has-an-awesome-blog"))
         {
             topicArn = result.TopicArn;
             break;
         }
     }
     var publishMessageRequest = new PublishRequest()
         .WithMessage(DateTime.Now.ToString() + " YOOOOOOOO!")
         .WithSubject("Elliott has an amazing blog")
         .WithTopicArn(topicArn);
     snsClient.Publish(publishMessageRequest);
 }
        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;
            }
        }
        /// <summary>
        /// <para>The <c>Publish</c> action sends a message to all of a topic's subscribed endpoints. When a <c>messageId</c> 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 selected.</para> <para>To use the <c>Publish</c> 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. The EndpointArn is returned when
        /// making a call with the <c>CreatePlatformEndpoint</c> action. The second example below shows a request and response for publishing to a
        /// mobile endpoint. </para>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the Publish service method on
        /// AmazonSimpleNotificationService.</param>
        /// 
        /// <returns>The response from the Publish service method, as returned by AmazonSimpleNotificationService.</returns>
        /// 
        /// <exception cref="T:Amazon.SimpleNotificationService.Model.NotFoundException" />
        /// <exception cref="T:Amazon.SimpleNotificationService.Model.PlatformApplicationDisabledException" />
        /// <exception cref="T:Amazon.SimpleNotificationService.Model.EndpointDisabledException" />
        /// <exception cref="T:Amazon.SimpleNotificationService.Model.AuthorizationErrorException" />
        /// <exception cref="T:Amazon.SimpleNotificationService.Model.InternalErrorException" />
        /// <exception cref="T:Amazon.SimpleNotificationService.Model.InvalidParameterException" />
		public PublishResponse Publish(PublishRequest request)
        {
            var task = PublishAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                ExceptionDispatchInfo.Capture(e.InnerException).Throw();
                return null;
            }
        }
 /// <summary>
 /// Sends a message to all of a topic's subscribed endpoints. When a    <code>messageId</code>
 /// 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 selected.
 /// 
 ///     
 /// <para>
 /// To use the <code>Publish</code> 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.
 /// The EndpointArn is returned when making a call with the <code>CreatePlatformEndpoint</code>
 /// action.       The second example below shows a request and response for publishing
 /// to a mobile endpoint.    
 /// </para>
 /// </summary>
 /// <param name="topicArn">The topic you want to publish to.</param>
 /// <param name="message">The message you want to send to the topic. If you want to send the same message to all transport protocols,    include the text of the message as a String value. If you want to send different messages for each transport protocol,    set the value of the <code>MessageStructure</code> parameter to <code>json</code>    and use a JSON object for the <code>Message</code> parameter.    See the Examples section for the format of the JSON object.  Constraints: Messages must be UTF-8 encoded   strings at most 256 KB in size (262144 bytes, not 262144 characters). JSON-specific constraints:   <ul>  <li>Keys in the JSON object that correspond to supported transport   protocols must have simple JSON string values. </li>  <li>The values will be parsed (unescaped)  before they are used in outgoing messages.</li>  <li>Outbound notifications are JSON  encoded (meaning that the characters will be reescaped for sending).</li>  <li>Values have a minimum length of 0 (the empty string, "", is allowed).</li>  <li>Values have a maximum length bounded by the overall message size (so, including  multiple protocols may limit message sizes).</li>  <li>Non-string values will cause the key  to be ignored.</li>  <li>Keys that do not correspond to supported transport protocols are ignored.</li>  <li>Duplicate keys are not allowed.</li>  <li>Failure to parse or validate any key or    value in the message will cause the <code>Publish</code> call to return an error (no partial   delivery).</li>   </ul>  </param>
 /// <param name="subject">Optional parameter to be used as the "Subject" line when the message is   delivered to email endpoints. This field will also be included, if present,    in the standard JSON messages delivered to other endpoints. Constraints: Subjects must be ASCII text that begins with a letter, number,    or punctuation mark; must not include line breaks or control characters; and    must be less than 100 characters long.</param>
 /// <param name="cancellationToken">
 ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
 /// </param>
 /// 
 /// <returns>The response from the Publish service method, as returned by SimpleNotificationService.</returns>
 /// <exception cref="Amazon.SimpleNotificationService.Model.AuthorizationErrorException">
 /// Indicates that the user has been denied access to the requested resource.
 /// </exception>
 /// <exception cref="Amazon.SimpleNotificationService.Model.EndpointDisabledException">
 /// Exception error indicating endpoint disabled.
 /// </exception>
 /// <exception cref="Amazon.SimpleNotificationService.Model.InternalErrorException">
 /// Indicates an internal service error.
 /// </exception>
 /// <exception cref="Amazon.SimpleNotificationService.Model.InvalidParameterException">
 /// Indicates that a request parameter does not comply with the associated constraints.
 /// </exception>
 /// <exception cref="Amazon.SimpleNotificationService.Model.InvalidParameterValueException">
 /// 
 /// </exception>
 /// <exception cref="Amazon.SimpleNotificationService.Model.NotFoundException">
 /// Indicates that the requested resource does not exist.
 /// </exception>
 /// <exception cref="Amazon.SimpleNotificationService.Model.PlatformApplicationDisabledException">
 /// Exception error indicating platform application disabled.
 /// </exception>
 public Task<PublishResponse> PublishAsync(string topicArn, string message, string subject, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
 {
     var request = new PublishRequest();
     request.TopicArn = topicArn;
     request.Message = message;
     request.Subject = subject;
     return PublishAsync(request, cancellationToken);
 }
        /// <summary>
        /// Sends a message to all of a topic's subscribed endpoints. When a    <code>messageId</code>
        /// 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 selected.
        /// 
        ///     
        /// <para>
        /// To use the <code>Publish</code> 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.
        /// The EndpointArn is returned when making a call with the <code>CreatePlatformEndpoint</code>
        /// action.       The second example below shows a request and response for publishing
        /// to a mobile endpoint.    
        /// </para>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the Publish service method.</param>
        /// 
        /// <returns>The response from the Publish service method, as returned by SimpleNotificationService.</returns>
        /// <exception cref="Amazon.SimpleNotificationService.Model.AuthorizationErrorException">
        /// Indicates that the user has been denied access to the requested resource.
        /// </exception>
        /// <exception cref="Amazon.SimpleNotificationService.Model.EndpointDisabledException">
        /// Exception error indicating endpoint disabled.
        /// </exception>
        /// <exception cref="Amazon.SimpleNotificationService.Model.InternalErrorException">
        /// Indicates an internal service error.
        /// </exception>
        /// <exception cref="Amazon.SimpleNotificationService.Model.InvalidParameterException">
        /// Indicates that a request parameter does not comply with the associated constraints.
        /// </exception>
        /// <exception cref="Amazon.SimpleNotificationService.Model.InvalidParameterValueException">
        /// 
        /// </exception>
        /// <exception cref="Amazon.SimpleNotificationService.Model.NotFoundException">
        /// Indicates that the requested resource does not exist.
        /// </exception>
        /// <exception cref="Amazon.SimpleNotificationService.Model.PlatformApplicationDisabledException">
        /// Exception error indicating platform application disabled.
        /// </exception>
        public PublishResponse Publish(PublishRequest request)
        {
            var marshaller = new PublishRequestMarshaller();
            var unmarshaller = PublishResponseUnmarshaller.Instance;

            return Invoke<PublishRequest,PublishResponse>(request, marshaller, unmarshaller);
        }
        /// <summary>
        /// <para>The <c>Publish</c> action sends a message to all of a topic's subscribed endpoints. When a <c>messageId</c> 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 selected.</para> <para>To use the <c>Publish</c> 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. The EndpointArn is returned when
        /// making a call with the <c>CreatePlatformEndpoint</c> action. The second example below shows a request and response for publishing to a
        /// mobile endpoint. </para>
        /// </summary>
        /// 
        /// <param name="publishRequest">Container for the necessary parameters to execute the Publish service method on
        /// AmazonSimpleNotificationService.</param>
        /// 
        /// <returns>The response from the Publish service method, as returned by AmazonSimpleNotificationService.</returns>
        /// 
        /// <exception cref="T:Amazon.SimpleNotificationService.Model.NotFoundException" />
        /// <exception cref="T:Amazon.SimpleNotificationService.Model.PlatformApplicationDisabledException" />
        /// <exception cref="T:Amazon.SimpleNotificationService.Model.EndpointDisabledException" />
        /// <exception cref="T:Amazon.SimpleNotificationService.Model.AuthorizationErrorException" />
        /// <exception cref="T:Amazon.SimpleNotificationService.Model.InternalErrorException" />
        /// <exception cref="T:Amazon.SimpleNotificationService.Model.InvalidParameterException" />
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
		public async Task<PublishResponse> PublishAsync(PublishRequest publishRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new PublishRequestMarshaller();
            var unmarshaller = PublishResponseUnmarshaller.GetInstance();
            var response = await Invoke<IRequest, PublishRequest, PublishResponse>(publishRequest, marshaller, unmarshaller, signer, cancellationToken)
                .ConfigureAwait(continueOnCapturedContext: false);
            return response;
        }
        /// <summary>
        /// <para>The <c>Publish</c> action sends a message to all of a topic's subscribed endpoints. When a <c>messageId</c> 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 selected.</para> <para>To use the <c>Publish</c> 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. The EndpointArn is returned when
        /// making a call with the <c>CreatePlatformEndpoint</c> action. The second example below shows a request and response for publishing to a
        /// mobile endpoint. </para>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the Publish service method on
        /// AmazonSimpleNotificationService.</param>
        /// 
        /// <returns>The response from the Publish service method, as returned by AmazonSimpleNotificationService.</returns>
        /// 
        /// <exception cref="T:Amazon.SimpleNotificationService.Model.NotFoundException" />
        /// <exception cref="T:Amazon.SimpleNotificationService.Model.PlatformApplicationDisabledException" />
        /// <exception cref="T:Amazon.SimpleNotificationService.Model.EndpointDisabledException" />
        /// <exception cref="T:Amazon.SimpleNotificationService.Model.AuthorizationErrorException" />
        /// <exception cref="T:Amazon.SimpleNotificationService.Model.InternalErrorException" />
        /// <exception cref="T:Amazon.SimpleNotificationService.Model.InvalidParameterException" />
		public PublishResponse Publish(PublishRequest request)
        {
            var task = PublishAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                throw e.InnerException;
            }
        }
 /// <summary>
 /// <para>The <c>Publish</c> action sends a message to all of a topic's subscribed endpoints. When a <c>messageId</c> 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 selected.</para> <para>To use the <c>Publish</c> 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. The EndpointArn is returned when
 /// making a call with the <c>CreatePlatformEndpoint</c> action. The second example below shows a request and response for publishing to a
 /// mobile endpoint. </para>
 /// </summary>
 /// 
 /// <param name="publishRequest">Container for the necessary parameters to execute the Publish service method on
 ///          AmazonSimpleNotificationService.</param>
 /// 
 /// <returns>The response from the Publish service method, as returned by AmazonSimpleNotificationService.</returns>
 /// 
 /// <exception cref="NotFoundException"/>
 /// <exception cref="PlatformApplicationDisabledException"/>
 /// <exception cref="EndpointDisabledException"/>
 /// <exception cref="AuthorizationErrorException"/>
 /// <exception cref="InternalErrorException"/>
 /// <exception cref="InvalidParameterException"/>
 public PublishResponse Publish(PublishRequest publishRequest)
 {
     IAsyncResult asyncResult = invokePublish(publishRequest, null, null, true);
     return EndPublish(asyncResult);
 }
Пример #31
0
 /// <summary>Execute NAnt task</summary>
 protected override void ExecuteTask()
 {
     var isArnSet = !String.IsNullOrEmpty(ARN);
     // Ensure our topic exists
     if (!DoesTopicExist())
         CreateTopic();
     // Ensure the ARN is set
     if (!isArnSet) {
         Project.Log(Level.Info, "Please set the SNS ARN!");
         return;
     }
     Project.Log(Level.Info, "Sending message to '{0}'.", Topic);
     using (Client) {
         try {
             var request = new PublishRequest {
                 TopicArn = ARN,
                 Subject = Subject,
                 Message = Message
             };
             var response = Client.Publish(request);
             if (response.IsSetPublishResult()) {
                 var result = response.PublishResult;
                 Project.Log(Level.Info, "Successfully published message ID: {0}", result.MessageId);
                 return;
             }
         } catch(AmazonS3Exception ex) {
             ShowError(ex);
         }
     }
     Project.Log(Level.Error, "Error publishing message!");
 }
        IAsyncResult invokePublish(PublishRequest request, AsyncCallback callback, object state, bool synchronized)
        {
            var marshaller = new PublishRequestMarshaller();
            var unmarshaller = PublishResponseUnmarshaller.Instance;

            return Invoke(request, callback, state, synchronized, marshaller, unmarshaller, signer);
        }