public void TestJsonSerializationIncludesApiKey()
        {
            var message = new Message.Message();

            var messageJson = JsonConvert.SerializeObject(message, _requestSerializerSettings);
            Assert.IsTrue(messageJson.Contains(string.Format("\"api_key\":\"{0}\"", API_KEY)));
        }
        public void TestSendMessageInvalidDomain()
        {
            var client = new Client(ApiKey) { BaseUri = "http://0.0.0.0/" };

            var threwException = false;
            try
            {
                var message = new Message.Message
                {
                    Uid = Guid.NewGuid().ToString(),
                    Recipient = new Recipient("*****@*****.**"),
                    RecipientOverride = RecipientOverride,
                    Text = "This is my text content"
                };

                client.SendMessage(message);
            }
            catch (PostageResponseException<MessageResponse> exception)
            {
                threwException = true;
                Assert.IsNull(exception.ResponseContainer);
            }

            Assert.IsTrue(threwException);
        }
 public DirectResponder(Dispatcher dispatcher, PeerBean peerBeanMaster, ChannelHandlerContext ctx, Message.Message requestMessage)
 {
     _dispatcher = dispatcher;
     _peerBeanMaster = peerBeanMaster;
     _ctx = ctx;
     _requestMessage = requestMessage;
 }
 public void listToPics(String topic)
 {
     EventArgs e = new EventArgs();
     Message.Message msg = new Message.Message("getTopics", topic);
     getTopic(e, topic);
     sendNewTopic(e, msg);
 }
Beispiel #5
0
        /// <summary>
        /// Обработчик события срабатывания межкадрового таймера
        /// </summary>
        /// <param name="sender">Отправитель события</param>
        /// <param name="e">Аргументы события</param>
        private void EventHandler_TmrInterFrameDelay_Elapsed(
            object sender, ElapsedEventArgs e)
        {
            Byte[]          message;
            Message.Message request;
            Timer           tmr = (Timer)sender;

            tmr.Stop();

            // Таймер сработал, значит сообщение (запрос)
            // принят полностью считаем CRC16
            message = new byte[_SerialPort.BytesToRead];
            _SerialPort.Read(message, 0, _SerialPort.BytesToRead);

            if (true == Modbus.OSIModel.DataLinkLayer.CRC16.VerefyCRC16(message))
            {
                // Запрос принят корректно
                Byte[] array = new byte[(message.Length - 4)];  //Данные в сообщениии
                Array.Copy(message, 2, array, 0, array.Length); // Выделили данные из сообщения

                request = new Message.Message(message[0], message[1], array);

                if (request.Address == 0)
                {
                    // Формируем событие приёма широковещаетельного запроса
                    _СurrentTransaction = new Transaction.Transaction(
                        TransactionType.BroadcastMode, request);
                    _СurrentTransaction.TransactionWasEnded +=
                        new EventHandler(EventHandler_СurrentTransaction_TransactionWasEnded);
                    _СurrentTransaction.Start(); // Стартуем транзакцию
                    OnRequestWasRecived(new MessageEventArgs(request));
                    // ??? Можно было бы запустить таймер задержки при широковещаетльном запросе
                    // Сейчас не реализовано. По этому, завершам транзакцию сразу.
                    _СurrentTransaction.Stop(null); // Завершает транзакцию
                }
                else
                {
                    _СurrentTransaction = new Transaction.Transaction(
                        TransactionType.UnicastMode, request);
                    _СurrentTransaction.TransactionWasEnded +=
                        new EventHandler(EventHandler_СurrentTransaction_TransactionWasEnded);
                    _СurrentTransaction.Start();
                    // Запускаем таймер таймаута ответа подчинённого устройства
                    _TimerTimeoutCurrentTransaction.Start();
                    // Формируем событие приёма адресованного запроса.
                    // Транзакция здесь продолжается до тех пор, покак не будет
                    // отправлен ответ.
                    OnRequestWasRecived(new MessageEventArgs(request));
                }
            }
            else
            {
                // Принят запрос с неверным CRC16
                OnErrorOccurred(new ErrorOccurredEventArgs
                                    (PortError.CheckSumError, "Принят запрос с неверным CRC16"));
            }
            return;
        }
Beispiel #6
0
        private async Task SendSelectionResult(Message.Message contex, Mediator mediator)
        {
            var correctAnswer = new CheckAnswer(contex.Id, contex.Data);
            await mediator.HandleCommand(correctAnswer);

            Console.WriteLine("_________________correctAnswer" + correctAnswer.Result);
            var text = MessageTextPattern.GetResultMessage(correctAnswer.Result);
            await mediator.HandleCommand(new SendMessageCommand(contex.Id, text));
        }
Beispiel #7
0
        public void Response(Message.Message responseMessage)
        {
            if (responseMessage.Sender.IsRelayed)
            {
                responseMessage.SetPeerSocketAddresses(responseMessage.Sender.PeerSocketAddresses);
            }

            _dispatcher.Respond(_ctx, responseMessage);
        }
Beispiel #8
0
        private void dataFromServer()
        {
            isListen = true;
            try
            {
                while (isListen)
                {
                    Byte[] bytesFromServer = new Byte[2097152];

                    int    len           = _clientSocket.Receive(bytesFromServer);
                    byte[] receivedBytes = new byte[len];
                    receivedBytes = bytesFromServer;
                    Message.Message msg = (Message.Message)Message.MessageHandle.deserialize(receivedBytes);

                    //此时消息已经被反序列化为Message类,这里添加接受到消息后做的处理



                    if (msg.messageType == Message.MessageTypeEnum.text)
                    {
                        if (msg.userName == _userName)
                        {
                            //do something
                        }
                        else
                        {
                            //do something
                        }
                    }
                    //else if (msg.messageType == Message.MessageTypeEnum.picture)
                    //{
                    //    if (msg.userName == _userName)
                    //    {
                    //        ShowPicture(msg.userName, LoadImage(msg.bitmap), "mine");
                    //    }
                    //    else
                    //    {
                    //        ShowPicture(msg.userName, LoadImage(msg.bitmap), "other");
                    //    }

                    //}
                    //else if (msg.messageType == Message.MessageTypeEnum.notification)
                    //{
                    //    showMassage(msg.userName, msg.text, "noti");
                    //}
                    //else if (msg.messageType == Message.MessageTypeEnum.warn)
                    //{
                    //    showWarn(msg.text);

                    //}
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
        }
Beispiel #9
0
 public BaseChannelData ToBaseChannelData(Message.Message lastMessage)
 {
     return(new BaseChannelData
     {
         _id = _id,
         name = name,
         lastMessage = lastMessage
     });
 }
Beispiel #10
0
 private Message.Message genMessage(Message.MessageTypeEnum msgType)
 {
     Message.Message msg = new Message.Message();
     msg.userName    = _userName;
     msg.room        = _userRoom;
     msg.time        = System.DateTime.Now.ToString();
     msg.messageType = msgType;
     return(msg);
 }
Beispiel #11
0
        public override void AcceptMessage(Message.Message msg)
        {
            string ret = string.Empty;

            ThalesCore.Message.XML.MessageParser.Parse(msg, XMLMessageFields, ref kvp, out ret);
            if (ret == ErrorCodes.ER_00_NO_ERROR)
            {
                _delay = kvp.Item("Delay");
            }
        }
Beispiel #12
0
        public override void AcceptMessage(Message.Message msg)
        {
            string xMLParseResult = XMLParseResult;

            MessageParser.Parse(msg, XMLMessageFields, ref kvp, out xMLParseResult);
            if (xMLParseResult == ErrorCodes.ER_00_NO_ERROR)
            {
                _modeFlag = kvp.Item("Mode Flag");
            }
        }
Beispiel #13
0
        //---------------------------------------------------------------------------
        #endregion
        //---------------------------------------------------------------------------
        #region Constructors
        //---------------------------------------------------------------------------
        /// <summary>
        /// Конструктор
        /// </summary>
        public Transaction()
        {
            _Identifier = Transaction.GetRandomNumber();

            _Answer      = null;
            _Request     = null;
            _Status      = TransactionStatus.NotInitialized;
            _TimeOfEnd   = 0;
            _TimeOfStart = 0;
            _Type        = TransactionType.Undefined;
        }
Beispiel #14
0
 public bool OutputMessage(Message.Message message)
 {
     if (message is TodaysTransactionsMessage transactionsMessage)
     {
         return(transactionsMessage.Detailed == Detailed);
     }
     else
     {
         return(true);
     }
 }
Beispiel #15
0
        private async Task SendMusicPage1(Message.Message contex, Mediator mediator)
        {
            UserAnswer userAnswer = new UserAnswer {
                userId = contex.Id, answer = "1"
            };
            await mediator.HandleCommand(new AddUserAnswer(userAnswer));

            MusicInfo musicInfo = new MusicInfo {
                fileLocation = @"D:\file4.ogg"
            };
            await mediator.HandleCommand(new SendGamePageCommand(contex.Id, "Test", musicInfo));
        }
Beispiel #16
0
        //---------------------------------------------------------------------------
        /// <summary>
        /// Конструктор
        /// </summary>
        /// <param name="type">Тип modbus транзации</param>
        /// <param name="request">Запрос от мастера сети</param>
        public Transaction(TransactionType type,
                           Message.Message request)
        {
            _Identifier = Transaction.GetRandomNumber();

            _Type        = type;
            _Answer      = null;
            _Request     = request;
            _Status      = TransactionStatus.NotInitialized;
            _TimeOfEnd   = 0;
            _TimeOfStart = 0;
        }
Beispiel #17
0
        /// <summary>
        /// Creates a request handler that can send TCP and UDP messages.
        /// </summary>
        /// <param name="tcsResponse">The future that will be called when we get an answer.</param>
        /// <param name="peerBean">The peer bean.</param>
        /// <param name="connectionBean">The connection bean.</param>
        /// <param name="configuration">The client-side connection configuration.</param>
        public RequestHandler(TaskCompletionSource<Message.Message> tcsResponse, PeerBean peerBean, ConnectionBean connectionBean, IConnectionConfiguration configuration)
        {
            _tcsResponse = tcsResponse;
            PeerBean = peerBean;
            ConnectionBean = connectionBean;
            _message = tcsResponse.Task.AsyncState as Message.Message;
            _sendMessageId = new MessageId(_message);
            IdleTcpSeconds = configuration.IdleTcpSeconds;
            IdleUdpSeconds = configuration.IdleUdpSeconds;
            ConnectionTimeoutTcpMillis = configuration.ConnectionTimeoutTcpMillis;

            //Logger.Info("Instantiated with object identity: {0}.", RuntimeHelpers.GetHashCode(this));
        }
Beispiel #18
0
        /// <summary>
        /// Creates a request handler that can send TCP and UDP messages.
        /// </summary>
        /// <param name="tcsResponse">The future that will be called when we get an answer.</param>
        /// <param name="peerBean">The peer bean.</param>
        /// <param name="connectionBean">The connection bean.</param>
        /// <param name="configuration">The client-side connection configuration.</param>
        public RequestHandler(TaskCompletionSource <Message.Message> tcsResponse, PeerBean peerBean, ConnectionBean connectionBean, IConnectionConfiguration configuration)
        {
            _tcsResponse               = tcsResponse;
            PeerBean                   = peerBean;
            ConnectionBean             = connectionBean;
            _message                   = tcsResponse.Task.AsyncState as Message.Message;
            _sendMessageId             = new MessageId(_message);
            IdleTcpSeconds             = configuration.IdleTcpSeconds;
            IdleUdpSeconds             = configuration.IdleUdpSeconds;
            ConnectionTimeoutTcpMillis = configuration.ConnectionTimeoutTcpMillis;

            //Logger.Info("Instantiated with object identity: {0}.", RuntimeHelpers.GetHashCode(this));
        }
        public void TestJsonSerializationIncludesAttachments()
        {
            var fileContent = "this is my file content";

            var contentBytes = Encoding.UTF8.GetBytes(fileContent);
            var stream = new MemoryStream(contentBytes);
            var message = new Message.Message();
            message.Attachments.Add(new Attachment(stream, "notes.txt", "text/plain"));

            var messageJson = JsonConvert.SerializeObject(message, _requestSerializerSettings);
            Assert.IsTrue(
                messageJson.Contains(
                    "{\"attachments\":{\"notes.txt\":{\"content_type\":\"text/plain\",\"content\":\"dGhpcyBpcyBteSBmaWxlIGNvbnRlbnQ=\"}}}"));
        }
Beispiel #20
0
        /// <summary>
        /// Sends a message via TCP.
        /// </summary>
        /// <param name="handler">The handler to deal with the response message.</param>
        /// <param name="tcsResponse">The TCS for the response message. (FutureResponse equivalent.)</param>
        /// <param name="message">The message to send.</param>
        /// <param name="channelCreator">The channel creator for the TCP channel.</param>
        /// <param name="idleTcpSeconds">The idle time until message fail.</param>
        /// <param name="connectTimeoutMillis">The idle time for the connection setup.</param>
        /// <param name="peerConnection"></param>
        /// <returns></returns>
        public async Task SendTcpAsync(IInboundHandler handler, TaskCompletionSource <Message.Message> tcsResponse,
                                       Message.Message message, ChannelCreator channelCreator, int idleTcpSeconds, int connectTimeoutMillis,
                                       PeerConnection peerConnection)
        {
            // no need to continue if already finished
            if (tcsResponse.Task.IsCompleted)
            {
                return;
            }
            RemovePeerIfFailed(tcsResponse, message);

            bool isFireAndForget = handler == null;

            // we need to set the neighbors if we use relays
            if (message.Sender.IsRelayed && message.Sender.PeerSocketAddresses.Count != 0)
            {
                message.SetPeerSocketAddresses(message.Sender.PeerSocketAddresses);
            }
            if (peerConnection != null && peerConnection.Channel != null && peerConnection.Channel.IsOpen)
            {
                var channel = SendTcpPeerConnection(peerConnection, handler, channelCreator, tcsResponse);
                await AfterConnectAsync(tcsResponse, message, channel, isFireAndForget);
            }
            else if (channelCreator != null)
            {
                var timeoutHandler = CreateTimeoutHandler(tcsResponse, idleTcpSeconds, handler == null);
                // check relay
                if (message.Recipient.IsRelayed)
                {
                    // check if reverse connection is possible
                    if (!message.Sender.IsRelayed)
                    {
                        await HandleRconAsync(handler, tcsResponse, message, channelCreator, connectTimeoutMillis, peerConnection,
                                              timeoutHandler);
                    }
                    else
                    {
                        await HandleRelayAsync(handler, tcsResponse, message, channelCreator, idleTcpSeconds, connectTimeoutMillis,
                                               peerConnection, timeoutHandler);
                    }
                }
                // normal connection
                else
                {
                    await ConnectAndSendAsync(handler, tcsResponse, channelCreator, connectTimeoutMillis, peerConnection,
                                              timeoutHandler, message);
                }
            }
        }
Beispiel #21
0
        public void SendResponse(Message.Message answer)
        {
            // Останавливаем таймер таймаута
            _TimerTimeoutCurrentTransaction.Stop();

            Byte[] array = answer.ToArray();
            // Отсылаем ответ
            _SerialPort.Write(array, 0, array.Length);
            // Останавливаем транзакцию
            _СurrentTransaction.Stop(answer);
            // Формирует событие
            OnResponseWasSent(new MessageEventArgs(answer));

            return;
        }
Beispiel #22
0
        public async Task<object> StartRequest(string action, MessageTypeDefinition messageTypeDefinition, object arguments)
        {
            var message = new Message.Message { Action = action, MessageTypeDefinition = messageTypeDefinition, Arguments = arguments };

            MessageClient messageClient = new MessageClient();
            var messageResult = await messageClient.SendMessage(message);

            var returnType = concreteType.GetMethod(action).ReturnType;
            //var obj = ByteArrayToObject(messageResult.Result);

            return Convert.ChangeType(messageResult.Result, returnType);

            //var result = host.RunMessage(action, messageTypeDefinition, messageBytes);
            //var result =  messageResult.Result;
        }
Beispiel #23
0
 public static Message.Message CreateResponseMessage(Message.Message requestMessage,
                                                     Message.Message.MessageType replyType, PeerAddress peerAddress)
 {
     // this will have the ports >40'000 that we need to know for sending the reply
     return(new Message.Message()
            .SetSenderSocket(requestMessage.SenderSocket)
            .SetRecipientSocket(requestMessage.RecipientSocket)
            .SetRecipient(requestMessage.Sender)
            .SetSender(peerAddress)
            .SetCommand(requestMessage.Command)
            .SetType(replyType)
            .SetVersion(requestMessage.Version)
            .SetMessageId(requestMessage.MessageId)
            .SetIsUdp(requestMessage.IsUdp));
 }
Beispiel #24
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="msg"></param>
 public void InvokePlugins(Message.Message msg)
 {
     foreach (var plugin in plugins[msg.action])
     {
         var methodAttribute = plugin.Item2;
         if (methodAttribute.respondsTo.HasFlag(msg.action) && msg.permission.CompareTo(methodAttribute.accessLevel) >= 0)
         {
             if (plugin.Item1.CanExecute(msg, methodAttribute.command))
             {
                 plugin.Item1.message = msg;
                 plugin.Item1.Invoke();
             }
         }
     }
 }
Beispiel #25
0
        public override void AcceptMessage(Message.Message msg)
        {
            string ret = string.Empty;

            ThalesCore.Message.XML.MessageParser.Parse(msg, XMLMessageFields, ref kvp, out ret);
            if (XMLParseResult == ErrorCodes.ER_00_NO_ERROR)
            {
                _modeFlag  = kvp.Item("Mode");
                _keyType   = kvp.Item("Key Type");
                _keyScheme = kvp.Item("Key Scheme LMK");
                _zmkScheme = kvp.ItemOptional("Key Scheme ZMK");
                _zmk       = kvp.ItemOptional("ZMK Scheme") + kvp.ItemOptional("ZMK");
            }
            XMLParseResult = ret;
        }
Beispiel #26
0
        /// <summary>
        /// Extracts the sender's IPEndPoint from the message.
        /// In Java, this is done in TomP2POutbound.write().
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static IPEndPoint ExtractSenderEp(Message.Message message)
        {
            IPEndPoint sender;

            if (message.SenderSocket == null)
            {
                // in case of a request
                sender = message.Sender.CreateSocketUdp();
            }
            else
            {
                // in case of a reply
                sender = message.RecipientSocket;
            }
            return(sender);
        }
Beispiel #27
0
        public Boolean sendText(string text)
        {
            try
            {
                Message.Message msg = genMessage(Message.MessageTypeEnum.text);
                msg.text = text;

                _clientSocket.Send(Message.MessageHandle.serialize(msg));
                return(true);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
                return(false);
            }
        }
Beispiel #28
0
        /// <summary>
        /// // TODO document
        /// </summary>
        /// <param name="handler"></param>
        /// <param name="tcsResponse"></param>
        /// <param name="message"></param>
        /// <param name="channelCreator"></param>
        /// <param name="idleTcpSeconds"></param>
        /// <param name="connectTimeoutMillis"></param>
        /// <param name="peerConnection"></param>
        /// <param name="timeoutHandler"></param>
        private async Task HandleRelayAsync(IInboundHandler handler, TaskCompletionSource <Message.Message> tcsResponse,
                                            Message.Message message, ChannelCreator channelCreator, int idleTcpSeconds, int connectTimeoutMillis,
                                            PeerConnection peerConnection, TimeoutFactory timeoutHandler)
        {
            var   taskPingDone = PingFirst(message.Recipient.PeerSocketAddresses);
            await taskPingDone;

            if (!taskPingDone.IsFaulted)
            {
                var recipient = PeerSocketAddress.CreateSocketTcp(taskPingDone.Result);
                var channel   = SendTcpCreateChannel(recipient, channelCreator, peerConnection, handler,
                                                     timeoutHandler, connectTimeoutMillis);
                await AfterConnectAsync(tcsResponse, message, channel, handler == null);

                // TODO add this before AfterConnect?
                var   taskResponse = tcsResponse.Task;
                await taskResponse;
                if (taskResponse.IsFaulted)
                {
                    if (taskResponse.Result != null &&
                        taskResponse.Result.Type != Message.Message.MessageType.User1)
                    {
                        // "clearInactivePeerSocketAddress"
                        var tmp = new List <PeerSocketAddress>();
                        foreach (var psa in message.Recipient.PeerSocketAddresses)
                        {
                            if (psa != null)
                            {
                                if (!psa.Equals(taskPingDone.Result))
                                {
                                    tmp.Add(psa);
                                }
                            }
                        }
                        message.SetPeerSocketAddresses(tmp);

                        await SendTcpAsync(handler, tcsResponse, message, channelCreator, idleTcpSeconds,
                                           connectTimeoutMillis, peerConnection);
                    }
                }
            }
            else
            {
                // .NET-specific:
                tcsResponse.SetException(new TaskFailedException("No relay could be contacted. <-> " + taskPingDone.Exception));
            }
        }
Beispiel #29
0
        /// <summary>
        /// saveDoc(doc [,BodySave, string MD5]) - сохраняет Документ в Excel файл, если он изменялся
        /// </summary>
        /// <param name="name">имя документа</param>
        /// <param name="BodySave>true - doc.Body нужно сохранить, false - уже в Excel</param>
        /// <param name="MD5">MD5 документа. Если BodySave = false - обязательно</param>
        /// <history>10.1.2016
        /// 18.1.16 - аккуратная обработка BodySave=false и MD5
        /// 20.1.16 - fix bug: not write EOLinTOC for TSmatch type Documents
        /// 1.04.16 - overlay saveDoc(..)
        /// </history>
        public static void saveDoc(Document doc, bool BodySave = true, string MD5 = "", int EOL = 0)
        {
            Log.set("saveDoc(\"" + doc.name + "\")");
            try
            {
                Document toc = Documents[Decl.DOC_TOC];
                if (doc.type == Decl.DOC_TYPE_N) doc.isChanged = true;
                if (doc.isChanged)
                {
                    int EOLinTOC = EOL;
                    if (BodySave)
                    {
                        FileOp.setRange(doc.Sheet);
                        FileOp.saveRngValue(doc.Body);
//24/4/17                        doc.chkSum = doc.Body.ComputeMD5();
//2/8/17 removed EOLinTOC                       doc.EOLinTOC = doc.Body.iEOL();
                        doc.il = doc.Body.iEOL();
                        FileOp.fileSave(doc.Wb);
                        doc.isChanged = false;
                    }
                    else
                    {
                        if (MD5.Length < 20 || EOL == 0) { Message.Message Msg = new Message.Message(); Msg.F("ERR_05.8_saveDoc_NOMD5"); }
                        //2/8/17 removed EOLinTOC                        else { doc.chkSum = MD5; doc.EOLinTOC = EOLinTOC; }
                        else { doc.chkSum = MD5; doc.il = EOLinTOC; }
                    }
                    Mtr tmp = FileOp.getSheetValue(toc.Sheet);
                    for (int n = toc.i0; n <= toc.il; n++)
                    {   // находим и меняем строку документа doc TOC
                        if ((string)toc.Body[n, Decl.DOC_NAME] != doc.name) continue;
                        tmp[1, 1] = Lib.timeStr();
                        tmp[n, Decl.DOC_TIME] = Lib.timeStr();
                        tmp[n, Decl.DOC_MD5] = doc.chkSum;
                        if (doc.type == "N") tmp[n, Decl.DOC_CREATED] = Lib.timeStr();
//2/8/17 removed EOLinTOC                        if (doc.type != Decl.TSMATCH_TYPE) tmp[n, Decl.DOC_EOL] = doc.EOLinTOC;
                        if (doc.type != Decl.TSMATCH_TYPE) tmp[n, Decl.DOC_EOL] = doc.il;
                        FileOp.setRange(toc.Sheet);
                        FileOp.saveRngValue(tmp, AutoFit: false);  //======= save TОC in TSmatch.xlsx
                        break;
                    }
                }
            }
            catch (Exception e) { Log.FATAL("Ошибка \"" + e.Message + "\" сохранения файла \"" + doc.name + "\""); }
            Log.exit();
        }
        public async Task HandleMessage(Message.Message contex, Mediator mediator)
        {
            if (contex.Data == "Run Game")
            {
                var userStatus = new UpdateUserStatus(contex.Id, UserStates.SecondLevel);
                await mediator.HandleCommand(userStatus);

                if (!userStatus.IsExseption)
                {
                    contex.Data = "";
                    await mediator.HandleCommand(contex);
                }
            }
            else
            {
                await mediator.HandleCommand(new SendMainPageCommand(contex));
            }
        }
Beispiel #31
0
 public override void HandleResponse(Message.Message requestMessage, PeerConnection peerConnection, bool sign, IResponder responder)
 {
     if (!(requestMessage.Type == Message.Message.MessageType.RequestFf1 &&
           requestMessage.Command == Rpc.Commands.Broadcast.GetNr()))
     {
         throw new ArgumentException("Message content is wrong for this handler.");
     }
     Logger.Debug("Received BROADCAST message: {0}.", requestMessage);
     BroadcastHandler.Receive(requestMessage);
     if (requestMessage.IsUdp)
     {
         responder.ResponseFireAndForget();
     }
     else
     {
         responder.Response(CreateResponseMessage(requestMessage, Message.Message.MessageType.Ok));
     }
 }
Beispiel #32
0
        private TaskCompletionSource <Message.Message> Send(Message.Message message, IConnectionConfiguration configuration,
                                                            ChannelCreator channelCreator)
        {
            var tcsResponse = new TaskCompletionSource <Message.Message>(message);

            tcsResponse.Task.ContinueWith(taskResponse =>
            {
                if (!taskResponse.IsFaulted)
                {
                    var response = taskResponse.Result;
                    if (response != null)
                    {
                        var neighborSet = response.NeighborsSet(0);
                        if (neighborSet != null)
                        {
                            foreach (var neighbor in neighborSet.Neighbors)
                            {
                                lock (PeerBean.PeerStatusListeners)
                                {
                                    foreach (var listener in PeerBean.PeerStatusListeners)
                                    {
                                        listener.PeerFound(neighbor, response.Sender, null);
                                    }
                                }
                            }
                        }
                    }
                }
            });

            var requestHandler = new RequestHandler(tcsResponse, PeerBean, ConnectionBean, configuration);

            if (!configuration.IsForceTcp)
            {
                requestHandler.SendUdpAsync(channelCreator);
            }
            else
            {
                requestHandler.SendTcpAsync(channelCreator);
            }
            // .NET-specific: Return TCS instead of Task. It's actually the same TCS that is provided with
            // the RequestHandler c'tor
            return(tcsResponse);
        }
Beispiel #33
0
        public static void Log(Message.Message data)
        {
            try
            {
                StreamWriter sw   = File.AppendText(logFileLocation + "log.txt");
                string       temp = "";

                //Change the temp to what you want to log
                temp = "Type" + data.messageType.ToString() + " Time:" + data.time + " User:"******" Room:" + data.room + " Text:" + data.text;


                sw.WriteLine(temp);
                sw.Flush();
                sw.Close();
            }
            catch
            {
            }
        }
Beispiel #34
0
        public async Task HandleMessage(Message.Message message, Mediator mediator)
        {
            if ("Stop the game" == message.Data)
            {
                await mediator.HandleCommand(new UpdateUserStatus(message.Id, UserStates.FirstLevel));

                await mediator.HandleCommand(new DeleteUserAnswer(message.Id));

                await mediator.HandleCommand(message);
            }
            if (Regex.IsMatch(message.Data, @"^[1-4]$", RegexOptions.Multiline))
            {
                await SendSelectionResult(message, mediator);
                await SendMusicPage(message, mediator);
            }
            if ("" == message.Data)
            {
                await SendMusicPage(message, mediator);
            }
        }
Beispiel #35
0
        /// <summary>
        /// Returns the registered handler for the provided message, if any.
        /// </summary>
        /// <param name="message">The message a handler should be found for.</param>
        /// <returns>The handler for the provided message or null, if none has been registered for that message.</returns>
        public DispatchHandler AssociatedHandler(Message.Message message)
        {
            if (message == null || !message.IsRequest())
            {
                return(null);
            }

            PeerAddress recipient = message.Recipient;

            // search for handler, 0 is ping
            // if we send with peerId = ZERO, then we take the first one we found
            if (recipient.PeerId.IsZero && message.Command == Rpc.Rpc.Commands.Ping.GetNr())
            {
                Number160 peerId = _peerBeanMaster.ServerPeerAddress.PeerId;
                return(SearchHandler(peerId, peerId, Rpc.Rpc.Commands.Ping.GetNr()));
            }
            else
            {
                // else we search for the handler that we are responsible for
                DispatchHandler handler = SearchHandler(recipient.PeerId, recipient.PeerId, message.Command);
                if (handler != null)
                {
                    return(handler);
                }
                else
                {
                    // If we could not find a handler that we are responsible for, we
                    // are most likely a relay. Since we have no ID of the relay, we
                    // just take the first one.
                    var handlers = SearchHandler(Convert.ToInt32(message.Command));
                    foreach (var entry in handlers)
                    {
                        if (entry.Key.DomainKey.Equals(recipient.PeerId))
                        {
                            return(entry.Value);
                        }
                    }
                    return(null);
                }
            }
        }
Beispiel #36
0
 private void RemovePeerIfFailed(TaskCompletionSource <Message.Message> tcs, Message.Message message)
 {
     // execute the following delegate only if TCS task failed
     tcs.Task.ContinueWith(delegate(Task task)
     {
         if (message.Recipient.IsRelayed)
         {
             // TODO: Java, make the relay go away if failed
         }
         else
         {
             lock (_peerStatusListeners)
             {
                 foreach (var listener in _peerStatusListeners)
                 {
                     listener.PeerFailed(message.Recipient, new PeerException(tcs));
                 }
             }
         }
     }, TaskContinuationOptions.OnlyOnFaulted);
 }
Beispiel #37
0
        public List <BaseChannelData> ReadManyBase(Expression <Func <Channel, bool> > filter = null)
        {
            if (filter == null)
            {
                filter = x => true;
            }

            List <Channel> fetchedChannels = ReadMany(filter);

            MessageCrud messageCrud = new MessageCrud();

            var baseChannels = new List <BaseChannelData>();

            foreach (Channel channel in fetchedChannels)
            {
                Message.Message lastMessage = messageCrud.ReadLatest(channel._id);
                baseChannels.Add(channel.ToBaseChannelData(lastMessage));
            }

            return(baseChannels);
        }
        public void Start()
        {
            var message = new Message.Message();

            if (!_udpManuallySet)
            {
                // not set, decide based on the data
                if (DataMap == null)
                {
                    SetIsUdp(true);
                }
                else
                {
                    SetIsUdp(false);
                    message.SetDataMap(new DataMap(DataMap));
                }
            }

            message.SetKey(MessageKey);
            message.SetIntValue(0);
            message.SetIsUdp(IsUdp);

            _peer.BroadcastRpc.BroadcastHandler.Receive(message);
        }
Beispiel #39
0
        //---------------------------------------------------------------------------
        /// <summary>
        /// Функция 16 (0х10). Записывает значения массива регистров
        /// </summary>
        /// <param name="AddressSlave">Адрес удалённого slave-устройства,
        /// в котором необходимо установить значения последовательности 
        /// регистров</param>
        /// <param name="StartingAddress">Адрес первого регистра</param>
        /// <param name="value">Количество, значения регистров 1...123</param>
        /// <returns>Результат выполнения операции</returns>
        public Modbus.OSIModel.Message.Result WriteMultipleRegisters(byte AddressSlave,
            UInt16 StartingAddress, UInt16[] value)
        {
            String message;
            Message.Message request;
            Modbus.OSIModel.Message.Message answer;
            Modbus.OSIModel.Message.Result result;

            if ((value.Length == 0) && (value.Length > 124))
            {
                message = String.Format(
                    "Длина блока регистров {0} выходит за пределы диапазона 1...124", 
                    value.Length);
                throw new ArgumentOutOfRangeException("Quantity", message);
            }
            
            // Проверяем выход блока данных за граници диапазона допустимых адресов
            if ((StartingAddress + value.Length) > 0xFFFF)
            {
                message = String.Format(
                    "Длина блока регистров {0} больше допустимой величины 0xFFFF",
                    (StartingAddress + value.Length));
                throw new ArgumentException(message, "Quantity");
            }

            // Формируем запрос
            List<Byte> data = new List<byte>();
            data.AddRange(Convert.ConvertToBytes(StartingAddress)); // Адрес первого регистра в блоке
            data.AddRange(Convert.ConvertToBytes((UInt16)value.Length)); // Длина блока регистров
            data.Add((Byte)(value.Length * 2)); // Количество байт 
            // Значения регистров
            for (int i = 0; i < value.Length; i++)
            {
                data.AddRange(Convert.ConvertToBytes(value[i]));
            }

            Message.PDU pdu = new Message.PDU(0x10, data.ToArray());
            request = new Message.Message(AddressSlave, pdu);

            // Проверяем состояние сервера
            if (_flgBusy == true)
            {
                return result = new Message.Result(Error.IllegalReguest,
                    String.Format("Попытка выполнить запрос (код функции 0x10) к серверу {0}, во время выполнения предыдущего",
                    Name), null, null);
            }
            else
            {
                // Устанавливаем начало транзакции
                StartTransaction();

                // Отправляем запрос
                Modbus.OSIModel.DataLinkLayer.RequestError error =
                    _dataLinkObject.SendMessage(request, out answer);

                switch (error)
                {
                    case Modbus.OSIModel.DataLinkLayer.RequestError.NoError:
                        {
                            // Разбираем сообщение на предмет ошибок
                            if (IsError(request, answer, out result))
                            {
                                // Ошибка была
                                break;
                            }
                            else
                            {
                                // Ошибки нет возвращаем результат выполнения запроса
                                // Проверяем длину сообщения
                                if (answer.PDUFrame.Data.Length != 4)
                                {
                                    result = new Message.Result(Error.DataFormatError,
                                        String.Format(
                                        "Длина ответного сообщения {0} не соответствет ожидаемой 4",
                                        answer.PDUFrame.Data.Length), request, answer);
                                }
                                else
                                {
                                    // Проверяем адрес начального регистра в ответном сообщениии
                                    Byte[] arr = new Byte[2];
                                    Array.Copy(answer.PDUFrame.Data, 0, arr, 0, 2);
                                    UInt16 var = Modbus.Convert.ConvertToUInt16(arr);
                                    
                                    if (var != StartingAddress)
                                    {
                                        result = new Message.Result(Error.DataFormatError,
                                            String.Format(
                                            "Адрес начального регистра {0} в запросе не совпадает с адресом в ответном сообщении {1}",
                                            StartingAddress, var), request, answer);
                                    }
                                    else
                                    {
                                        // Проверяем длину блока регистров
                                        Array.Copy(answer.PDUFrame.Data, 2, arr, 0, 2);
                                        var = Modbus.Convert.ConvertToUInt16(arr);

                                        if (var != value.Length)
                                        {
                                            result = new Message.Result(Error.DataFormatError,
                                               String.Format(
                                               "Длина блока регистров {0} в запросе не совпадает с длиной блока в ответном сообщении {1}",
                                               value.Length, var), request, answer);
                                        }
                                        else
                                        {
                                            // Ответ корректен
                                            result = new Modbus.OSIModel.Message.Result(Error.NoError,
                                                String.Empty, request, answer);
                                        }
                                    }
                                }
                                break;
                            }
                        }
                    case Modbus.OSIModel.DataLinkLayer.RequestError.TimeOut:
                        {
                            // Таймаут ответа
                            result = new Modbus.OSIModel.Message.Result(Error.TimeOut,
                                "Ответ не был получен в заданное время", request, null);
                            break;
                        }
                    default:
                        {
                            // Ошибка уровня Datalink layer.
                            result = new Modbus.OSIModel.Message.Result(Error.ReciveMessageError,
                                error.ToString(), request, null);
                            break;
                        }
                }
                StopTransaction();
                return result;
            }           
        }
 public void join(Chat.Chat.Chatter chatter)
 {
     chatroom.join(chatter);
     for (int i = 0; i < chatroom.roomChatter.Count; i++)
         if (chatroom.roomChatter[i].Equals(chatter)) return;
     roomUser.Add(client);
     EventArgs e = new EventArgs();
     Message.Message msg=new Message.Message("in",chatter.getUserName() + "join the chatroom\"" + chatroomTopic + "\"");
     addText(e,msg.data);
     sendMessage(msg);
 }
Beispiel #41
0
        /// <summary>
        /// Функция 0х3. Читает holding-регистры
        /// в удалённом устройстве
        /// </summary>
        /// <param name="AddressSlave">Адрес подчинённого устройства</param>
        /// <param name="StartingAddress">Адрес первого регистра в блоке</param>
        /// <param name="Quantity">Длина блока регистров хранения для чтения</param>
        /// <param name="values">Значения прочитанных регистров</param>
        /// <returns>Результат выполения операции</returns>
        public Message.Result ReadHoldingRegisters(
            byte AddressSlave, 
            ushort StartingAddress, 
            ushort Quantity, 
            out ushort[] values)
        {            
            Message.PDU frame = new Message.PDU();
            frame.Function = 0x3;
            frame.AddDataBytesRange(Convert.ConvertToBytes(StartingAddress));
            frame.AddDataBytesRange(Convert.ConvertToBytes(Quantity));

            Message.Message request = new Message.Message(AddressSlave, frame);
            return ReadHoldingRegisters(request, out values);
        }
Beispiel #42
0
        public void TestSendMessageSuccess()
        {
            var client = new Client(ApiKey);

            var message = new Message.Message
            {
                Uid = Guid.NewGuid().ToString(),
                Recipient = new Recipient("*****@*****.**"),
                RecipientOverride = RecipientOverride,
                Text = "This is my text content"
            };

            var responseContainer = client.SendMessage(message);
            Assert.AreEqual(ResponseStatus.Ok, responseContainer.Response.Status);
            Assert.IsNotNull(responseContainer.Response.Uid);
            Assert.IsTrue(responseContainer.Response.Uid.Length > 0);
            Assert.IsNotNull(responseContainer.Data.Id);
            Assert.IsTrue(responseContainer.Data.Id > 0);
        }
        public override void getMessage(object userState)
        {
            byte[] requestbuffer = new byte[1024];
            Message.Message msg = new Message.Message("", "");
            ChatAplication.user client = (ChatAplication.user)userState;

            while(true)// (mode.Equals("treatClient")) //(isNormalExit == false)
            {
                try
                {
                    if (client.sr.Read(requestbuffer, 0, 1024) > 0)
                    {
                        msg = (Message.Message)deserializeStream(requestbuffer);
                        handleMsg(msg);
                    }
                }
                catch (Exception ex)
                {
                    EventArgs e = new EventArgs();
                    showMsg(e, ex.Message);
                }
            }
        }
Beispiel #44
0
        /// <summary>
        /// Обработчик события срабатывания межкадрового таймера 
        /// </summary>
        /// <param name="sender">Отправитель события</param>
        /// <param name="e">Аргументы события</param>
        private void EventHandler_TmrInterFrameDelay_Elapsed(
            object sender, ElapsedEventArgs e)
        {
            Byte[] message;
            Message.Message request;
            Timer tmr = (Timer)sender;
            tmr.Stop();

            // Таймер сработал, значит сообщение (запрос) 
            // принят полностью считаем CRC16            
            message = new byte[_SerialPort.BytesToRead];
            _SerialPort.Read(message, 0, _SerialPort.BytesToRead);

            if (true == Modbus.OSIModel.DataLinkLayer.CRC16.VerefyCRC16(message))
            {
                // Запрос принят корректно
                Byte[] array = new byte[(message.Length - 4)]; //Данные в сообщениии
                Array.Copy(message, 2, array, 0, array.Length); // Выделили данные из сообщения
                
                request = new Message.Message(message[0], message[1], array);
                
                if (request.Address == 0)
                {
                    // Формируем событие приёма широковещаетельного запроса
                    _СurrentTransaction = new Transaction.Transaction(
                        TransactionType.BroadcastMode, request);
                    _СurrentTransaction.TransactionWasEnded += 
                        new EventHandler(EventHandler_СurrentTransaction_TransactionWasEnded);
                    _СurrentTransaction.Start(); // Стартуем транзакцию
                    OnRequestWasRecived(new MessageEventArgs(request));
                    // ??? Можно было бы запустить таймер задержки при широковещаетльном запросе
                    // Сейчас не реализовано. По этому, завершам транзакцию сразу.
                    _СurrentTransaction.Stop(null); // Завершает транзакцию 
                }
                else
                {
                    _СurrentTransaction = new Transaction.Transaction(
                        TransactionType.UnicastMode, request);
                    _СurrentTransaction.TransactionWasEnded +=
                        new EventHandler(EventHandler_СurrentTransaction_TransactionWasEnded);
                    _СurrentTransaction.Start();
                    // Запускаем таймер таймаута ответа подчинённого устройства
                    _TimerTimeoutCurrentTransaction.Start();
                    // Формируем событие приёма адресованного запроса. 
                    // Транзакция здесь продолжается до тех пор, покак не будет
                    // отправлен ответ.
                    OnRequestWasRecived(new MessageEventArgs(request));
                }
            }
            else
            {
                // Принят запрос с неверным CRC16
                OnErrorOccurred(new ErrorOccurredEventArgs
                    (PortError.CheckSumError, "Принят запрос с неверным CRC16"));
            }
            return;
        }
Beispiel #45
0
        public async Task TestSendMessageWithAttachmentAsync()
        {
            var client = new Client(ApiKey);

            var fileContent = "file contents!\n\n";

            var contentBytes = Encoding.UTF8.GetBytes(fileContent);
            var stream = new MemoryStream(contentBytes);

            var message = new Message.Message
            {
                Uid = Guid.NewGuid().ToString(),
                Subject = "Has attachment",
                Recipient = new Recipient("*****@*****.**"),
                RecipientOverride = RecipientOverride,
                Text = "This email should have an attachment",
            };

            message.Attachments.Add(new Attachment(stream, "readme.txt", "text/plain"));

            var responseContainer = await client.SendMessageAsync(message);

            Assert.AreEqual(ResponseStatus.Ok, responseContainer.Response.Status);
        }
        public void TestJsonSerializationIncludesText()
        {
            var text = "my content";
            var message = new Message.Message { Text = text };

            var messageJson = JsonConvert.SerializeObject(message, _requestSerializerSettings);

            Assert.IsTrue(messageJson.Contains(string.Format("\"arguments\":{{\"content\":{{\"text/plain\":\"{0}\"}}}}", text)));
        }
        public void TestJsonSerializationIncludesVariables()
        {
            var message = new Message.Message();
            message.Variables.Add("movie", "Pee Wee's Big Adventure");
            message.Variables.Add("actor", "Meryl Streep");

            var messageJson = JsonConvert.SerializeObject(message, _requestSerializerSettings);
            Assert.IsTrue(
                messageJson.Contains(
                    ":{\"variables\":{\"movie\":\"Pee Wee's Big Adventure\",\"actor\":\"Meryl Streep\"}}"));
        }
        public void TestJsonSerializationIncludesReplyToHeader()
        {
            var replyTo = "*****@*****.**";
            var message = new Message.Message { ReplyTo = replyTo };

            var messageJson = JsonConvert.SerializeObject(message, _requestSerializerSettings);

            Assert.IsTrue(messageJson.Contains(string.Format("\"arguments\":{{\"headers\":{{\"reply-to\":\"{0}\"}}}}", replyTo)));
        }
        public void TestJsonSerializationIncludesTemplate()
        {
            var slug = "some-template-slug";
            var message = new Message.Message { Template = slug };

            var messageJson = JsonConvert.SerializeObject(message, _requestSerializerSettings);

            Assert.IsTrue(messageJson.Contains(string.Format(":{{\"template\":\"{0}\"}}", slug)));
        }
        public void TestJsonSerializationIncludesRecipients()
        {
            var email1 = "*****@*****.**";
            var recipient1 = new Recipient(email1);
            recipient1.Variables.Add("actor", "Steve Gutenberg");

            var email2 = "*****@*****.**";
            var recipient2 = new Recipient(email2);
            recipient2.Variables.Add("actor", "Steve Martin");

            var message = new Message.Message();
            message.Recipients.Add(recipient1);
            message.Recipients.Add(recipient2);
            var messageJson = JsonConvert.SerializeObject(message, _requestSerializerSettings);
            Assert.IsTrue(messageJson.Contains("\"arguments\":" +
                                               "{\"recipients\":{\"[email protected]\":{\"actor\":\"Steve Gutenberg\"}," +
                                               "\"[email protected]\":{\"actor\":\"Steve Martin\"}}}"));
        }
        public void TestJsonSerializationIncludesRecipientOverride()
        {
            var recipientOverride = "*****@*****.**";
            var message = new Message.Message { RecipientOverride = recipientOverride };

            var messageJson = JsonConvert.SerializeObject(message, _requestSerializerSettings);

            Assert.IsTrue(messageJson.Contains(string.Format(":{{\"recipient_override\":\"{0}\"}}", recipientOverride)));
        }
Beispiel #52
0
 //---------------------------------------------------------------------------
 /// <summary>
 /// Конструктор
 /// </summary>
 /// <param name="type">Тип modbus транзации</param>
 /// <param name="request">Запрос от мастера сети</param>
 public Transaction(TransactionType type, 
     Message.Message request)
 {
     _Identifier = Transaction.GetRandomNumber();
     
     _Type = type;
     _Answer = null;
     _Request = request;
     _Status = TransactionStatus.NotInitialized;
     _TimeOfEnd = 0;
     _TimeOfStart = 0;
 }
Beispiel #53
0
 /// <summary>
 /// Конструктор
 /// </summary>
 /// <param name="message">Сообщение отправленное 
 /// мастеру или принятое от него</param>
 public MessageEventArgs(Message.Message message)
 {
     Message = message;
 }
Beispiel #54
0
        /// <summary>
        /// This method makes a copy of the original message and prepares it for 
        /// sending it to the relay.
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private static Message.Message CreateRconMessage(Message.Message message)
        {
            // get relay address from the unreachable peer
            var relayAddresses = message.Recipient.PeerSocketAddresses.ToArray();
            PeerSocketAddress socketAddress;

            if (relayAddresses.Length > 0)
            {
                // we should be fair and choose one of the relays randomly
                socketAddress = relayAddresses[Utils.Utils.RandomPositiveInt(relayAddresses.Length)];
            }
            else
            {
                throw new ArgumentException("There are no PeerSocketAddresses available for this relayed peer. This should not be possible!");
            }

            // we need to make a copy of the original message
            var rconMessage = new Message.Message();
            rconMessage.SetSender(message.Sender);
            rconMessage.SetVersion(message.Version);
            rconMessage.SetIntValue(message.MessageId);

            // make the message ready to send
            PeerAddress recipient =
                message.Recipient
                    .ChangeAddress(socketAddress.InetAddress)
                    .ChangePorts(socketAddress.TcpPort, socketAddress.UdpPort)
                    .ChangeIsRelayed(false);
            rconMessage.SetRecipient(recipient);
            rconMessage.SetCommand(Rpc.Rpc.Commands.Rcon.GetNr());
            rconMessage.SetType(Message.Message.MessageType.Request1);

            return rconMessage;
        }
Beispiel #55
0
 /// <summary>
 /// Конструктор
 /// </summary>
 public MessageEventArgs()
 {
     Message = new Message.Message(0, new PDU());
 }
Beispiel #56
0
        /// <summary>
        /// Заканчивает текущую транзакцию
        /// </summary>
        /// <param name="answer">Ответ slave-устройства</param>
        public void Stop(Message.Message answer)
        {
            if (!IsRunning)
            {
                switch (Status)
                {
                    case TransactionStatus.Aborted:
                        {
                            throw new InvalidOperationException(
                                String.Format("Transaction ID: {0}; Попытка завершить прерванную транзакцию",
                                Identifier));
                        }
                    case TransactionStatus.Completed:
                        {
                            throw new InvalidOperationException(
                                String.Format("Transaction ID: {0}; Попытка завершить завершённую транзакцию",
                                Identifier));
                        }
                    case TransactionStatus.NotInitialized:
                        {
                            throw new InvalidOperationException(
                                String.Format("Transaction ID: {0}; Попытка завершить не начатую транзакцию",
                                Identifier));
                        }
                    default:
                        {
                            throw new NotImplementedException();
                        }
                }
            }
            else
            {

                switch (TransactionType)
                {
                    case TransactionType.UnicastMode:
                        {
                            if (answer != null)
                            {
                                _Answer = answer;
                            }
                            else
                            {
                                throw new NullReferenceException(
                                    "Попытка установить в null ответное сообщение для завершения " +
                                    "транзакции адресованного запроса");
                            }
                            break;
                        }
                    case TransactionType.BroadcastMode:
                        {
                            if (answer != null)
                            {
                                throw new InvalidOperationException(
                                    "Попытка установить ответное сообщение для завершения транзакции " +
                                    "широковещательного запроса");
                            }
                            break;
                        }
                    case TransactionType.Undefined:
                        {
                            _Answer = answer;
                            break;
                        }
                }

                _TimeOfEnd = Environment.TickCount;
                _Status = TransactionStatus.Completed;
                
                // Генерируем событие окончания транзакции.
                OnTransactionWasEnded();

                //Debug.WriteLine(String.Format(
                //    "Transaction ID: {0} - Конец транзакции: {1}; Время транзакции: {2}",
                //    Identifier, _TimeOfEnd, TimeOfTransaction));
            }
            return;
        }
Beispiel #57
0
        public async Task TestGetMessageReceiptSuccessAsync()
        {
            var client = new Client(ApiKey);

            var message = new Message.Message
            {
                Uid = Guid.NewGuid().ToString(),
                Recipient = new Recipient("*****@*****.**"),
                RecipientOverride = RecipientOverride,
                Text = "This is my text content"
            };

            var sendResponseContainer = await client.SendMessageAsync(message);

            var responseContainer = await client.GetMessageReceiptAsync(sendResponseContainer.Response.Uid);

            Assert.AreEqual(ResponseStatus.Ok, responseContainer.Response.Status);
            Assert.AreEqual(sendResponseContainer.Data.Id, responseContainer.Data.Id);
        }
        public void TestJsonSerializationIncludesHeaders()
        {
            var message = new Message.Message();
            message.Headers.Add("Subject", "Hello friend!");
            message.Headers.Add("X-Accept-Language", "en-us, en");

            var messageJson = JsonConvert.SerializeObject(message, _requestSerializerSettings);

            Assert.IsTrue(messageJson.Contains("{\"headers\":{\"Subject\":\"Hello friend!\",\"X-Accept-Language\":\"en-us, en\"}}"));
        }
Beispiel #59
0
        public async Task TestSendMessageWithHeadersAsync()
        {
            var client = new Client(ApiKey);
            var message = new Message.Message
                {
                    Uid = Guid.NewGuid().ToString(),
                    Recipient = new Recipient("*****@*****.**"),
                    RecipientOverride = RecipientOverride,
                    Text = "This email should have a custom from name and subject line."
                };

            message.Headers.Add("From", "*****@*****.**");
            message.Headers.Add("Subject", "This is a custom subject line");

            var responseContainer = await client.SendMessageAsync(message);

            Assert.AreEqual(ResponseStatus.Ok, responseContainer.Response.Status);
        }
Beispiel #60
0
        //---------------------------------------------------------------------------
        #endregion
        //---------------------------------------------------------------------------
        #region Constructors
        //---------------------------------------------------------------------------
        /// <summary>
        /// Конструктор
        /// </summary>
        public Transaction() 
        {
            _Identifier = Transaction.GetRandomNumber();

            _Answer = null;
            _Request = null;
            _Status = TransactionStatus.NotInitialized;
            _TimeOfEnd = 0;
            _TimeOfStart = 0;
            _Type = TransactionType.Undefined;
        }