Example #1
0
        public void InfoFormat(string format, IMessage message, MessageId messageId, int messageSize, IList<Peer> peers, Level logLevel = null)
        {
            if (peers.Count == 0)
            {
                InfoFormat(format, message, messageId, messageSize);
                return;
            }
            if (peers.Count == 1)
            {
                InfoFormat(format, message, messageId, messageSize, peerId: peers[0].Id);
                return;
            }

            var logInfo = GetLogInfo(message);
            if (!logInfo.Logger.IsInfoEnabled)
                return;

            var messageText = logInfo.GetMessageText(message);
            var otherPeersCount = peers.Count - 1;
            var peerIdText = otherPeersCount > 1
                ? peers[0].Id + " and " + otherPeersCount + " other peers"
                : peers[0].Id + " and " + otherPeersCount + " other peer";

            _logger.Logger.Log(_loggerType, logLevel ?? Level.Info, string.Format(format, messageText, messageId, messageSize, peerIdText), null);
        }
 public MessageExecutionCompleted(MessageId sourceCommandId, MessageTypeId payloadTypeId, byte[] payload)
 {
     SourceCommandId = sourceCommandId;
     ErrorCode = 0;
     PayloadTypeId = payloadTypeId;
     Payload = payload;
 }
Example #3
0
 public MessagePublished(MessageId id, UserId author, string content)
     : this()
 {
     Content = content;
     Id = id;
     Author = author;
 }
Example #4
0
        internal Task<MqttCommand> WaitForCommand(CommandMessage message, MessageId messageId, TimeSpan timeout)
        {
            lock (_desireLock)
            {
                var maybeLoved =
                    _unlovedCommands.FirstOrDefault(c => c.MessageId == messageId && c.CommandMessage == message);

                if (maybeLoved != null)
                {
                    var tcs = new TaskCompletionSource<MqttCommand>();
                    tcs.SetResult(maybeLoved);
                    return tcs.Task;
                }

                MqttCommand result = null;
                var wait = new ManualResetEvent(false);

                var d = new Desire(message, messageId, cmd =>
                    {
                        result = cmd;
                        wait.Set();
                    });

                _desireCache.AddAndRemoveDuplicates(d);

                return Task<MqttCommand>.Factory.StartNew(() =>
                    {
                        wait.WaitOne(timeout);
                        return result;
                    });
            }
        }
Example #5
0
 public TransportMessage(MessageTypeId messageTypeId, byte[] messageBytes, OriginatorInfo originator, MessageId messageId)
 {
     Id = messageId;
     MessageTypeId = messageTypeId;
     MessageBytes = messageBytes;
     Originator = originator;
 }
Example #6
0
 public MessageWithId(MessageId id, byte attributes, byte[] key, byte[] value, uint crc32)
 {
     Attributes = attributes;
     Id = id;
     Key = key;
     Value = value;
     Crc32 = crc32;
 }
        public SentMessageWithCachedReplies(MessageId messageId, ReplyStream replyStream)
        {
            if (messageId == null) throw new ArgumentNullException("messageId");
            if (replyStream == null) throw new ArgumentNullException("replyStream");

            _messageId = messageId;
            _replyStream = replyStream;
        }
Example #8
0
        public void DebugFormat(string format, IMessage message, MessageId? messageId = null, int messageSize = 0, PeerId peerId = default(PeerId))
        {
            var logInfo = GetLogInfo(message);
            if (!logInfo.Logger.IsDebugEnabled)
                return;

            var messageText = logInfo.GetMessageText(message);
            _logger.DebugFormat(format, messageText, messageId, messageSize, peerId);
        }
		public static void TraceData( this TraceSource source, MessageId id, params object[] data )
		{
			Contract.Assert( source != null );

			source.TraceData(
				_typeTable[ id ],
				( int )id,
				data
			);
		}
Example #10
0
 /// <summary>
 /// 通过“消息ID”、“参数类型”和“字节类型的参数值”执行操作
 /// </summary>
 /// <param name="msgId">消息ID的枚举值</param>
 /// <param name="pmtType">参数的类型枚举值</param>
 /// <param name="pmtValueByte">字节类型的参数值</param>
 /// <returns></returns>
 public Byte[] OperateCommand(MessageId msgId, ParameterType pmtType, Byte pmtValueByte)
 {
     return OperateCommand(msgId,
         new Parameter(pmtType,
             new List<Byte> {
                 pmtValueByte
             }
         )
     );
 }
Example #11
0
        public void Roundtrip()
        {
            var id = MessageId.CreateNew(10);

            var bytes = id.GetBytes();
            var restored = new MessageId(bytes);
            Assert.AreEqual(id.GetOffset(), restored.GetOffset(), "offset");
            Assert.AreEqual(id.GetTimeUtc(), restored.GetTimeUtc(), "time");
            Assert.AreEqual(id.GetRand(), restored.GetRand(), "rand");
        }
Example #12
0
		/// <summary>
		/// 	Outputs the trace message for the interesting event.
		/// </summary>
		/// <param name="id">
		/// 	<see cref="MessageId" /> for the trace message.
		/// </param>
		/// <param name="format">
		/// 	The format string of the descriptive message.
		/// </param>
		/// <param name="args">
		/// 	The format arguments of the descriptive message.
		/// </param>
		public static void TraceEvent ( MessageId id, string format, params object[] args )
		{
			if ( args == null || args.Length == 0 )
			{
				_source.TraceEvent( _typeTable[ id ], ( int )id, format );
			}
			else
			{
				_source.TraceEvent( _typeTable[ id ], ( int )id, format, args );
			}
		}
Example #13
0
        public Desire(CommandMessage msg, MessageId id, Action<MqttCommand> fulfilled)
        {
            if (fulfilled == null)
            {
                throw new ArgumentNullException("fulfilled", "The fulfilled action cannot be null");
            }

            Message = msg;
            MessageId = id;
            _fulfilled = fulfilled;
        }
Example #14
0
        internal bool TryGetAndRemove(CommandMessage commandMessage, MessageId messageId, out Desire desire)
        {
            int key = GetKeyFrom(commandMessage, messageId);
            if (_desires.TryGetValue(key, out desire))
            {
                _desires.Remove(key);
                return true;
            }

            return false;
        }
		public static void TraceEvent( this TraceSource source, MessageId id, string format, params object[] args )
		{
			Contract.Assert( source != null );

			source.TraceEvent(
				_typeTable[ id ],
				( int )id,
				format,
				args
			);
		}
Example #16
0
        public Subscribe(IEnumerable<Subscription> subscriptions, MessageId messageId)
            : this(new FixedHeader(CommandMessage.SUBSCRIBE), null)
        {
            Header.QualityOfService = QualityOfService.AtLeastOnce;

            if (subscriptions != null)
            {
                Subscriptions.AddRange(subscriptions);
            }

            MessageId = messageId;
        }
 public ReplyMessagePublished(
     MessageId replyId, 
     UserId replier, 
     string replyContent, 
     MessageId parentId)
     : this()
 {
     ReplyId = replyId;
     Replier = replier;
     ReplyContent = replyContent;
     ParentId = parentId;
 }
Example #18
0
        public Task NotifyLastReplyReceived(MessageId relatedToMessageId)
        {
            return Task.Run(() =>
            {
                var replyStream = _cache.Remove(relatedToMessageId) as ReplyStream;
                if (replyStream == null)
                {
                    return;
                }

                replyStream.NotifyCompleted();
            });
        }
Example #19
0
        public void OffsetRoundtrip()
        {
            long value = 1;
            for (int i = 0; i < 48; i++) {
                var created = MessageId.CreateNew(value);

                Assert.AreEqual(value, created.GetOffset(), "instance " + created);
                var rehydrated = new MessageId(created.GetBytes());
                Assert.AreEqual(value, rehydrated.GetOffset(), "roundtrip");

                value = value << 1;
            }
        }
Example #20
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));
        }
Example #21
0
        public Task ReplyReceived(object reply, MessageId relatedToMessageId)
        {
            CheckDisposed();
            return Task.Run(() =>
            {
                var replyStream = _cache.Get(relatedToMessageId) as ReplyStream;
                if (replyStream == null)
                {
                    return;
                }

                replyStream.NotifyReplyReceived(reply);
            });
        }
Example #22
0
        public void RandRoundtrip()
        {
            long value = 1;
            for (int i = 0; i < 32; i++)
            {
                var created = new MessageId(0, 0, i);

                Assert.AreEqual(i, created.GetRand(), "instance " + created);
                var rehydrated = new MessageId(created.GetBytes());
                Assert.AreEqual(i, rehydrated.GetRand(), "roundtrip");

                value = value << 1;
            }
        }
Example #23
0
        public RabbitMqMessage(
            string message,
            IReadOnlyDictionary<string, string> headers,
            Exchange exchange,
            RoutingKey routingKey,
            MessageId messageId)
        {
            if (string.IsNullOrEmpty(message)) throw new ArgumentNullException(nameof(message));
            if (headers == null) throw new ArgumentNullException(nameof(headers));
            if (exchange == null) throw new ArgumentNullException(nameof(exchange));
            if (routingKey == null) throw new ArgumentNullException(nameof(routingKey));
            if (messageId == null) throw new ArgumentNullException(nameof(messageId));

            Message = message;
            Headers = headers;
            Exchange = exchange;
            RoutingKey = routingKey;
            MessageId = messageId;
        }
Example #24
0
        /// <summary>
        /// 通过“消息ID”和“参数列表”获取消息报文字节数组
        /// </summary>
        /// <param name="msgId">
        /// 消息ID
        ///     <para>UInt16类型,长度为2个字节</para>
        /// </param>
        /// <param name="pmtList">参数列表</param>
        /// <returns></returns>
        protected Byte[] GetDatagram(MessageId msgId, List<Parameter> pmtList)
        {
            // 获取消息体对象
            MessageBody mb = new MessageBody(
                msgId,
                DevId,
                pmtList);

            // 获取消息体字节数组
            Byte[] msgBody = mb.GetBody();

            // 获取消息头对象
            MessageHead mh = new MessageHead(
                MessageType,
                (UInt16)(msgBody.Length),
                Counter.Instance.SeqNumber++,
                Crc.GetCrc(msgBody));

            // 返回消息报文字节数组
            return new Datagram(mh, mb).GetDatagram();
        }
Example #25
0
 public ShowErrorHelper(IWin32Window owner, MessageId messageId, object[] args)
 {
     _owner = owner;
     _messageId = messageId;
     _args = args;
 }
Example #26
0
 /// <summary>
 /// 通过“消息ID”、“参数类型”和“参数值字节列表”执行操作
 /// </summary>
 /// <param name="msgId">消息ID的枚举值</param>
 /// <param name="pmtType">参数的类型枚举值</param>
 /// <param name="pmtValueByteList">参数值字节列表</param>
 /// <returns></returns>
 public Byte[] OperateCommand(MessageId msgId, ParameterType pmtType, List <Byte> pmtValueByteList)
 {
     return(OperateCommand(msgId,
                           new Parameter(pmtType, pmtValueByteList)
                           ));
 }
 public DisplayMessageHelper(IWin32Window owner, MessageId messageId, object[] parameters)
 {
     _owner      = owner;
     _messageId  = messageId;
     _parameters = parameters;
 }
Example #28
0
        public PersistentMessage Dequeue(string subqueue)
        {
            Api.JetSetCurrentIndex(session, msgs, "by_sub_queue");
            Api.MakeKey(session, msgs, subqueue, Encoding.Unicode, MakeKeyGrbit.NewKey);

            if (Api.TrySeek(session, msgs, SeekGrbit.SeekGE) == false)
            {
                return(null);
            }

            Api.MakeKey(session, msgs, subqueue, Encoding.Unicode, MakeKeyGrbit.NewKey | MakeKeyGrbit.FullColumnEndLimit);
            try
            {
                Api.JetSetIndexRange(session, msgs, SetIndexRangeGrbit.RangeInclusive | SetIndexRangeGrbit.RangeUpperLimit);
            }
            catch (EsentErrorException e)
            {
                if (e.Error != JET_err.NoCurrentRecord)
                {
                    throw;
                }
                return(null);
            }

            do
            {
                var id = new MessageId
                {
                    MessageIdentifier = new Guid(Api.RetrieveColumn(session, msgs, msgsColumns["msg_id"])),
                    SourceInstanceId  = new Guid(Api.RetrieveColumn(session, msgs, msgsColumns["instance_id"]))
                };

                var status = (MessageStatus)Api.RetrieveColumnAsInt32(session, msgs, msgsColumns["status"]).Value;

                logger.DebugFormat("Scanning incoming message {2} on '{0}/{1}' with status {3}",
                                   queueName, subqueue, id, status);

                if (status != MessageStatus.ReadyToDeliver)
                {
                    continue;
                }

                try
                {
                    using (var update = new Update(session, msgs, JET_prep.Replace))
                    {
                        Api.SetColumn(session, msgs, msgsColumns["status"], (int)MessageStatus.Processing);
                        update.Save();
                    }
                }
                catch (EsentErrorException e)
                {
                    logger.DebugFormat("Write conflict on '{0}/{1}' for {2}, skipping message",
                                       queueName, subqueue, id);
                    if (e.Error == JET_err.WriteConflict)
                    {
                        continue;
                    }
                    throw;
                }
                var bookmark = new MessageBookmark {
                    QueueName = queueName
                };
                Api.JetGetBookmark(session, msgs, bookmark.Bookmark, bookmark.Size, out bookmark.Size);
                changeNumberOfMessages(-1);

                logger.DebugFormat("Dequeuing message {2} from '{0}/{1}'",
                                   queueName, subqueue, id);

                var headersAsQueryString = Api.RetrieveColumnAsString(session, msgs, msgsColumns["headers"]);

                var message = new PersistentMessage
                {
                    Bookmark = bookmark,
                    Headers  = HttpUtility.ParseQueryString(headersAsQueryString),
                    Queue    = queueName,
                    SentAt   = DateTime.FromOADate(Api.RetrieveColumnAsDouble(session, msgs, msgsColumns["timestamp"]).Value),
                    Data     = Api.RetrieveColumn(session, msgs, msgsColumns["data"]),
                    Id       = id,
                    SubQueue = subqueue,
                    Status   = (MessageStatus)Api.RetrieveColumnAsInt32(session, msgs, msgsColumns["status"]).Value
                };
                return(message);
            } while (Api.TryMoveNext(session, msgs));

            return(null);
        }
Example #29
0
 public Message PeekById(MessageId id)
 {
     return(queueManager.PeekById(queueName, id));
 }
 public override string ToString() => MessageId?.ToString() ?? "<unknown reference>";
Example #31
0
 /// <summary>
 /// 异步
 /// </summary>
 static public void BroadcastAsync <T, U>(MessageId eventType, T arg1, U arg2)
 {
     DoBroadcast <T, U>((uint)eventType, arg1, arg2, true);
 }
Example #32
0
 /// <summary>
 /// 异步
 /// </summary>
 static public void BroadcastAsync(MessageId eventType)
 {
     DoBroadcast((uint)eventType, true);
 }
Example #33
0
 /// <summary>
 /// 同步
 /// </summary>
 static public void BroadcastSync(MessageId eventType)
 {
     DoBroadcast((uint)eventType, false);
 }
Example #34
0
    protected override Task ProcessBrowserMessage(string msg, CancellationToken token)
    {
        try
        {
            logger.LogTrace($"from-browser: {msg}");
            var res = JObject.Parse(msg);
            if (res["error"] is not null)
            {
                logger.LogDebug($"from-browser: {res}");
            }

            //if (method != "Debugger.scriptParsed" && method != "Runtime.consoleAPICalled")

            if (res["prototype"] != null || res["frames"] != null)
            {
                var msgId = new FirefoxMessageId(null, 0, res["from"].Value <string>());
                // if (pending_cmds.ContainsKey(msgId))
                {
                    // HACK for now, as we don't correctly handle responses yet
                    OnResponse(msgId, Result.FromJsonFirefox(res));
                }
            }
            else if (res["resultID"] == null)
            {
                return(OnEvent(res.ToObject <SessionId>(), res, token));
            }
            else if (res["type"] == null || res["type"].Value <string>() != "evaluationResult")
            {
                var o = JObject.FromObject(new
                {
                    type     = "evaluationResult",
                    resultID = res["resultID"].Value <string>()
                });
                var id    = int.Parse(res["resultID"].Value <string>().Split('-')[1]);
                var msgId = new MessageId(null, id + 1);

                return(SendCommandInternal(msgId, "", o, token));
            }
            else if (res["result"] is JObject && res["result"]["type"].Value <string>() == "object" && res["result"]["class"].Value <string>() == "Array")
            {
                var msgIdNew = new FirefoxMessageId(null, 0, res["result"]["actor"].Value <string>());
                var id       = int.Parse(res["resultID"].Value <string>().Split('-')[1]);

                var msgId       = new FirefoxMessageId(null, id + 1, "");
                var pendingTask = pending_cmds[msgId];
                pending_cmds.Remove(msgId);
                pending_cmds.Add(msgIdNew, pendingTask);
                return(SendCommandInternal(msgIdNew, "", JObject.FromObject(new
                {
                    type = "prototypeAndProperties",
                    to = res["result"]["actor"].Value <string>()
                }), token));
            }
            else
            {
                var id    = int.Parse(res["resultID"].Value <string>().Split('-')[1]);
                var msgId = new FirefoxMessageId(null, id + 1, "");
                if (pending_cmds.ContainsKey(msgId))
                {
                    OnResponse(msgId, Result.FromJsonFirefox(res));
                }
                else
                {
                    return(SendCommandInternal(msgId, "", res, token));
                }
                return(null);
            }
            return(null);
        }
        catch (Exception ex)
        {
            logger.LogError(ex.ToString());
            _runLoop.Fail(ex);
            throw;
        }
    }
Example #35
0
 public TalkActivity(FDCreature creature, MessageId mId)
 {
     this.Creature  = creature;
     this.MessageId = mId;
 }
Example #36
0
        public bool Receive()
        {
            try
            {
                if (m_stream == null)
                {
                    return(true);
                }

                if (!m_receivedSessionId)
                {
                    return(ParseSessionId());
                }

                MessageId messageId = (MessageId)m_reader.ReadByte();
                //Debug.WriteLine(string.Format("Message: {0}", messageId));
                //TODO: Refactor candidate?
                switch (messageId)
                {
                case MessageId.MID_MapFunction:
                    var mapFunc = Messages.MapFunction.Read(m_reader);
                    MapFunction(mapFunc);
                    break;

                case MessageId.MID_MapClass:
                    var mapClass = Messages.MapClass.Read(m_reader);
                    MapClass(mapClass);
                    break;

                case MessageId.MID_MapThread:
                    var mapThread = Messages.MapThread.Read(m_reader);
                    MapThread(mapThread);
                    break;

                case MessageId.MID_EnterFunction:
                    var funcEvent = Messages.FunctionEvent.Read(m_reader);
                    FunctionEvent(messageId, funcEvent);
                    break;

                case MessageId.MID_LeaveFunction:
                case MessageId.MID_TailCall:
                    var funcEvent2 = Messages.FunctionEvent.Read(m_reader);
                    FunctionEvent(messageId, funcEvent2);
                    break;

                case MessageId.MID_CreateThread:
                case MessageId.MID_DestroyThread:
                    var threadEvent = Messages.CreateThread.Read(m_reader);
                    UpdateThread(threadEvent.ThreadId, messageId == MessageId.MID_CreateThread ? true : false, null);
                    break;

                case MessageId.MID_NameThread:
                    var nameThread = Messages.NameThread.Read(m_reader);
                    //asume that dead threads can't be renamed
                    UpdateThread(nameThread.ThreadId, true, nameThread.Name);
                    break;

                case MessageId.MID_Sample:
                    var sample = Messages.Sample.Read(m_reader);
                    ParseSample(sample);
                    break;

                case MessageId.MID_PerfCounter:
                    var counter = Messages.PerfCounter.Read(m_reader);
                    ParseCounter(counter);
                    break;

                case MessageId.MID_CounterName:
                    var counterName = Messages.CounterName.Read(m_reader);
                    NameCounter(counterName);
                    break;

                case MessageId.MID_ObjectAllocated:
                    var objectAllocated = Messages.ObjectAllocated.Read(m_reader);
                    ObjectedAllocated(objectAllocated);
                    break;

                case MessageId.MID_GarbageCollected:
                    var garbageCollected = Messages.GarbageCollected.Read(m_reader);
                    GarbageCollection(garbageCollected);
                    break;

                case MessageId.MID_GenerationSizes:
                    var generationSizes = Messages.GenerationSizes.Read(m_reader);
                    Console.WriteLine("Gen0 size: {0}", generationSizes.Sizes[0]);
                    break;

                case MessageId.MID_KeepAlive:
                    //don't really need to do anything
                    Debug.WriteLine("Keep alive.");
                    break;

                default:
#if DEBUG
                    Debugger.Break();
#endif
                    throw new InvalidOperationException();
                    //break;
                }

                return(true);
            }
            catch (IOException)
            {
                return(false);
            }
        }
Example #37
0
 /// <summary>
 /// 同步
 /// </summary>
 static public void BroadcastSync <T, U, V>(MessageId eventType, T arg1, U arg2, V arg3)
 {
     DoBroadcast <T, U, V>((uint)eventType, arg1, arg2, arg3, false);
 }
Example #38
0
 /// <summary>
 /// 通过“消息ID”初始化消息体对象实例
 ///     <para>默认设备ID为0X0000000000000000,即广播到所有设备</para>
 /// </summary>
 /// <param name="msgId">
 /// 消息ID
 ///     <para>UInt16类型,长度为2个字节</para>
 /// </param>
 public MessageBody(MessageId msgId)
     : this()
 {
     MsgId = msgId;
     DevId = 0X0000000000000000;
 }
Example #39
0
 /// <summary>
 /// 通过“消息ID”、“设备ID”和“参数列表”初始化消息体对象实例
 /// </summary>
 /// <param name="msgId">
 /// 消息ID
 ///     <para>UInt16类型,长度为2个字节</para>
 /// </param>
 /// <param name="devId">
 /// 设备ID
 ///     <para>UInt64类型,长度为8个字节</para>
 /// </param>
 /// <param name="pmtList">
 /// 参数列表
 ///     <para>长度可变</para>
 /// </param>
 public MessageBody(MessageId msgId, UInt64 devId, List<Parameter> pmtList)
     : this()
 {
     MsgId = msgId;
     DevId = devId;
     PmtList = pmtList;
 }
Example #40
0
 public IReaderBuilder StartMessageId(MessageId messageId)
 {
     _startMessageId = messageId;
     return(this);
 }
Example #41
0
 /// <summary>
 ///     Returns the value whether the specified message should be traced in current configuration.
 /// </summary>
 /// <param name="id">
 ///     <see cref="MessageId" /> for the trace message.
 /// </param>
 /// <returns>
 ///     <c>true</c> if the specified message should be traced; otherwise, <c>false</c>.
 /// </returns>
 public static bool ShouldTrace(MessageId id)
 {
     return(_source.Switch.ShouldTrace(_typeTable[id]));
 }
Example #42
0
 public HelloRequest(MessageId id, Subscriber subscriber)
     :
     base(id, StandardDialogs.Hello)
 {
     this.Subscriber = subscriber;
 }
Example #43
0
        public void ProcessArrow(TCPConnection TCPConnection)
        {
            #region Start

            //TCPConnection.WriteLineToResponseStream(ServiceBanner);
            TCPConnection.NoDelay = true;

            Byte Byte;
            var  MemoryStream     = new MemoryStream();
            var  EndOfSMTPCommand = EOLSearch.NotYet;
            var  ClientClose      = false;
            var  ServerClose      = false;
            var  MailClientName   = "";

            #endregion

            try
            {
                var MailFroms = new EMailAddressList();
                var RcptTos   = new EMailAddressList();

                TCPConnection.WriteLineSMTP(SMTPStatusCode.ServiceReady,
                                            _DefaultServerName + " ESMTP Vanaheimr Hermod Mail Transport Service");

                do
                {
                    switch (TCPConnection.TryRead(out Byte, MaxInitialWaitingTimeMS: ReadTimeout))
                    {
                        // 421 4.4.2 mail.ahzf.de Error: timeout exceeded

                        #region DataAvailable

                    case TCPClientResponse.DataAvailable:

                        #region Check for end of SMTP line...

                        if (EndOfSMTPCommand == EOLSearch.NotYet)
                        {
                            // \n
                            if (Byte == 0x0a)
                            {
                                EndOfSMTPCommand = EOLSearch.EoL_Found;
                            }
                            // \r
                            else if (Byte == 0x0d)
                            {
                                EndOfSMTPCommand = EOLSearch.R_Read;
                            }
                        }

                        // \n after a \r
                        else if (EndOfSMTPCommand == EOLSearch.R_Read)
                        {
                            if (Byte == 0x0a)
                            {
                                EndOfSMTPCommand = EOLSearch.EoL_Found;
                            }
                            else
                            {
                                EndOfSMTPCommand = EOLSearch.NotYet;
                            }
                        }

                        #endregion

                        MemoryStream.WriteByte(Byte);

                        #region If end-of-line -> process data...

                        if (EndOfSMTPCommand == EOLSearch.EoL_Found)
                        {
                            if (MemoryStream.Length > 0)
                            {
                                var RequestTimestamp = DateTime.Now;

                                #region Check UTF8 encoding

                                var SMTPCommand = String.Empty;

                                try
                                {
                                    SMTPCommand = Encoding.UTF8.GetString(MemoryStream.ToArray()).Trim();

                                    Debug.WriteLine("<< " + SMTPCommand);
                                }
                                catch (Exception e)
                                {
                                    NotifyErrors(TCPConnection,
                                                 RequestTimestamp,
                                                 "",
                                                 SMTPStatusCode.SyntaxError,
                                                 Error: "Protocol Error: Invalid UTF8 encoding!");
                                }

                                #endregion

                                #region Try to parse SMTP commands

                                #region ""

                                if (SMTPCommand == "")
                                {
                                }

                                #endregion

                                #region HELO <MailClientName>

                                else if (SMTPCommand.ToUpper().StartsWith("HELO"))
                                {
                                    if (SMTPCommand.Trim().Length > 5 && SMTPCommand.Trim()[4] == ' ')
                                    {
                                        MailClientName = SMTPCommand.Trim().Substring(5);

                                        // 250 mail.ahzf.de
                                        TCPConnection.WriteLineSMTP(SMTPStatusCode.Ok, DefaultServerName);
                                    }
                                    else
                                    {
                                        // 501 Syntax: HELO hostname
                                        TCPConnection.WriteLineSMTP(SMTPStatusCode.SyntaxError, "Syntax: HELO hostname");
                                    }
                                }

                                #endregion

                                #region EHLO <MailClientName>

                                else if (SMTPCommand.ToUpper().StartsWith("EHLO"))
                                {
                                    if (SMTPCommand.Trim().Length > 5 && SMTPCommand.Trim()[4] == ' ')
                                    {
                                        MailClientName = SMTPCommand.Trim().Substring(5);

                                        // 250-mail.graphdefined.org
                                        // 250-PIPELINING
                                        // 250-SIZE 204800000
                                        // 250-VRFY
                                        // 250-ETRN
                                        // 250-STARTTLS
                                        // 250-AUTH PLAIN LOGIN CRAM-MD5 DIGEST-MD5
                                        // 250-AUTH=PLAIN LOGIN CRAM-MD5 DIGEST-MD5
                                        // 250-ENHANCEDSTATUSCODES
                                        // 250-8BITMIME
                                        // 250 DSN
                                        TCPConnection.WriteLineSMTP(SMTPStatusCode.Ok,
                                                                    DefaultServerName,
                                                                    "VRFY",
                                                                    _UseTLS     ? "STARTTLS"         : null,
                                                                    _TLSEnabled ? "AUTH PLAIN LOGIN" : null,
                                                                    "SIZE 204800000",
                                                                    "ENHANCEDSTATUSCODES",
                                                                    "8BITMIME");
                                    }
                                    else
                                    {
                                        // 501 Syntax: EHLO hostname
                                        TCPConnection.WriteLineSMTP(SMTPStatusCode.SyntaxError, "Syntax: EHLO hostname");
                                    }
                                }

                                #endregion

                                #region STARTTLS

                                else if (SMTPCommand.ToUpper() == "STARTTLS")
                                {
                                    if (_TLSEnabled)
                                    {
                                        TCPConnection.WriteLineSMTP(SMTPStatusCode.BadCommandSequence, "5.5.1 TLS already started");
                                    }

                                    else if (MailClientName.IsNullOrEmpty())
                                    {
                                        TCPConnection.WriteLineSMTP(SMTPStatusCode.BadCommandSequence, "5.5.1 EHLO/HELO first");
                                    }

                                    else
                                    {
                                        TCPConnection.WriteLineSMTP(SMTPStatusCode.ServiceReady, "2.0.0 Ready to start TLS");

                                        //                                            var _TLSStream = new SslStream(TCPConnection.NetworkStream);
                                        //                                            _TLSStream.AuthenticateAsServer(TLSCert, false, SslProtocols.Tls12, false);
                                        _TLSEnabled = true;
                                    }
                                }

                                #endregion

                                #region AUTH LOGIN|PLAIN|...

                                else if (SMTPCommand.ToUpper().StartsWith("AUTH "))
                                {
                                    if (!_TLSEnabled)
                                    {
                                        TCPConnection.WriteLineSMTP(SMTPStatusCode.BadCommandSequence, "5.5.1 STARTTLS first");
                                    }
                                }

                                #endregion

                                #region MAIL FROM: <SenderMailAddress>

                                else if (SMTPCommand.ToUpper().StartsWith("MAIL FROM"))
                                {
                                    var SMTPCommandParts = SMTPCommand.Split(new Char[2] {
                                        ' ', ':'
                                    }, StringSplitOptions.RemoveEmptyEntries);

                                    if (SMTPCommandParts.Length >= 3)
                                    {
                                        var MailFrom = SMTPCommandParts[2];

                                        if (MailFrom[0] == '<' && MailFrom[MailFrom.Length - 1] == '>')
                                        {
                                            MailFrom = MailFrom.Substring(1, MailFrom.Length - 2);
                                        }

                                        MAIL_FROM_FilterResponse _SMTPFilterResponse = null;

                                        var MAIL_FROMFilterLocal = MAIL_FROMFilter;
                                        if (MAIL_FROMFilterLocal != null)
                                        {
                                            _SMTPFilterResponse = MAIL_FROMFilterLocal(MailFrom);
                                        }

                                        if (_SMTPFilterResponse == null)
                                        {
                                            TCPConnection.WriteLineSMTP(SMTPStatusCode.Ok, "2.1.0 " + MailFrom + " Sender ok");
                                            MailFroms.Add(EMailAddress.Parse(MailFrom));
                                        }

                                        else if (_SMTPFilterResponse.Forward)
                                        {
                                            TCPConnection.WriteLineSMTP(SMTPStatusCode.Ok, "2.1.0 " + MailFrom + " " + _SMTPFilterResponse.Description);
                                            MailFroms.Add(EMailAddress.Parse(MailFrom));
                                        }

                                        else
                                        {
                                            TCPConnection.WriteLineSMTP(SMTPStatusCode.TransactionFailed, "5.7.1 " + _SMTPFilterResponse.Description);
                                        }
                                    }
                                    else
                                    {
                                        // 501 Syntax: EHLO hostname
                                        TCPConnection.WriteLineSMTP(SMTPStatusCode.SyntaxError, "Syntax: MAIL FROM: <*****@*****.**>");
                                    }
                                }

                                #endregion

                                #region RCPT TO: <ReceiverMailAddress>

                                else if (SMTPCommand.ToUpper().StartsWith("RCPT TO"))
                                {
                                    var SMTPCommandParts = SMTPCommand.Split(new Char[2] {
                                        ' ', ':'
                                    }, StringSplitOptions.RemoveEmptyEntries);

                                    if (SMTPCommandParts.Length >= 3)
                                    {
                                        var RcptTo = SMTPCommandParts[2];

                                        // telnet: > telnet mx1.example.com smtp
                                        // telnet: Trying 192.0.2.2...
                                        // telnet: Connected to mx1.example.com.
                                        // telnet: Escape character is '^]'.
                                        // server: 220 mx1.example.com ESMTP server ready Tue, 20 Jan 2004 22:33:36 +0200
                                        // client: HELO client.example.com
                                        // server: 250 mx1.example.com
                                        // client: MAIL from: <*****@*****.**>
                                        // server: 250 Sender <*****@*****.**> Ok
                                        //         250 2.1.0 Ok
                                        // client: RCPT to: <*****@*****.**>
                                        // server: 250 Recipient <*****@*****.**> Ok

                                        // server: 554 5.7.1 <*****@*****.**>: Relay access denied

                                        // client: DATA
                                        // server: 354 Ok Send data ending with <CRLF>.<CRLF>
                                        // client: From: [email protected]
                                        // client: To: [email protected]
                                        // client: Subject: Test message
                                        // client:
                                        // client: This is a test message.
                                        // client: .
                                        // server: 250 Message received: [email protected]
                                        // client: QUIT
                                        // server: 221 mx1.example.com ESMTP server closing connection

                                        // MAIL FROM: [email protected]
                                        // 250 2.1.0 [email protected]... Sender ok
                                        //
                                        // RCPT TO: [email protected]
                                        // 250 2.1.0 [email protected]... Recipient ok

                                        if (RcptTo[0] == '<' && RcptTo[RcptTo.Length - 1] == '>')
                                        {
                                            RcptTo = RcptTo.Substring(1, RcptTo.Length - 2);
                                        }

                                        RCPT_TO_FilterResponse _SMTPFilterResponse = null;

                                        var RCPT_TOFilterLocal = RCPT_TOFilter;
                                        if (RCPT_TOFilterLocal != null)
                                        {
                                            _SMTPFilterResponse = RCPT_TOFilterLocal(RcptTo);
                                        }

                                        if (_SMTPFilterResponse == null)
                                        {
                                            TCPConnection.WriteLineSMTP(SMTPStatusCode.Ok, "2.1.0 " + RcptTo + " Recipient ok");
                                            RcptTos.Add(EMailAddress.Parse(RcptTo));
                                        }

                                        else if (_SMTPFilterResponse.Forward)
                                        {
                                            TCPConnection.WriteLineSMTP(SMTPStatusCode.Ok, "2.1.0 " + RcptTo + " " + _SMTPFilterResponse.Description);
                                            RcptTos.Add(EMailAddress.Parse(RcptTo));
                                        }

                                        else
                                        {
                                            TCPConnection.WriteLineSMTP(SMTPStatusCode.TransactionFailed, "5.7.1 " + _SMTPFilterResponse.Description);
                                        }
                                    }
                                    else
                                    {
                                        // 501 Syntax: EHLO hostname
                                        TCPConnection.WriteLineSMTP(SMTPStatusCode.SyntaxError, "Syntax: RCPT TO: <*****@*****.**>");
                                    }
                                }

                                #endregion

                                #region DATA

                                else if (SMTPCommand.ToUpper().StartsWith("DATA"))
                                {
                                    if (MailFroms.Count == 0 || RcptTos.Count == 0)
                                    {
                                        TCPConnection.WriteLineSMTP(SMTPStatusCode.BadCommandSequence, "Bad command sequence!");
                                    }

                                    else
                                    {
                                        TCPConnection.WriteLineSMTP(SMTPStatusCode.StartMailInput, "Ok Send data ending with <CRLF>.<CRLF>");

                                        #region Read all e-mail lines...

                                        var MailText = new List <String>();
                                        var MailLine = "";

                                        do
                                        {
                                            MailLine = TCPConnection.ReadLine();

                                            // "." == End-of-EMail...
                                            if (MailLine != null && MailLine != ".")
                                            {
                                                MailText.Add(MailLine);
                                                Debug.WriteLine("<<< " + MailLine);
                                            }
                                        } while (MailLine != ".");

                                        #endregion

                                        #region Try to parse the incoming e-mail...

                                        EMail IncomingMail = null;

                                        try
                                        {
                                            IncomingMail = EMail.Parse(MailText);
                                        }
                                        catch (Exception)
                                        { }

                                        if (IncomingMail == null)
                                        {
                                            TCPConnection.WriteLineSMTP(SMTPStatusCode.TransactionFailed, "The e-mail could not be parsed!");

                                            Debug.WriteLine("[" + DateTime.Now + "] Incoming e-mail could not be parsed!");
                                            Debug.WriteLine(MailText.AggregateWith(Environment.NewLine));
                                        }

                                        #endregion

                                        #region Generate a MessageId... if needed!

                                        var _MessageId = IncomingMail.MessageId;

                                        if (_MessageId == null)
                                        {
                                            _MessageId   = MessageId.Parse(Guid.NewGuid().ToString() + "@" + _DefaultServerName);
                                            IncomingMail = EMail.Parse(new String[] { "Message-Id: " + _MessageId + Environment.NewLine }.Concat(MailText));
                                        }

                                        #endregion

                                        TCPConnection.WriteLineSMTP(SMTPStatusCode.Ok, "Message received: " + _MessageId);

                                        var OnNotificationLocal = OnNotification;
                                        if (OnNotificationLocal != null)
                                        {
                                            OnNotificationLocal(new EMailEnvelop(MailFrom:      MailFroms,
                                                                                 RcptTo:        RcptTos,
                                                                                 EMail:         IncomingMail,
                                                                                 RemoteSocket:  TCPConnection.RemoteSocket));
                                        }
                                    }
                                }

                                #endregion

                                #region RSET

                                else if (SMTPCommand.ToUpper() == "RSET")
                                {
                                    TCPConnection.WriteLineSMTP(SMTPStatusCode.Ok, "2.0.0 Ok");
                                    MailClientName = "";
                                    MailFroms.Clear();
                                    RcptTos.Clear();
                                }

                                #endregion

                                #region NOOP

                                else if (SMTPCommand.ToUpper() == "NOOP")
                                {
                                    TCPConnection.WriteLineSMTP(SMTPStatusCode.Ok, "2.0.0 Ok");
                                }

                                #endregion

                                #region VRFY

                                else if (SMTPCommand.ToUpper().StartsWith("VRFY"))
                                {
                                    TCPConnection.WriteLineSMTP(SMTPStatusCode.CannotVerifyUserWillAttemptDelivery, "2.0.0 Send some mail. I'll try my best!");
                                    MailClientName = "";
                                    MailFroms.Clear();
                                    RcptTos.Clear();
                                }

                                #endregion

                                #region QUIT

                                else if (SMTPCommand.ToUpper() == "QUIT")
                                {
                                    TCPConnection.WriteLineSMTP(SMTPStatusCode.ServiceClosingTransmissionChannel, "2.0.0 closing connection");
                                    ClientClose = true;
                                }

                                #endregion

                                #region else error...

                                else
                                {
                                    TCPConnection.WriteLineSMTP(SMTPStatusCode.CommandUnrecognized, "2.0.0 I don't understand how to handle '" + SMTPCommand + "'!");

                                    NotifyErrors(TCPConnection,
                                                 RequestTimestamp,
                                                 SMTPCommand.Trim(),
                                                 SMTPStatusCode.BadCommandSequence,
                                                 Error: "Invalid SMTP command!");
                                }

                                #endregion

                                #endregion
                            }

                            MemoryStream.SetLength(0);
                            MemoryStream.Seek(0, SeekOrigin.Begin);
                            EndOfSMTPCommand = EOLSearch.NotYet;
                        }

                        #endregion

                        break;

                        #endregion

                        #region CanNotRead

                    case TCPClientResponse.CanNotRead:
                        ServerClose = true;
                        break;

                        #endregion

                        #region ClientClose

                    case TCPClientResponse.ClientClose:
                        ClientClose = true;
                        break;

                        #endregion

                        #region Timeout

                    case TCPClientResponse.Timeout:
                        ServerClose = true;
                        break;

                        #endregion
                    }
                } while (!ClientClose && !ServerClose);
            }

            #region Process exceptions

            catch (IOException ioe)
            {
                if (ioe.Message.StartsWith("Unable to read data from the transport connection"))
                {
                }
                else if (ioe.Message.StartsWith("Unable to write data to the transport connection"))
                {
                }

                else
                {
                    //if (OnError != null)
                    //    OnError(this, DateTime.Now, ConnectionIdBuilder(newTCPConnection.RemoteIPAddress, newTCPConnection.RemotePort), ioe, MemoryStream);
                }
            }

            catch (Exception e)
            {
                //if (OnError != null)
                //    OnError(this, DateTime.Now, ConnectionIdBuilder(newTCPConnection.RemoteIPAddress, newTCPConnection.RemotePort), e, MemoryStream);
            }

            #endregion

            #region Close the TCP connection

            try
            {
                TCPConnection.Close((ClientClose) ? ConnectionClosedBy.Client : ConnectionClosedBy.Server);
            }
            catch (Exception)
            { }

            #endregion
        }
Example #44
0
 public MessageData(MessageId id, object data = null)
 {
     Id   = id;
     Data = data;
 }
Example #45
0
 public void CancelRequest(MessageId id)
 {
     RequestContext.Features.Get <IRequestCancellationFeature>().TryCancel(id);
 }
        public void TestEncode()
        {
            GameInfoMessage gim = new GameInfoMessage(MessageId.Create(), 1, 2, "1.2.3", "4.5.6");

            byte[] bytes = gim.Encode();

            byte[] messagePIdBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(gim.msgId.Pid));
            byte[] messageSeqBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(gim.msgId.Seq));
            byte[] convPIdBytes    = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(gim.convId.Pid));
            byte[] convSeqBytes    = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(gim.convId.Seq));

            int currByte = 0;

            //MessageId
            //pid
            Assert.AreEqual(messagePIdBytes[0], bytes[currByte], $"bytes[{currByte++}] did not match asserted value");
            Assert.AreEqual(messagePIdBytes[1], bytes[currByte], $"bytes[{currByte++}] did not match asserted value");
            //seq
            Assert.AreEqual(messageSeqBytes[0], bytes[currByte], $"bytes[{currByte++}] did not match asserted value");
            Assert.AreEqual(messageSeqBytes[1], bytes[currByte], $"bytes[{currByte++}] did not match asserted value");

            //ConversationId
            //pid
            Assert.AreEqual(convPIdBytes[0], bytes[currByte], $"bytes[{currByte++}] did not match asserted value");
            Assert.AreEqual(convPIdBytes[1], bytes[currByte], $"bytes[{currByte++}] did not match asserted value");
            //seq
            Assert.AreEqual(convSeqBytes[0], bytes[currByte], $"bytes[{currByte++}] did not match asserted value");
            Assert.AreEqual(convSeqBytes[1], bytes[currByte], $"bytes[{currByte++}] did not match asserted value");

            //short MessageType
            Assert.AreEqual(0, bytes[currByte], $"bytes[{currByte++}] did not match asserted value");
            Assert.AreEqual(2, bytes[currByte], $"bytes[{currByte++}] did not match asserted value");

            //short GameId
            Assert.AreEqual(0, bytes[currByte], $"bytes[{currByte++}] did not match asserted value");
            Assert.AreEqual(1, bytes[currByte], $"bytes[{currByte++}] did not match asserted value");

            //short UserId
            Assert.AreEqual(0, bytes[currByte], $"bytes[{currByte++}] did not match asserted value");
            Assert.AreEqual(2, bytes[currByte], $"bytes[{currByte++}] did not match asserted value");

            //string GMAddress
            Assert.AreEqual(0, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(10, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(0, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(49, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(0, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(46, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(0, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(50, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(0, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(46, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(0, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(51, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");

            //string UAAddress
            Assert.AreEqual(0, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(10, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(0, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(52, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(0, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(46, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(0, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(53, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(0, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(46, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(0, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
            Assert.AreEqual(54, bytes[currByte], $"bytes[{currByte++}] did note match asserted value");
        }
Example #47
0
 /// <summary>
 /// 通过“消息ID”、“参数类型”和“字符串类型的参数值”执行操作
 /// </summary>
 /// <param name="msgId">消息ID的枚举值</param>
 /// <param name="pmtType">参数的类型枚举值</param>
 /// <param name="pmtValueString">字符串类型的参数值</param>
 /// <returns></returns>
 public Byte[] OperateCommand(MessageId msgId, ParameterType pmtType, string pmtValueString)
 {
     return(OperateCommand(msgId, pmtType, pmtValueString.ToByteArray()));
 }
Example #48
0
 public RequestCancellingEventArgs(MessageId requestId)
 {
     RequestId = requestId;
 }
Example #49
0
 /// <summary>
 /// 通过“消息ID”、“参数类型”和“字节数组类型的参数值”执行操作
 /// </summary>
 /// <param name="msgId">消息ID的枚举值</param>
 /// <param name="pmtType">参数的类型枚举值</param>
 /// <param name="byteArray">字节数组类型的参数值</param>
 /// <returns></returns>
 public Byte[] OperateCommand(MessageId msgId, ParameterType pmtType, Byte[] byteArray)
 {
     return(OperateCommand(msgId, pmtType, GetByteList(byteArray)));
 }
Example #50
0
        public static Type GetCorrespondingMessageType(this MessageId messageId)
        {
            switch (messageId)
            {
            case MessageId.CheckShamRequest:
                return(typeof(Message <CheckShamRequest>));

            case MessageId.DestroyPieceRequest:
                return(typeof(Message <DestroyPieceRequest>));

            case MessageId.DiscoverRequest:
                return(typeof(Message <DiscoverRequest>));

            case MessageId.ExchangeInformationResponse:
                return(typeof(Message <ExchangeInformationResponse>));

            case MessageId.ExchangeInformationRequest:
                return(typeof(Message <ExchangeInformationRequest>));

            case MessageId.JoinRequest:
                return(typeof(Message <JoinRequest>));

            case MessageId.MoveRequest:
                return(typeof(Message <MoveRequest>));

            case MessageId.PickUpPieceRequest:
                return(typeof(Message <PickUpPieceRequest>));

            case MessageId.PutDownPieceRequest:
                return(typeof(Message <PutDownPieceRequest>));

            case MessageId.CheckShamResponse:
                return(typeof(Message <CheckShamResponse>));

            case MessageId.DestroyPieceResponse:
                return(typeof(Message <DestroyPieceResponse>));

            case MessageId.DiscoverResponse:
                return(typeof(Message <DiscoverResponse>));

            case MessageId.EndGameMessage:
                return(typeof(Message <EndGamePayload>));

            case MessageId.StartGameMessage:
                return(typeof(Message <StartGamePayload>));

            case MessageId.ExchangeInformationRequestForward:
                return(typeof(Message <ExchangeInformationRequestForward>));

            case MessageId.JoinResponse:
                return(typeof(Message <JoinResponse>));

            case MessageId.MoveResponse:
                return(typeof(Message <MoveResponse>));

            case MessageId.PickUpPieceResponse:
                return(typeof(Message <PickUpPieceResponse>));

            case MessageId.PutDownPieceResponse:
                return(typeof(Message <PutDownPieceResponse>));

            case MessageId.ExchangeInformationResponseForward:
                return(typeof(Message <ExchangeInformationResponseForward>));

            case MessageId.MoveError:
                return(typeof(Message <MoveError>));

            case MessageId.PickUpPieceError:
                return(typeof(Message <PickUpPieceError>));

            case MessageId.PutDownPieceError:
                return(typeof(Message <PutDownPieceError>));

            case MessageId.IgnoredDelayError:
                return(typeof(Message <IgnoredDelayError>));

            case MessageId.UndefinedError:
                return(typeof(Message <UndefinedError>));

            default:
                throw new ArgumentException($"No payload type corresponding to message: {messageId.ToString()}");
            }
        }
Example #51
0
 public MessageExecutionCompleted(MessageId sourceCommandId, int errorCode)
     : this(sourceCommandId, errorCode, null)
 {
 }
Example #52
0
 public MessageExecutionCompleted(MessageId sourceCommandId, int errorCode, string responseMessage)
 {
     SourceCommandId = sourceCommandId;
     ErrorCode       = errorCode;
     ResponseMessage = responseMessage ?? string.Empty;
 }
        // GET: /Bedrijf/Edit/5
        public ActionResult Edit(int id, MessageId? message)
        {
            ViewBag.StatusMessage =
                message == MessageId.ChangeSuccess ? "Uw wijzigingen zijn succesvol opgeslagen."
                : message == MessageId.ChangeFaild ? "Uw wijzigingen zijn onsuccesvol opgeslagen."
                : message == MessageId.Error ? "Een fout deed zich voor."
                : "";

            Bedrijf bedrijf = bedrijfRepository.FindById(id);

            if (bedrijf == null)
            {
                return HttpNotFound();
            }
            return View(bedrijf);
        }
Example #54
0
        public static MessageExecutionCompleted Failure(MessageId sourceCommandId, IEnumerable <Exception> exceptions)
        {
            var errorStatus = CommandResult.GetErrorStatus(exceptions);

            return(new MessageExecutionCompleted(sourceCommandId, errorStatus.Code, errorStatus.Message));
        }
Example #55
0
 /// <summary>
 /// 通过“消息ID”和“设备ID”初始化消息体对象实例
 /// </summary>
 /// <param name="msgId">
 /// 消息ID
 ///     <para>UInt16类型,长度为2个字节</para>
 /// </param>
 /// <param name="devId">
 /// 设备ID
 ///     <para>UInt64类型,长度为8个字节</para>
 /// </param>
 public MessageBody(MessageId msgId, UInt64 devId)
     : this()
 {
     MsgId = msgId;
     DevId = devId;
 }
Example #56
0
 /// <summary>
 ///     Outputs the raw data for the interesting event.
 /// </summary>
 /// <param name="id">
 ///     <see cref="MessageId" /> for the trace data.
 /// </param>
 /// <param name="data">
 ///     The raw data for this event.
 /// </param>
 public static void TraceData(MessageId id, params object[] data)
 {
     _source.TraceData(_typeTable[id], ( int )id, data);
 }
Example #57
0
    //from ide
    protected override async Task <bool> AcceptCommand(MessageId sessionId, JObject args, CancellationToken token)
    {
        if (args["type"] == null)
        {
            return(false);
        }

        switch (args["type"].Value <string>())
        {
        case "resume":
        {
            if (!contexts.TryGetValue(sessionId, out ExecutionContext context))
            {
                return(false);
            }
            context.PausedOnWasm = false;
            if (context.CallStack == null)
            {
                return(false);
            }
            if (args["resumeLimit"] == null || args["resumeLimit"].Type == JTokenType.Null)
            {
                await OnResume(sessionId, token);

                return(false);
            }
            switch (args["resumeLimit"]["type"].Value <string>())
            {
            case "next":
                await context.SdbAgent.Step(context.ThreadId, StepKind.Over, token);

                break;

            case "finish":
                await context.SdbAgent.Step(context.ThreadId, StepKind.Out, token);

                break;

            case "step":
                await context.SdbAgent.Step(context.ThreadId, StepKind.Into, token);

                break;
            }
            await SendResume(sessionId, token);

            return(true);
        }

        case "isAttached":
        case "attach":
        {
            var ctx = GetContextFixefox(sessionId);
            ctx.ThreadName = args["to"].Value <string>();
            break;
        }

        case "source":
        {
            return(await OnGetScriptSource(sessionId, args["to"].Value <string>(), token));
        }

        case "getBreakableLines":
        {
            return(await OnGetBreakableLines(sessionId, args["to"].Value <string>(), token));
        }

        case "getBreakpointPositionsCompressed":
        {
            //{"positions":{"39":[20,28]},"from":"server1.conn2.child10/source27"}
            if (args["to"].Value <string>().StartsWith("dotnet://"))
            {
                var line    = new JObject();
                var offsets = new JArray();
                offsets.Add(0);
                line.Add(args["query"]["start"]["line"].Value <string>(), offsets);
                var o = JObject.FromObject(new
                    {
                        positions = line,
                        from      = args["to"].Value <string>()
                    });

                await SendEventInternal(sessionId, "", o, token);

                return(true);
            }
            break;
        }

        case "setBreakpoint":
        {
            if (!contexts.TryGetValue(sessionId, out ExecutionContext context))
            {
                return(false);
            }
            var req = JObject.FromObject(new
                {
                    url          = args["location"]["sourceUrl"].Value <string>(),
                    lineNumber   = args["location"]["line"].Value <int>() - 1,
                    columnNumber = args["location"]["column"].Value <int>()
                });

            var bp = context.BreakpointRequests.Where(request => request.Value.CompareRequest(req)).FirstOrDefault();

            if (bp.Value != null)
            {
                bp.Value.UpdateCondition(args["options"]?["condition"]?.Value <string>());
                await SendCommand(sessionId, "", args, token);

                return(true);
            }

            string bpid = Interlocked.Increment(ref context.breakpointId).ToString();

            if (args["options"]?["condition"]?.Value <string>() != null)
            {
                req["condition"] = args["options"]?["condition"]?.Value <string>();
            }

            var  request = BreakpointRequest.Parse(bpid, req);
            bool loaded  = context.Source.Task.IsCompleted;

            context.BreakpointRequests[bpid] = request;

            if (await IsRuntimeAlreadyReadyAlready(sessionId, token))
            {
                DebugStore store = await RuntimeReady(sessionId, token);

                Log("verbose", $"BP req {args}");
                await SetBreakpoint(sessionId, store, request, !loaded, false, token);
            }
            await SendCommand(sessionId, "", args, token);

            return(true);
        }

        case "removeBreakpoint":
        {
            if (!contexts.TryGetValue(sessionId, out ExecutionContext context))
            {
                return(false);
            }
            Result resp = await SendCommand(sessionId, "", args, token);

            var reqToRemove = JObject.FromObject(new
                {
                    url          = args["location"]["sourceUrl"].Value <string>(),
                    lineNumber   = args["location"]["line"].Value <int>() - 1,
                    columnNumber = args["location"]["column"].Value <int>()
                });

            foreach (var req in context.BreakpointRequests.Values)
            {
                if (req.CompareRequest(reqToRemove))
                {
                    foreach (var bp in req.Locations)
                    {
                        var breakpoint_removed = await context.SdbAgent.RemoveBreakpoint(bp.RemoteId, token);

                        if (breakpoint_removed)
                        {
                            bp.RemoteId = -1;
                            bp.State    = BreakpointState.Disabled;
                        }
                    }
                }
            }
            return(true);
        }

        case "prototypeAndProperties":
        case "slice":
        {
            var to = args?["to"].Value <string>().Replace("propertyIterator", "");
            if (!DotnetObjectId.TryParse(to, out DotnetObjectId objectId))
            {
                return(false);
            }
            var res = await RuntimeGetObjectMembers(sessionId, objectId, args, token);

            var variables = ConvertToFirefoxContent(res);
            var o         = JObject.FromObject(new
                {
                    ownProperties = variables,
                    from          = args["to"].Value <string>()
                });
            if (args["type"].Value <string>() == "prototypeAndProperties")
            {
                o.Add("prototype", GetPrototype(objectId, args));
            }
            await SendEvent(sessionId, "", o, token);

            return(true);
        }

        case "prototype":
        {
            if (!DotnetObjectId.TryParse(args?["to"], out DotnetObjectId objectId))
            {
                return(false);
            }
            var o = JObject.FromObject(new
                {
                    prototype = GetPrototype(objectId, args),
                    from      = args["to"].Value <string>()
                });
            await SendEvent(sessionId, "", o, token);

            return(true);
        }

        case "enumSymbols":
        {
            if (!DotnetObjectId.TryParse(args?["to"], out DotnetObjectId objectId))
            {
                return(false);
            }
            var o = JObject.FromObject(new
                {
                    type  = "symbolIterator",
                    count = 0,
                    actor = args["to"].Value <string>() + "symbolIterator"
                });

            var iterator = JObject.FromObject(new
                {
                    iterator = o,
                    from     = args["to"].Value <string>()
                });

            await SendEvent(sessionId, "", iterator, token);

            return(true);
        }

        case "enumProperties":
        {
            //{"iterator":{"type":"propertyIterator","actor":"server1.conn19.child63/propertyIterator73","count":3},"from":"server1.conn19.child63/obj71"}
            if (!DotnetObjectId.TryParse(args?["to"], out DotnetObjectId objectId))
            {
                return(false);
            }
            var res = await RuntimeGetObjectMembers(sessionId, objectId, args, token);

            var variables = ConvertToFirefoxContent(res);
            var o         = JObject.FromObject(new
                {
                    type  = "propertyIterator",
                    count = variables.Count,
                    actor = args["to"].Value <string>() + "propertyIterator"
                });

            var iterator = JObject.FromObject(new
                {
                    iterator = o,
                    from     = args["to"].Value <string>()
                });

            await SendEvent(sessionId, "", iterator, token);

            return(true);
        }

        case "getEnvironment":
        {
            if (!DotnetObjectId.TryParse(args?["to"], out DotnetObjectId objectId))
            {
                return(false);
            }
            var ctx = GetContextFixefox(sessionId);
            if (ctx.CallStack == null)
            {
                return(false);
            }
            Frame scope = ctx.CallStack.FirstOrDefault(s => s.Id == objectId.Value);
            var   res   = await RuntimeGetObjectMembers(sessionId, objectId, args, token);

            var variables = ConvertToFirefoxContent(res);
            var o         = JObject.FromObject(new
                {
                    actor     = args["to"].Value <string>() + "_0",
                    type      = "function",
                    scopeKind = "function",
                    function  = new
                    {
                        displayName = scope.Method.Name
                    },
                    bindings = new
                    {
                        arguments = new JArray(),
                        variables
                    },
                    from = args["to"].Value <string>()
                });

            await SendEvent(sessionId, "", o, token);

            return(true);
        }

        case "frames":
        {
            ExecutionContext ctx = GetContextFixefox(sessionId);
            if (ctx.PausedOnWasm)
            {
                try
                {
                    await GetFrames(sessionId, ctx, args, token);

                    return(true);
                }
                catch (Exception)         //if the page is refreshed maybe it stops here.
                {
                    await SendResume(sessionId, token);

                    return(true);
                }
            }
            //var ret = await SendCommand(sessionId, "frames", args, token);
            //await SendEvent(sessionId, "", ret.Value["result"]["fullContent"] as JObject, token);
            return(false);
        }

        case "evaluateJSAsync":
        {
            var context = GetContextFixefox(sessionId);
            if (context.CallStack != null)
            {
                var resultID = $"runtimeResult-{context.GetResultID()}";
                var o        = JObject.FromObject(new
                    {
                        resultID,
                        from = args["to"].Value <string>()
                    });
                await SendEvent(sessionId, "", o, token);

                Frame scope = context.CallStack.First <Frame>();

                var     resolver = new MemberReferenceResolver(this, context, sessionId, scope.Id, logger);
                JObject retValue = await resolver.Resolve(args?["text"]?.Value <string>(), token);

                if (retValue == null)
                {
                    retValue = await ExpressionEvaluator.CompileAndRunTheExpression(args?["text"]?.Value <string>(), resolver, logger, token);
                }
                var osend = JObject.FromObject(new
                    {
                        type = "evaluationResult",
                        resultID,
                        hasException = false,
                        input        = args?["text"],
                        from         = args["to"].Value <string>()
                    });
                if (retValue["type"].Value <string>() == "object")
                {
                    osend["result"] = JObject.FromObject(new
                        {
                            type        = retValue["type"],
                            @class      = retValue["className"],
                            description = retValue["description"],
                            actor       = retValue["objectId"],
                        });
                }
                else
                {
                    osend["result"]            = retValue["value"];
                    osend["resultType"]        = retValue["type"];
                    osend["resultDescription"] = retValue["description"];
                }
                await SendEvent(sessionId, "", osend, token);
            }
            else
            {
                var ret = await SendCommand(sessionId, "evaluateJSAsync", args, token);

                var o = JObject.FromObject(new
                    {
                        resultID = ret.FullContent["resultID"],
                        from     = args["to"].Value <string>()
                    });
                await SendEvent(sessionId, "", o, token);
                await SendEvent(sessionId, "", ret.FullContent, token);
            }
            return(true);
        }

        case "DotnetDebugger.getMethodLocation":
        {
            var ret = await GetMethodLocation(sessionId, args, token);

            ret.Value["from"] = "internal";
            await SendEvent(sessionId, "", ret.Value, token);

            return(true);
        }

        default:
            return(false);
        }
        return(false);
    }
Example #58
0
 /// <summary>
 /// 同步
 /// </summary>
 static public void BroadcastSync <T>(MessageId eventType, T arg1)
 {
     DoBroadcast <T>((uint)eventType, arg1, false);
 }
        // GET: /Student/Edit/5
        public ActionResult Edit(int id, MessageId? message)
        {
            ViewBag.StatusMessage =
                message == MessageId.ChangeSuccess ? "Uw wijzigingen zijn succesvol opgeslagen."
                : message == MessageId.ChangeFaild ? "Uw wijzigingen zijn onsuccesvol opgeslagen."
                : message == MessageId.Error ? "Een fout deed zich voor."
                : "";

            Student student = studentRepository.FindById(id);
            TempData["fotourl"] = student.Foto;
            ViewBag.fotourl = student.Foto;
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }
Example #60
0
        private void SendToPersistenceService(IMessage message, IEnumerable <Peer> persistentPeers)
        {
            var transportMessage = _serializer.ToTransportMessage(message, MessageId.NextId(), PeerId, InboundEndPoint);

            _innerTransport.Send(transportMessage, persistentPeers);
        }