示例#1
0
        public static long SendMessage(this ISendMailService svc, Message message)
        {
            var req = new SendMessageRequest
            {
                Body = new SendMessageRequestBody
                {
                    message = message
                }
            };

            var resp = svc.SendMessage(req);

            return resp.Body.SendMessageResult;
        }
        public async Task <EmailResult> SendEmailAsync(EmailMessage emailMessage)
        {
            var sbQueueMessage = new StringBuilder();

            sbQueueMessage.AppendLine(emailMessage.EmailAddress);
            sbQueueMessage.AppendLine(emailMessage.Subject);
            sbQueueMessage.AppendLine(emailMessage.Body);

            var sendMessageRequest = new SendMessageRequest(_options.QueueUrl, sbQueueMessage.ToString());

            var response = await _sqsClient.SendMessageAsync(sendMessageRequest);

            return(new EmailResult()
            {
                Success = true,
                Details = response.MessageId
            });
        }
示例#3
0
        public void SendMessage_WithoutBody_ShouldThrowException()
        {
            const string queueName = "StandardQueue-EmptyMessageBodyTest";

            var sqsRequest          = new CreateQueueRequest(queueName);
            var createQueueResponse = _sqs.CreateQueue(sqsRequest);

            _queueUrl = createQueueResponse.QueueUrl;

            var sendMessageRequest = new SendMessageRequest
            {
                QueueUrl = _queueUrl
            };

            var exception = Assert.Throws <InvalidMessageContentsException>(() => _sqs.SendMessage(sendMessageRequest));

            Assert.Contains("InvalidMessageContents", exception.ErrorCode);
        }
示例#4
0
        /// <summary>
        /// Method sender to connect and send the queue to azure.
        /// </summary>
        /// <typeparam name="T">Type of message to send</typeparam>
        /// <param name="message">Object of message to send</param>
        /// <returns>The task of Process topic</returns>
        public override async Task SendToQueue(object message)
        {
            SqsSnsConfiguration config    = GetConnection(_queueName);
            AmazonSQSClient     sqsClient = new AmazonSQSClient(config.AwsAccessKeyId, config.AwsSecretAccessKey);

            string queueURL = sqsClient.CreateQueueAsync(new CreateQueueRequest
            {
                QueueName = _queueName
            }).Result.QueueUrl;
            var sendMessageRequest = new SendMessageRequest
            {
                QueueUrl               = queueURL,
                MessageBody            = message.ToStringCamelCase(),
                MessageGroupId         = Guid.NewGuid().ToString("N"),
                MessageDeduplicationId = Guid.NewGuid().ToString("N")
            };
            var sendMessageResponse = await sqsClient.SendMessageAsync(sendMessageRequest);
        }
示例#5
0
        private static string SendMessage(string message)
        {
            var awsCreds = new BasicAWSCredentials(AccessKey, SecretKey);
            var config   = new AmazonSQSConfig
            {
                ServiceURL = ServiceUrl,
                //RegionEndpoint = RegionEndpoint.USEast1
            };
            var amazonSqsClient    = new AmazonSQSClient(awsCreds, config);
            var sendMessageRequest = new SendMessageRequest
            {
                QueueUrl    = QueueUrl,
                MessageBody = message
            };
            var sendMessageResponse = amazonSqsClient.SendMessageAsync(sendMessageRequest);

            return(sendMessageResponse.Result.SequenceNumber);
        }
示例#6
0
        /// <summary>
        /// Post a message to the server
        /// </summary>
        public override Task <SendMessageResponse> SendMessage(
            SendMessageRequest request,
            ServerCallContext context)
        {
            System.Console.WriteLine(
                $"{context.Host} sent message Name={request.From}; Text={request.Text}");

            // first we map the received protobuffer 'model' to the local data 'model'
            var msg = new ChatMessage(request.Text, request.From);

            // now push the new message into the repository
            var repo = new Repositories.MessageRepository();

            repo.PostMessage(msg);

            // finally we return the expected response to the client
            return(Task.FromResult(new SendMessageResponse()));
        }
示例#7
0
        public async Task<IActionResult> Send([FromBody] SendMessageRequest request)
        {
            if (!ModelState.IsValid)
                return BadRequest();

            if ((!await _userService.isUserNameExist(request.SenderName) || (!await _userService.isUserNameExist(request.ReceiverName))))
                return NotFound("There is no such a username");

            if (await _userService.isBlocked(new BlockUserRequest { KickerName = request.ReceiverName, BlockedName = request.SenderName }))
                return BadRequest("You cannot send message to this user");

            var success = await _service.Send(request);

            if (success == 0)
                return BadRequest("An error occured");

            return Ok();
        }
        //public static async Task<SendMessageBatchResponse> PushToSqsBatchAsync(this IEnumerable<Tuple<string, string>> messageRequestEntries, string queueUrl)
        //{
        //    if (messageRequestEntries == null) return null;

        //    var requests = messageRequestEntries
        //        .Select(entry =>
        //        {
        //            var requestId = entry.Item1;
        //            var messageBody = entry.Item2;
        //            return new SendMessageBatchRequestEntry(requestId, messageBody);
        //        }).ToList();

        //    if (requests.Count > 10)
        //    {
        //        throw new ArgumentOutOfRangeException($"[SendMessageBatchAsync] Number of messages exceeded max allowed by SQS batch 10. Your request batch contains {requests.Count}");
        //    }

        //    if (!requests.Any()) return null;

        //    var response = await AmazonSqsClientSingleton.SendMessageBatchAsync(queueUrl, requests);
        //    return response;
        //}

        //public static async Task<IEnumerable<KeyValuePair<string, HttpStatusCode>>> PushToSqsAsync(this string messageBody, string queueUrl, IEnumerable<KeyValuePair<string, string>> messageAttributes)
        //{
        //    var sendMessageRequest = new SendMessageRequest(queueUrl, messageBody);

        //    if (messageAttributes != null)
        //    {
        //        foreach (var pair in messageAttributes)
        //        {
        //            sendMessageRequest.MessageAttributes.Add(pair.Key, new MessageAttributeValue() { DataType = "String", StringValue = pair.Value });
        //        }
        //    }

        //    var response = await AmazonSqsClientSingleton.SendMessageAsync(sendMessageRequest);
        //    var result = new[] { new KeyValuePair<string, HttpStatusCode>(response.MessageId, response.HttpStatusCode) };
        //    return result;
        //}

        public static async Task <Tuple <HttpStatusCode, string> > PushToSqsAsync(this string messageBody, AmazonSQSClient client, string queueUrl, int?delayQueueInSeconds = null)
        {
            try
            {
                var sendMessageRequest = new SendMessageRequest(queueUrl, messageBody);
                if (delayQueueInSeconds.HasValue)
                {
                    sendMessageRequest.DelaySeconds = delayQueueInSeconds.Value;
                }
                var response = await client.SendMessageAsync(sendMessageRequest);

                return(Tuple.Create(response.HttpStatusCode, $"MessageID:{response.MessageId}"));
            }
            catch (AmazonSQSException ex)
            {
                return(Tuple.Create(HttpStatusCode.BadRequest, $"RequestID={ex.RequestId}\nError={ex}"));
            }
        }
示例#9
0
        public virtual List <IMailResponse> Send(MailAttributes mailAttributes)
        {
            var mail     = GenerateProspectiveMailMessage(mailAttributes);
            var response = new List <IMailResponse>();
            var request  = new SendMessageRequest(mail);

            var resp = AsyncHelpers.RunSync(() => _client.SendMessage(request));

            response.AddRange(resp.Select(result => new MandrillMailResponse
            {
                Email        = result.Email,
                Status       = MandrillMailResponse.GetProspectiveStatus(result.Status.ToString()),
                RejectReason = result.RejectReason,
                Id           = result.Id
            }));

            return(response);
        }
示例#10
0
        public async Task <SendMessageResponse> SendToSqsAsync(object messageBody, bool log = true)
        {
            var request = new SendMessageRequest
            {
                QueueUrl = "https://sqs.us-east-1.amazonaws.com/105029661252/start-checkout", // Leandro
                // QueueUrl = "https://sqs.us-east-1.amazonaws.com/106868270748/start-checkout", // Carlos
                MessageBody = JsonUtilities.Serialize(messageBody)
            };

            var response = await _amazonSqsClient.SendMessageAsync(request);

            if (log && !string.IsNullOrEmpty(response.MessageId))
            {
                Log.Information("Sent to SQS: {data}", messageBody);
            }

            return(response);
        }
        private ServiceBusResponse sendMessage(SendMessageRequest request)
        {
            if (authenticated == false)
            {
                return(new ServiceBusResponse(false, "Error: You must be logged in to use the send message functionality."));
            }

            // This class indicates to the request function where
            SendOptions sendOptions = new SendOptions();

            sendOptions.SetDestination("Chat");

            // The Request<> funtion itself is an asynchronous operation. However, since we do not want to continue execution until the Request
            // function runs to completion, we call the ConfigureAwait, GetAwaiter, and GetResult functions to ensure that this thread
            // will wait for the completion of Request before continueing.
            return(requestingEndpoint.Request <ServiceBusResponse>(request, sendOptions).
                   ConfigureAwait(false).GetAwaiter().GetResult());
        }
示例#12
0
        public void TestSendMessageWithDelay()
        {
            // Create the queue
            queueName = setQueueName();
            queueURL  = createQueueURLAsync(queueName);

            // Set the request
            var request = new SendMessageRequest(queueURL.Result.ToString(), messageBody);

            // Set the delay to 5 seconds
            request.DelaySeconds = 5;

            // Get the response when sending the message request
            var response = sqsClient.SendMessageAsync(request);

            // Verify the message body is correct between the request and the response
            ValidateMD5(request.MessageBody, response.Result.MD5OfMessageBody);
        }
        public string Send(SendMessageRequest request)
        {
            if (request.MessageBody.Equals(FakeBatchItemFailString, StringComparison.OrdinalIgnoreCase))
            {
                return(null);
            }

            var newItem = new FakeSqsQueueItem
            {
                Body              = request.MessageBody,
                Status            = FakeSqsItemStatus.Queued,
                MessageAttributes = request.MessageAttributes,
            };

            qItems.Enqueue(newItem);

            return(newItem.MessageId);
        }
        /// <summary>
        /// </summary>
        /// <param name="message"></param>
        internal void SendMessage(Message message)
        {
            var request = new SendMessageRequest
            {
                QueueUrl     = message.Queue.Url,
                MessageBody  = message.Body,
                DelaySeconds = message.DelaySeconds
            };
            SendMessageResponse response = _sqsClient.SendMessage(request);

            if (response.IsSetSendMessageResult())
            {
                if (response.SendMessageResult.IsSetMessageId())
                {
                    message.AwsAssignedId = response.SendMessageResult.MessageId;
                }
            }
        }
示例#15
0
        internal void SendLoggingPayload(LoggingPayload loggingPayload)
        {
#if DEBUG
            return;
#endif

            try
            {
                string payload = Serializer.SerializeToJson(loggingPayload);
                var    message = new SendMessageRequest(AnalyticsQueueUri, payload);

                _client.SendMessageAsync(message);
            }
            catch (Exception ex)
            {
                Logger.Warn("Problem posting logging", ex);
            }
        }
示例#16
0
        public IActionResult SendMessage([FromBody] string request)
        {
            SendMessageRequest inputRequest = JsonConvert.DeserializeObject <SendMessageRequest>(request);
            ApiType            apiType      = (ApiType)Enum.Parse(typeof(ApiType), inputRequest.ApiName);

            if (apiType == ApiType.WeboxAppApi)
            {
                WeboxappServiceBridge serviceBridge = new WeboxappServiceBridge();
                serviceBridge.SendWhatsAppMessage(inputRequest);
            }
            else if (apiType == ApiType.ChatApi)
            {
                ChatApiServiceBridge serviceBridge = new ChatApiServiceBridge();
                serviceBridge.SendWhatsAppMessage(inputRequest);
            }

            return(Ok("received : " + request));
        }
示例#17
0
        public async Task <string> Publish(IEventBusMessage message)
        {
            var request = new SendMessageRequest
            {
                QueueUrl    = QueueUrl,
                MessageBody = JsonConvert.SerializeObject(message)
            };

            if (QueueUrl.EndsWith(".fifo"))
            {
                request.MessageDeduplicationId = message.DeduplicationId;
                request.MessageGroupId         = "Default";
            }

            var response = await Client.SendMessageAsync(request);

            return(response.MessageId);
        }
示例#18
0
        public void SendMessage(string url, Message sqsMessage)
        {
            try
            {
                var sendMessageRequest = new SendMessageRequest
                {
                    QueueUrl    = url,
                    MessageBody = JsonConvert.SerializeObject(sqsMessage.Body),
                    // MessageAttributes = attributes.ToDictionary(item => item.Key, item => (MessageAttributeValue)item.Value),
                };
                var sqsSendMessage = Client.SendMessageAsync(sendMessageRequest).Result;
            }

            catch (AmazonSQSException ex)
            {
                throw new Exception(ex.Message);
            }
        }
示例#19
0
 public void Send(SqsMessage pQueue)
 {
     try
     {
         AmazonSQSClient    sqs           = SqsConfig.Initialize;
         SendMessageRequest requestToSend = new SendMessageRequest
         {
             MessageBody       = pQueue.MessageBody,
             MessageAttributes = pQueue.MessageAttributes,
             QueueUrl          = pQueue.QueueUrl
         };
         sqs.SendMessage(requestToSend);
     }
     catch (Exception oException)
     {
         throw oException;
     }
 }
示例#20
0
        public void Push <T>(T item)
        {
            var json = JsonConvert.SerializeObject(item);

            using (var client = _client)
            {
                var req = new SendMessageRequest
                {
                    MessageBody = json,
                    QueueUrl    = _queueUrl
                };
                var sendMessageResult = client.SendMessageAsync(req).Result;
                if (sendMessageResult.HttpStatusCode != HttpStatusCode.OK)
                {
                    throw new Exception($"unable to queue message for url: {_queueUrl}");
                }
            }
        }
示例#21
0
        /// <summary>
        /// Puts a message on the queue
        /// </summary>
        /// <param name="message">The message to be put on the queue</param>
        /// <param name="queueName">The name of the queue</param>
        /// <param name="messageAttributes">A dictionary of string values to include in the message attributes</param>
        /// <returns></returns>
        public async Task <string> SendMessageAsync(string message, string queueName, Dictionary <string, string> messageAttributes = null)
        {
            var queueUrl = await GetQueueUrlAsync(queueName);

            var request = new SendMessageRequest
            {
                QueueUrl       = queueUrl,
                MessageBody    = message,
                MessageGroupId = queueName.EndsWith(".fifo") ? queueUrl : null
            };

            if (messageAttributes != null)
            {
                var sqsMessageAttributes = messageAttributes.ToDictionary(attribute => attribute.Key, attribute => new MessageAttributeValue {
                    StringValue = attribute.Value, DataType = "String"
                });
                request.MessageAttributes = sqsMessageAttributes;
            }

            SendMessageResponse response = null;
            var retryCounter             = 0;

            while (response == null)
            {
                try
                {
                    response = await _client.SendMessageAsync(request);
                }
                catch (AmazonSQSException e)
                {
                    if (e.Message.EndsWith("Throttled") && retryCounter < 10)
                    {
                        retryCounter += 1;
                        await Task.Delay(retryCounter * 3);
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            return(response.MessageId);
        }
示例#22
0
        public bool SendMessage(User user, SendMessageRequest request)
        {
            var chatRoom = chatRoomDao.FindByID(request.ChatRoomID);

            if (chatRoom == null)
            {
                return(false);
            }
            var invalidUser = user != chatRoom.User1 && user != chatRoom.User2;

            if (invalidUser)
            {
                return(false);
            }
            var model = new Message
            {
                ChatRoom     = chatRoom,
                Date         = Constant.SERVER_TIME.Ticks,
                MessageOwner = user,
                Read         = false,
                Text         = request.Text,
                Type         = (MessageType)request.Type,
                Contents     = request.Contents
            };
            var message = messageDao.InsertAndGet(model);

            if (message != null)
            {
                if (chatRoom.MessagesRef == null)
                {
                    chatRoom.MessagesRef = new List <MongoDBRef>();
                }
                chatRoom.MessagesRef.Add(message.ToRef());
                chatRoomDao.Update(chatRoom, new string[] { "MessagesRef" });

                // TODO send notif
                var receiver = user == chatRoom.User1 ? chatRoom.User2 : chatRoom.User1;
                return(true);
            }
            else
            {
                return(false);
            }
        }
示例#23
0
        public SendMessageReply SendMessage(SendMessageRequest r)
        {
            if (r.Content.Length > 256)
            {
                return(SendMessageReply.CreateTooLong());
            }
            if (r.Content == "login")
            {
                SessionContext.RaiseAuthenticated();
                return(SendMessageReply.CreateSuccess());
            }
            else if (r.Content == "secure")
            {
                //生成测试用确定Key
                var ServerToken = Enumerable.Range(0, 41).Select(i => (Byte)(i)).ToArray();
                var ClientToken = Enumerable.Range(0, 41).Select(i => (Byte)(40 - i)).ToArray();
                SessionContext.RaiseSecureConnectionRequired(new SecureContext {
                    ServerToken = ServerToken, ClientToken = ClientToken
                });
                return(SendMessageReply.CreateSuccess());
            }
            SessionContext.SendMessageCount += 1;
            var Sessions = ServerContext.Sessions.ToList();

            foreach (var rc in Sessions)
            {
                rc.SessionLock.EnterWriteLock();
                try
                {
                    rc.ReceivedMessageCount += 1;
                    if (rc.EventPump != null)
                    {
                        rc.EventPump.MessageReceived(new MessageReceivedEvent {
                            Content = r.Content
                        });
                    }
                }
                finally
                {
                    rc.SessionLock.ExitWriteLock();
                }
            }
            return(SendMessageReply.CreateSuccess());
        }
示例#24
0
        static void Main(string[] args)
        {
            Console.WriteLine("Creating Aws Queue...........");

            Study s1 = new Study
            {
                StudyName               = "s1",
                StudyStartDate          = "01 Jan 2010",
                EstimatedCompletionDate = "05 Jan 2019",
                ProtocolID              = "ProtocolID1",
                StudyGroup              = "Groupd1",
                Phase               = "Phase1",
                PrimaryIndication   = "Indication 1",
                SecondaryIndication = "Secondary Indication1"
            };


            IAmazonSQS sqs      = new AmazonSQSClient(RegionEndpoint.APSouth1);
            var        queueUrl = "https://sqs.ap-south-1.amazonaws.com/066325793814/Cytelpoc.fifo";
            //var sqsRequest = new CreateQueueRequest()
            //{
            //    QueueName = "CytelSimulationQueueTest",
            //};
            //var createQueueResponse = sqs.CreateQueueAsync(sqsRequest).Result;
            //var myQueueQurl = createQueueResponse.QueueUrl;
            //var listQueuesRequest = new ListQueuesRequest();
            //var listQueuesResponse = sqs.ListQueuesAsync(listQueuesRequest);
            //Console.WriteLine("List of Queues");
            //foreach(var queueUrl in listQueuesResponse.Result.QueueUrls)
            //{
            //    Console.WriteLine($"Queue Url: {queueUrl}");
            //}

            var sqsmessageRequest = new SendMessageRequest()
            {
                QueueUrl               = queueUrl,
                MessageBody            = JsonConvert.SerializeObject(s1),
                MessageGroupId         = "CytelMessages1",
                MessageDeduplicationId = "CytemDeduplication66"
            };

            sqs.SendMessageAsync(sqsmessageRequest);
            Console.ReadLine();
        }
        public async Task SendSQSMessage(string content)
        {
            try
            {
                Console.WriteLine("===========================================");
                Console.WriteLine("Getting Started with Amazon SQS");
                Console.WriteLine("===========================================\n");

                //Creating a queue
                //Console.WriteLine("Create a queue called MyQueue.\n");
                //CreateQueueRequest sqsRequest = new CreateQueueRequest();
                //sqsRequest.QueueName = "MyQueue";
                //CreateQueueResponse createQueueResponse = await sqs.CreateQueueAsync(sqsRequest);
                //String myQueueUrl = "https://sqs.ap-southeast-1.amazonaws.com/783560535431/MyQueue1";
                //myQueueUrl = createQueueResponse.QueueUrl;

                //Confirming the queue exists
                ListQueuesRequest  listQueuesRequest  = new ListQueuesRequest();
                ListQueuesResponse listQueuesResponse = await sqs.ListQueuesAsync(listQueuesRequest);

                Console.WriteLine("Printing list of Amazon SQS queues.\n");
                foreach (String queueUrl in listQueuesResponse.QueueUrls)
                {
                    Console.WriteLine("  QueueUrl: {0}", queueUrl);
                }
                Console.WriteLine();

                //Sending a message
                Console.WriteLine("Sending a message to MyQueue.\n");
                SendMessageRequest sendMessageRequest = new SendMessageRequest();
                sendMessageRequest.QueueUrl    = myQueueUrl; //URL from initial queue creation
                sendMessageRequest.MessageBody = content;
                await sqs.SendMessageAsync(sendMessageRequest);
            }
            catch (AmazonSQSException ex)
            {
                Console.WriteLine("Caught Exception: " + ex.Message);
                Console.WriteLine("Response Status Code: " + ex.StatusCode);
                Console.WriteLine("Error Code: " + ex.ErrorCode);
                Console.WriteLine("Error Type: " + ex.ErrorType);
                Console.WriteLine("Request ID: " + ex.RequestId);
            }
            return;
        }
示例#26
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    var request = new ReceiveMessageRequest
                    {
                        QueueUrl            = _exampleQueueUrl,
                        MaxNumberOfMessages = 10,

                        WaitTimeSeconds = 5
                    };

                    var result = await _sqs.ReceiveMessageAsync(request);

                    if (result.Messages.Any())
                    {
                        foreach (var message in result.Messages)
                        {
                            // Some Processing code would live here
                            _logger.LogInformation("Processing Message: {message} | {time}", message.Body, DateTimeOffset.Now);

                            var processedMessage = new ProcessedMessage(message.Body);

                            var sendRequest = new SendMessageRequest(_processedMessageQueueUrl, JsonConvert.SerializeObject(processedMessage));

                            var sendResult = await _sqs.SendMessageAsync(sendRequest, stoppingToken);

                            if (sendResult.HttpStatusCode == System.Net.HttpStatusCode.OK)
                            {
                                var deleteResult = await _sqs.DeleteMessageAsync(_exampleQueueUrl, message.ReceiptHandle);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    _logger.LogError(e.InnerException.ToString());
                }

                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            }
        }
示例#27
0
        public async Task <GenericResponse> CreateSQSMessage(string messageBody, string filePath)
        {
            var result = new GenericResponse();

            try
            {
                Console.WriteLine($"about to create the chaptersQueue");
                var sqsRequest = new CreateQueueRequest {
                    QueueName = "ChaptersInQueue"
                };
                var createQueueResponse = _sqs.CreateQueueAsync(sqsRequest).Result;
                var myQueueUrl          = createQueueResponse.QueueUrl;

                //foreach (var url in listQueueResponse.Result.QueueUrls)
                //{
                //    Console.WriteLine($"{url}");
                //}

                var sqsMessageReq = new SendMessageRequest();
                sqsMessageReq.QueueUrl    = myQueueUrl;
                sqsMessageReq.MessageBody = messageBody;

                await _sqs.SendMessageAsync(sqsMessageReq);

                Console.WriteLine($"Message was sent successfully to SQS. \n");
                result.Text   = messageBody;
                result.Value  = myQueueUrl;
                result.Status = "OK";
            }
            catch (AmazonSQSException sqsEx)
            {
                result.Text   = sqsEx.Message;
                result.Value  = sqsEx.StackTrace;
                result.Status = "ERROR";
            }
            catch (Exception ex)
            {
                result.Text   = ex.Message;
                result.Value  = ex.StackTrace;
                result.Status = "ERROR";
            }

            return(result);
        }
        public async Task OnUserRegistered(UserDto user)
        {
            var str = JsonSerializer.Serialize(sqs.Config, new JsonSerializerOptions()
            {
                WriteIndented = true
            });
            var tmp = sqs.Config.DetermineServiceURL();

            logger.LogInformation(str);
            logger.LogInformation(tmp);
            logger.LogInformation(queueUrl);
            var body    = JsonSerializer.Serialize(user);
            var request = new SendMessageRequest
            {
                QueueUrl    = queueUrl,
                MessageBody = body
            };
            var response = await sqs.SendMessageAsync(request);
        }
        public HttpResponseMessage sendMessage(string user, [FromBody] SendMessageRequest request)
        {
            if (UserDAO.Instance.isExists(user))
            {
                User u = UserDAO.Instance.findByUsername(user);

                if (UserDAO.Instance.isExists(request.receiver))
                {
                    //Timestamp prüfen
                    Double   unixtimeDouble = Convert.ToDouble(request.timestamp);
                    DateTime timestamp      = Util.Converter.UnixTimeStampToDateTime(unixtimeDouble)
                                              .AddMinutes(5);

                    //Timestamp prüfen
                    if (DateTime.Now > timestamp)
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadRequest, "Timestamp ungültig"));
                    }

                    //Inhalt mit der Signatur prüfen
                    string publickey = Util.Converter.Base64StringToString(u.pubkey);
                    if (!VerifyLogic.verifyOuterEnvelope(request.inner_envelope, request.timestamp, request.receiver, request.sig_service, publickey))
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadRequest, "Signatur ungültig"));
                    }

                    User sender   = UserDAO.Instance.findByUsername(user);
                    User receiver = UserDAO.Instance.findByUsername(request.receiver);

                    Message msg = new Message();
                    msg.cipher            = request.inner_envelope.cipher;
                    msg.iv                = request.inner_envelope.iv;
                    msg.key_recipient_enc = request.inner_envelope.key_recipient_enc;
                    msg.sig_recipient     = request.inner_envelope.sig_recipient;
                    msg.sender            = user;

                    UserDAO.Instance.addMessage(receiver, msg);

                    return(new HttpResponseMessage(HttpStatusCode.OK));
                }
            }
            return(new HttpResponseMessage(HttpStatusCode.BadRequest));
        }
示例#30
0
        public async Task <SendMessageResponse> SendMessageAsync(SendMessageRequest request)
        {
            using (var client = new HttpClient())
            {
                var requestJson = JsonConvert.SerializeObject(
                    new Data.Json.MessageRequest.Rootobject
                {
                    text = request.Message,
                    to   = request.PhoneNumbers
                });

                try
                {
                    var response = await client.SendAsync(GetHttpRequestMessage(SendMessageURL, HttpMethod.Post, new StringContent(requestJson)));

                    if (response.StatusCode != HttpStatusCode.Accepted && response.StatusCode != HttpStatusCode.OK)
                    {
                        throw new SmsKitException($"Request failed. Received HTTP {response.StatusCode}");
                    }

                    var result = await response.Content.ReadAsStringAsync();

                    var resultObject = JsonConvert.DeserializeObject <Data.Json.MessageResponse.Rootobject>(result);

                    var jsonMessages = resultObject.data.message.Select(message => new Message
                    {
                        APIMessageID = message.apiMessageId,
                        To           = message.to
                    }).ToArray();

                    return(new SendMessageResponse
                    {
                        Result = result,
                        Success = true,
                        Messages = jsonMessages
                    });
                }
                catch (Exception ex)
                {
                    throw new SmsKitException($"Request failed. {ex.Message}");
                }
            }
        }
示例#31
0
        public async Task Long_Message_Async_S3KeyProvider_Is_Used_If_Configured()
        {
            var mockS3Provider = new Mock <IS3KeyProvider>();

            mockS3Provider.Setup(m => m.GenerateName()).Returns("CustomPrefix" + Guid.NewGuid().ToString("N"));

            var extendedClient = new AmazonSQSExtendedClient(
                sqsMock.Object,
                new ExtendedClientConfiguration()
                .WithLargePayloadSupportEnabled(s3Mock.Object, S3_BUCKET_NAME)
                .WithS3KeyProvider(mockS3Provider.Object));
            var body           = GenerateLongString(SQSExtendedClientConstants.DEFAULT_MESSAGE_SIZE_THRESHOLD + 1);
            var messageRequest = new SendMessageRequest(SQS_QUEUE_NAME, body);
            await extendedClient.SendMessageAsync(messageRequest);

            mockS3Provider.Verify(s => s.GenerateName(), Times.Once);
            s3Mock.Verify(s => s.PutObjectAsync(It.Is <PutObjectRequest>(r => r.Key.StartsWith("CustomPrefix")), It.IsAny <CancellationToken>()), Times.Once);
            sqsMock.Verify(s => s.SendMessageAsync(It.Is <SendMessageRequest>(r => MessagePointerIsCorrect(r.MessageBody, "CustomPrefix") && LargePayloadAttributeIsAdded(r.MessageAttributes)), It.IsAny <CancellationToken>()), Times.Once);
        }
示例#32
0
        private Task RunSendQueue(CancellationToken cancelToken)
        {
            return Task.Run(async () =>
            {
                try
                {
                    while (!cancelToken.IsCancellationRequested)
                    {
                        Message msg;
                        while (_pendingSends.TryDequeue(out msg))
                        {
                            DecrementCount();
                            string text;
                            if (_pendingSendsByNonce.TryRemove(msg.Nonce, out text)) //If it was deleted from queue, this will fail
                            {
                                try
                                {
                                    msg.RawText = text;
                                    msg.Text = msg.Resolve(text);

                                    var request = new SendMessageRequest(msg.Channel.Id)
                                    {
                                        Content = msg.RawText,
                                        Nonce = msg.Nonce.ToString(),
                                        IsTTS = msg.IsTTS
                                    };
#pragma warning disable
                                    _rest.Send(request).ContinueWith((t, msgObj) =>
                                    {
                                        var localMsg = msgObj as Message;
                                        if (t.Status == TaskStatus.RanToCompletion)
                                        {
                                            var x = t.Result;
                                            localMsg.State = MessageState.Normal;
                                            localMsg.Id = x.Id;
                                            localMsg.Update(x);
                                        }
                                        else
                                        {
                                            localMsg.State = MessageState.Failed;
                                            _logger.Error($"Failed to send message to {localMsg.Channel.Path}", t.Exception);
                                        }
                                    }, msg);
#pragma warning restore
                                }
                                catch (Exception ex)
                                {
                                    msg.State = MessageState.Failed;
                                    _logger.Error($"Failed to send message to {msg.Channel.Path}", ex);
                                }
                            }
                        }
                        await Task.Delay(Discord.DiscordConfig.MessageQueueInterval).ConfigureAwait(false);
                    }
                }
                catch (OperationCanceledException) { }
            });
        }
示例#33
0
 public SendMessageResponse SendMessage(SendMessageRequest sendMessageRequest)
 {
     return SendMessageResponse.Parse(ExecuteAction(sendMessageRequest));
 }
示例#34
0
文件: ChannelImpl.cs 项目: fry/d3
		public override void SendMessage(Google.ProtocolBuffers.IRpcController controller, SendMessageRequest request, Action<bnet.protocol.NoData> done) {
			throw new NotImplementedException();
		}
示例#35
0
        internal Task Run(CancellationToken cancelToken, int interval)
        {
            _nextWarning = WarningStart;
            return Task.Run(async () =>
            {
                MessageQueueItem queuedMessage;

                while (!cancelToken.IsCancellationRequested)
                {
                    await Task.Delay(interval).ConfigureAwait(false);

                    Count = _pending.Count;
                    if (Count >= _nextWarning)
                    {
                        _nextWarning *= 2;
                        _logger.Warning($"Queue is backed up, currently at {Count} messages.");
                    }
                    else if (Count < WarningStart) //Reset once the problem is solved
                        _nextWarning = WarningStart;

                    while (_pending.TryDequeue(out queuedMessage))
                    {
                        try
                        {
                            if (queuedMessage.Id == 0)
                            {
                                var request = new SendMessageRequest(queuedMessage.ChannelId)
                                {
                                    Content = queuedMessage.Text,
                                    Nonce = GenerateNonce().ToIdString(),
                                    IsTTS = queuedMessage.IsTTS
                                };
                                await _client.ClientAPI.Send(request).ConfigureAwait(false);
                            }
                            else
                            {
                                var request = new UpdateMessageRequest(queuedMessage.ChannelId, queuedMessage.Id)
                                {
                                    Content = queuedMessage.Text
                                };
                                await _client.ClientAPI.Send(request).ConfigureAwait(false);
                            }
                        }
                        catch (WebException) { break; }
                        catch (HttpException) { /*msg.State = MessageState.Failed;*/ }
                        catch (Exception ex) { _logger.Error(ex); }
                    }
                }
            });
        }
示例#36
0
 private Task RunSendQueue(CancellationToken cancelToken)
 {
     return Task.Run(async () =>
     {
         try
         {
             while (!cancelToken.IsCancellationRequested)
             {
                 Message msg;
                 while (_pendingSends.TryDequeue(out msg))
                 {
                     DecrementCount();
                     string text;
                     if (_pendingSendsByNonce.TryRemove(msg.Nonce, out text)) //If it was deleted from queue, this will fail
                     {
                         try
                         {
                             msg.RawText = text;
                             msg.Text = msg.Resolve(text);
                             var request = new SendMessageRequest(msg.Channel.Id)
                             {
                                 Content = msg.RawText,
                                 Nonce = msg.Nonce.ToString(),
                                 IsTTS = msg.IsTTS
                             };
                             var response = await _rest.Send(request).ConfigureAwait(false);
                             msg.State = MessageState.Normal;
                             msg.Id = response.Id;
                             msg.Update(response);
                         }
                         catch (Exception ex)
                         {
                             msg.State = MessageState.Failed;
                             _logger.Error($"Failed to send message to {msg.Channel.Path}", ex);
                         }
                     }
                 }
                 await Task.Delay(Discord.DiscordConfig.MessageQueueInterval).ConfigureAwait(false);
             }
         }
         catch (OperationCanceledException) { }
     });
 }
示例#37
0
 SendMessageResponse ISendMailService.SendMessage(SendMessageRequest request)
 {
     return _client.Invoke(s => s.SendMessage(request));
 }
示例#38
0
 private RemotingRequest BuildSendMessageRequest(Message message, int queueId, BrokerConnection brokerConnection)
 {
     var request = new SendMessageRequest { Message = message, QueueId = queueId };
     request.Message.ProducerAddress = brokerConnection.RemotingClient.LocalEndPoint.ToAddress();
     var data = MessageUtils.EncodeSendMessageRequest(request);
     if (data.Length > Setting.MessageMaxSize)
     {
         throw new Exception("Message size cannot exceed max message size:" + Setting.MessageMaxSize);
     }
     return new RemotingRequest((int)BrokerRequestCode.SendMessage, data);
 }
示例#39
0
 public void Send(SendMessageRequest request)
 {
     // send the message
 }
示例#40
0
        private async Task<Message> SendMessageInternal(string text, bool isTTS)
        {
            if (text.Length > DiscordConfig.MaxMessageSize)
                throw new ArgumentOutOfRangeException(nameof(text), $"Message must be {DiscordConfig.MaxMessageSize} characters or less.");

            if (Client.Config.UseMessageQueue)
                return Client.MessageQueue.QueueSend(this, text, isTTS);
            else
            {
                var request = new SendMessageRequest(Id)
                {
                    Content = text,
                    Nonce = null,
                    IsTTS = isTTS
                };
                var model = await Client.ClientAPI.Send(request).ConfigureAwait(false);
                var msg = AddMessage(model.Id, IsPrivate ? Client.PrivateUser : Server.CurrentUser, model.Timestamp.Value);
                msg.Update(model);
                return msg;
            }
        }
        public IEnumerable<Message> SendMessage(IEnumerable<string> MatchIds, string message)
        {
            var request = new SendMessageRequest(message);
            string requestSerialized = JsonConvert.SerializeObject(request);
            UTF8Encoding utf8Encoder = new UTF8Encoding();
            byte[] requestedEncoded = utf8Encoder.GetBytes(requestSerialized);
            string baseUri = TinderURLConstructor.GetUrl(TinderCalls.SendMessage);
            List<Message> messages = new List<Message>();

            foreach (string matchId in MatchIds)
            {
                string uri = baseUri + matchId;

                using (WebClient wc = WebClientFactory.Create())
                {
                    string response = utf8Encoder.GetString(wc.UploadData(uri, requestedEncoded));
                    Message msg = JsonConvert.DeserializeObject<Message>(response);
                    messages.Add(msg);
                }
            }

            return messages;
        }
示例#42
0
 internal async Task Send(Message msg)
 {
     if (_pendingSends.TryRemove(msg.Nonce, out msg)) //Remove it from pending
     {
         try
         {
             var request = new SendMessageRequest(msg.Channel.Id)
             {
                 Content = msg.RawText,
                 Nonce = msg.Nonce.ToString(),
                 IsTTS = msg.IsTTS
             };
             var response = await _client.ClientAPI.Send(request).ConfigureAwait(false);
             msg.Id = response.Id;
             msg.Update(response);
             msg.State = MessageState.Normal;
         }
         catch (Exception ex) { msg.State = MessageState.Failed; _logger.Error("Failed to send message", ex); }
     }
 }
示例#43
0
 public override void SendMessage(IRpcController controller, SendMessageRequest request, Action<NoData> done)
 {
     ProtoOutputBuffer.Write(request.GetType(), request.ToString());
 }
示例#44
0
        public static byte[] EncodeSendMessageRequest(SendMessageRequest request)
        {
            //queueId
            var queueIdBytes = BitConverter.GetBytes(request.QueueId);

            //messageCode
            var messageCodeBytes = BitConverter.GetBytes(request.Message.Code);

            //createdTimeTicks
            var messageCreatedTimeTicksBytes = BitConverter.GetBytes(request.Message.CreatedTime.Ticks);

            //topic
            var topicBytes = Encoding.UTF8.GetBytes(request.Message.Topic);
            var topicLengthBytes = BitConverter.GetBytes(topicBytes.Length);

            //tag
            var tagBytes = EmptyBytes;
            if (!string.IsNullOrEmpty(request.Message.Tag))
            {
                tagBytes = Encoding.UTF8.GetBytes(request.Message.Tag);
            }
            var tagLengthBytes = BitConverter.GetBytes(tagBytes.Length);

            //producerAddress
            var producerAddressBytes = Encoding.UTF8.GetBytes(request.Message.ProducerAddress);
            var producerAddressLengthBytes = BitConverter.GetBytes(producerAddressBytes.Length);

            return Combine(
                queueIdBytes,
                messageCodeBytes,
                messageCreatedTimeTicksBytes,
                topicLengthBytes,
                topicBytes,
                tagLengthBytes,
                tagBytes,
                producerAddressLengthBytes,
                producerAddressBytes,
                request.Message.Body);
        }
示例#45
0
 public override void SendMessage(IRpcController controller, SendMessageRequest request, Action<NoData> done)
 {
     throw new NotImplementedException();
 }