예제 #1
0
 // Notify observers when event occurs
 public void EventMessage(SNSRequest snsRequest)
 {
     foreach (var observer in _observers)
     {
         observer.OnNext(snsRequest);
     }
 }
예제 #2
0
        public async void OnNext(SNSRequest snsRequest)
        {
            foreach (var number in _options.Value.MessageRecipients)
            {
                var url = new StringBuilder(_options.Value.SmsEndpoint)
                          .Replace("$to", $"{number.Trim()}")
                          .Replace("$content", $"{snsRequest.Subject.Trim()} - {snsRequest.Message.Trim()}");
                _logger.LogInformation(url.ToString());
                var response =
                    await _httpClient.GetAsync(url.ToString());

                if (response.IsSuccessStatusCode)
                {
                    _logger.LogInformation($"sent message to {number} with {snsRequest.Message}");
                }
                else
                {
                    _logger.LogInformation($"could not send message to {number} with {snsRequest.Message}");
                }
            }
        }
예제 #3
0
        /**
         * Invoke request and return response
         */
        private T Invoke <T>(SNSRequest snsRequest, IDictionary <string, string> parameters)
        {
            string         actionName = parameters["Action"];
            T              response   = default(T);
            HttpStatusCode statusCode = default(HttpStatusCode);

            /* Add required request parameters */
            AddRequiredParameters(parameters);

            string queryString = AWSSDKUtils.GetParametersAsString(parameters);

            byte[] requestData = Encoding.UTF8.GetBytes(queryString);
            bool   shouldRetry = true;
            int    retries     = 0;
            int    maxRetries  = config.IsSetMaxErrorRetry() ? config.MaxErrorRetry : AWSSDKUtils.DefaultMaxRetry;

            do
            {
                string responseBody = null;
                IDictionary <string, string> headers = new Dictionary <string, string>();
                headers[AWSSDKUtils.UserAgentHeader] = config.UserAgent;
                ProcessRequestHandlers(snsRequest, headers);
                HttpWebRequest request = ConfigureWebRequest(requestData.Length, config, headers);

                /* Submit the request and read response body */
                try
                {
                    using (Stream requestStream = request.GetRequestStream())
                    {
                        requestStream.Write(requestData, 0, requestData.Length);
                    }
                    using (HttpWebResponse httpResponse = request.GetResponse() as HttpWebResponse)
                    {
                        if (httpResponse == null)
                        {
                            throw new WebException(
                                      "The Web Response for a successful request is null!",
                                      WebExceptionStatus.ProtocolError
                                      );
                        }

                        statusCode = httpResponse.StatusCode;
                        using (StreamReader reader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
                        {
                            responseBody = reader.ReadToEnd();
                        }
                    }

                    /* Perform response transformation */
                    if (responseBody.Trim().EndsWith(String.Concat(actionName, "Response>")))
                    {
                        responseBody = Transform(responseBody, this.GetType());
                    }
                    /* Attempt to deserialize response into <Action> Response type */
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    using (XmlTextReader sr = new XmlTextReader(new StringReader(responseBody)))
                    {
                        response = (T)serializer.Deserialize(sr);
                    }
                    shouldRetry = false;
                }
                /* Web exception is thrown on unsucessful responses */
                catch (WebException we)
                {
                    shouldRetry = false;
                    using (HttpWebResponse httpErrorResponse = we.Response as HttpWebResponse)
                    {
                        if (httpErrorResponse == null)
                        {
                            // Abort the unsuccessful request
                            request.Abort();
                            throw we;
                        }
                        statusCode = httpErrorResponse.StatusCode;
                        using (StreamReader reader = new StreamReader(httpErrorResponse.GetResponseStream(), Encoding.UTF8))
                        {
                            responseBody = reader.ReadToEnd();
                        }

                        // Abort the unsuccessful request
                        request.Abort();
                    }

                    if (statusCode == HttpStatusCode.InternalServerError ||
                        statusCode == HttpStatusCode.ServiceUnavailable)
                    {
                        shouldRetry = true;
                        PauseOnRetry(++retries, maxRetries, statusCode, we);
                    }
                    else
                    {
                        /* Attempt to deserialize response into ErrorResponse type */
                        try
                        {
                            using (XmlTextReader sr = new XmlTextReader(new StringReader(responseBody)))
                            {
                                XmlSerializer serializer    = new XmlSerializer(typeof(ErrorResponse));
                                ErrorResponse errorResponse = (ErrorResponse)serializer.Deserialize(sr);
                                Error         error         = errorResponse.Error[0];

                                /* Throw formatted exception with information available from the error response */
                                throw new AmazonSimpleNotificationServiceException(
                                          error.Message,
                                          statusCode,
                                          error.Code,
                                          error.Type,
                                          errorResponse.RequestId,
                                          errorResponse.ToXML()
                                          );
                            }
                        }
                        /* Rethrow on deserializer error */
                        catch (Exception e)
                        {
                            if (e is AmazonSimpleNotificationServiceException)
                            {
                                throw;
                            }
                            else
                            {
                                throw ReportAnyErrors(responseBody, statusCode);
                            }
                        }
                    }
                }

                /* Catch other exceptions, attempt to convert to formatted exception,
                 * else rethrow wrapped exception */
                catch (Exception)
                {
                    // Abort the unsuccessful request
                    request.Abort();
                    throw;
                }
            } while (shouldRetry);

            return(response);
        }
        /// <summary>
        /// The POST TelematicsNodeV2/Notifications/{telematicsNodeID}/Sns endpoint enrolls the Telematics Node for SNS notifications.
        /// Api partners with FDA permissions can include an Fda Configuration in the request to have the notification converted to a specified output preference.
        /// </summary>
        /// <param name="nodeId"></param>
        /// <param name="postNotificationSnsRequest"></param>
        /// <returns></returns>

        public async Task <NodeNotificationResponse> PostNotificationEnrollmentSns(int nodeId, SNSRequest postNotificationSnsRequest)
        {
            Dictionary <string, string> headers = ApiUtilities.BuildHeaders(UserKey, PublicKey, PrivateKey, $"telematicsnodev2/notifications/{nodeId}/sns", "POST");

            string json = JsonConvert.SerializeObject(postNotificationSnsRequest);

            StringContent content = new StringContent(json, Encoding.UTF8, "application/json");

            HttpResponseMessage response = await Api.Post($"telematicsnodev2/notifications/{nodeId}/sns", headers, content);

            NodeNotificationResponse result = await Api.DeserializeContent <NodeNotificationResponse>(response);

            return(result);
        }
예제 #5
0
 /// <summary>
 /// Accept incoming SNS Request
 /// </summary>
 /// <param name="payload">SNS Request Body</param>
 /// <returns></returns>
 public async Task Accept(SNSRequest payload)
 {
     var writer = _sChannel.Writer;
     await writer.WriteAsync(payload);
 }
예제 #6
0
        public static async Task <NodeNotificationResponse> EnrollSnsNotificationExample(int telematicsNode, SNSRequest snsRequest)
        {
            TelematicsV2             telematicsV2 = new TelematicsV2(publicKey, privateKey, userKey);
            NodeNotificationResponse response     = await telematicsV2.PostNotificationEnrollmentSns(telematicsNode, snsRequest);

            return(response);
        }