Esempio n. 1
0
 public void MessageReceive(IReceiveContext context)
 {
     _channelLock.EnterReadLock();
     foreach (var c in _channels)
         c.SendMessage(context.GetMessage());
     _channelLock.ExitReadLock();
 }
Esempio n. 2
0
        public void MessageReceive(IReceiveContext context)
        {
            var message = (JToken)context.GetMessage();
            switch (message.Value<string>("type"))
            {
                case "connect":
                    _client.Ver = message.Value<int>("ver");

                    //인증 시스템을 사용한다
                    if(_mobile.UseAuth)
                    {
                        _client.Auth(message.Value<JObject>("auth"));

                        if(_addPushData != null)
                        {
                            _mobile.Push.AddPush(_client, _addPushData);
                            _addPushData = null;
                        }
                    }
                    break;
                case "msg":
                    _mobile.Call(new Request() { Client = _client, Type = message.Value<string>("name"), Arg = message.Value<JToken>("arg") });
                    break;
                case "add_push":
                    if (_client.GetId() != -1)
                        _mobile.Push.AddPush(_client, message);
                    else
                        _addPushData = message;
                    break;
                case "remove_push":
                    _mobile.Push.RemovePush(_client, message);
                    break;
            }
        }
Esempio n. 3
0
 public void Disconnected(IReceiveContext context)
 {
     channelLock.EnterWriteLock();
     _channels.Remove(context.GetChannel());
     channelLock.ExitWriteLock();
     SendMessage(context.GetChannel() + " 88" + "\r\n> ");
 }
Esempio n. 4
0
 // 클라이언트가 접속시 호출
 public void Connected(IReceiveContext channel)
 {
     JObject o = new JObject();
     o.Add("name", "test");
     o.Add("value", i++);
     channel.GetChannel().SendMessage(o);
 }
Esempio n. 5
0
 // 클라이언트로부터 메시지가 왔을때 호출
 public void MessageReceive(IReceiveContext context)
 {
     context.GetChannel().SendMessage("test" + i++);
     Console.WriteLine("Client Thread " + System.Threading.Thread.CurrentThread.ManagedThreadId + " - " + context.GetMessage());
     if ((string) context.GetMessage() == "test20")
         SocketChannel.ExitEvent.Set();
 }
Esempio n. 6
0
 // 클라이언트로부터 메시지가 왔을때 호출
 public void MessageReceive(IReceiveContext context)
 {
     if(((string) context.GetMessage()).Substring(0,4) != "test")
         throw new Exception("Error!");
     Console.WriteLine("Server Thread " + System.Threading.Thread.CurrentThread.ManagedThreadId + " - " + context.GetMessage());
     context.GetChannel().SendMessage(context.GetMessage());
     //context.GetChannel().SendMessage(context.GetMessage()); // 에코 서버인 만큼 온 데이터를 그대로 전송
 }
Esempio n. 7
0
 public void Connected(IReceiveContext context)
 {
     dynamic packet = new JObject();
     packet.type = "connect_service_info";
     packet.service = _processor.GetServiceLoader().GetServiceName();
     packet.id = _processor.GetServiceId();
     context.GetChannel().SendMessage(packet);
 }
Esempio n. 8
0
 public void Connected(IReceiveContext context)
 {
     context.GetChannel().SetTag(false);
     channelLock.EnterWriteLock();
     _channels.AddLast(context.GetChannel());
     channelLock.ExitWriteLock();
     SendMessage("hi! " + context.GetChannel());
     context.GetChannel().SendMessage("your name\r\n>");
 }
 public ReceiveContextSender(IReceiveContext context, ISendContextSender innerSender, Route[] routes)
 {
     if (context == null) throw new ArgumentNullException("context");
     if (innerSender == null) throw new ArgumentNullException("innerSender");
     if (routes == null) throw new ArgumentNullException("routes");
     _context = context;
     _innerSender = innerSender;
     _routes = routes;
 }
Esempio n. 10
0
        // 클라이언트로부터 메시지가 왔을때 호출
        public void MessageReceive(IReceiveContext context)
        {
            var o = context.GetMessage() as JObject;

            if(o.Value<string>("name") != "test")
                throw new Exception("Error!");
            Console.WriteLine("Server Thread {0} - {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, context.GetMessage());
            context.GetChannel().SendMessage(context.GetMessage());
            //context.GetChannel().SendMessage(context.GetMessage()); // 에코 서버인 만큼 온 데이터를 그대로 전송
        }
Esempio n. 11
0
 public void MessageReceive(IReceiveContext context)
 {
     dynamic message = context.GetMessage();
     if (message.type == "notify_join_service")
         _processor.NotifyJoinService((string)message.service, (int)message.id, (byte[])message.address, (int)message.port);
     else if (message.type == "change_service_id")
         _processor.ChangeServiceId((int)message.id);
     else if (message.type == "max_entity_id")
         _processor.ChangeMaxEntityId((long)message.value);
 }
Esempio n. 12
0
 public void MessageReceive(IReceiveContext context)
 {
     if (context.GetChannel().GetTag() is bool)
     {
         context.GetChannel().SetTag(context.GetMessage());
         SendMessage(context.GetChannel() + " name is " + context.GetChannel().GetTag() + "\r\n> ");
         return;
     }
     SendMessage(context.GetChannel().GetTag() + " : " + context.GetChannel() + "> ");
 }
Esempio n. 13
0
        public async Task Handle(IReceiveContext <DeleteClientCommand> context, CancellationToken cancellationToken)
        {
            var mappings = _context.Client2HospitalClient.Where(x => x.ClientId == context.Message.Id);

            _context.Client2HospitalClient.RemoveRange(mappings);

            var Client = _context.Client.Find(context.Message.Id);

            _context.Client.Remove(Client);
            await _context.SaveChangesAsync();
        }
        public Task Handle(IReceiveContext <SimpleCommand> context, CancellationToken cancellationToken)
        {
            _simpleService.DoWork();
            DummyTransaction transaction;

            if (context.TryGetService(out transaction))
            {
                transaction.Commit();
            }
            return(Task.FromResult(0));
        }
Esempio n. 15
0
        public MoveMessageSendContext(IReceiveContext context)
        {
            SetUsing(context);
            CopyOrInitializeOriginalMessageId(context);

            Id = context.Id;

            _notifySend = address => context.NotifySend(this, address);

            _bodyWriter = stream => context.CopyBodyTo(stream);
        }
        public async Task <PagerResult <ListClient2HospitalClientResponse> > Handle(IReceiveContext <PagerQuery <ListClient2HospitalClientRequest> > context, CancellationToken cancellationToken)
        {
            var query = context.Message;
            var sql   = from p in _context.Client2HospitalClient
                        join u in _context.User on p.CreateUserId equals u.Id
                        join c in _context.HospitalClient on p.HospitalClientId equals c.Id
                        join h in _context.Hospital on c.HospitalId equals h.Id
                        join ct in _context.Client on p.ClientId equals ct.Id
                        orderby p.Id descending
                        select new ListClient2HospitalClientResponse
            {
                Client = new GetClientResponse
                {
                    Id   = ct.Id,
                    Name = ct.Name,
                },
                ClientMappingId = p.Id,
                HospitalClient  = new GetHospitalClientResponse
                {
                    Id       = c.Id,
                    Hospital = new GetHospitalResponse {
                        Id = h.Id,
                    }
                },
                CreateTime     = p.CreateTime,
                CreateUserName = u.Username,
            };

            if (query.Query?.HospitalId != null)
            {
                sql = sql.Where(x => x.HospitalClient.Hospital.Id == query.Query.HospitalId.Value);
            }
            if (query.Query?.ClientId != null)
            {
                sql = sql.Where(x => x.Client.Id == query.Query.ClientId.Value);
            }
            if (!string.IsNullOrEmpty(query.Query?.Name))
            {
                sql = sql.Where(x => x.Client.Name.Contains(query.Query.Name));
            }
            var data = new PagerResult <ListClient2HospitalClientResponse>(query.Index, query.Size, sql);

            if (data.Total > 0)
            {
                var hospitalclients = await _mediator.ListByIdsAsync <GetHospitalClientRequest, GetHospitalClientResponse>(data.Select(x => x.HospitalClient.Id));

                foreach (var m in data.Result)
                {
                    m.HospitalClient = hospitalclients.FirstOrDefault(x => x.Id == m.HospitalClient.Id);
                }
            }
            return(data);
        }
        public async Task Handle(IReceiveContext <DeleteClientGoodsCommand> context, CancellationToken cancellationToken)
        {
            var id       = context.Message.Id;
            var mappings = _context.ClientGoods2HospitalGoods.Where(x => x.ClientGoodsId == id);

            _context.ClientGoods2HospitalGoods.RemoveRange(mappings);

            var goods = _context.ClientGoods.Find(id);

            _context.ClientGoods.Remove(goods);
            await _context.SaveChangesAsync();
        }
Esempio n. 18
0
        void MoveMessageToErrorTransport(IReceiveContext context)
        {
            var moveContext = new MoveMessageSendContext(context);

            _errorTransport.Send(moveContext);

            string messageId = context.OriginalMessageId ?? context.MessageId;

            _tracker.MessageWasMovedToErrorQueue(messageId);

            Address.LogMoved(_errorTransport.Address, context.MessageId, "");
        }
        public async Task <HospitalClient> Handle(IReceiveContext <UpdateHospitalClientRequest> context, CancellationToken cancellationToken)
        {
            var updated = context.Message;
            var goods   = _context.HospitalClient.First(x => x.Id == updated.Id);

            goods.Name = updated.Name;

            _context.HospitalClient.Update(goods);
            await _context.SaveChangesAsync();

            return(goods);
        }
Esempio n. 20
0
        public async Task Handle(IReceiveContext <TestBaseCommand> context, CancellationToken cancellationToken)
        {
            var userName = context.MetaData["UserName"];

            RubishBox.Rublish.Add(userName);

            var password = context.MetaData["Password"];

            RubishBox.Rublish.Add(password);

            await Task.FromResult(0);
        }
Esempio n. 21
0
        public async Task <Client> Handle(IReceiveContext <UpdateClientRequest> context, CancellationToken cancellationToken)
        {
            var payload = context.Message;
            var client  = _context.Client.First(x => x.Id == payload.Id);

            client.Name = payload.Name;

            _context.Client.Update(client);
            await _context.SaveChangesAsync();

            return(client);
        }
        public async Task <HospitalGoods> Handle(IReceiveContext <UpdateHospitalGoodsIsActiveRequest> context, CancellationToken cancellationToken)
        {
            var updated = context.Message;
            var goods   = _context.HospitalGoods.First(x => x.Id == updated.Id);

            goods.IsActive = updated.IsActive ? 1 : 0;

            _context.HospitalGoods.Update(goods);
            await _context.SaveChangesAsync();

            return(goods);
        }
Esempio n. 23
0
        public void Should_receive_the_message_in_the_type_requested()
        {
            using (var buffer = new MemoryStream(Encoding.UTF8.GetBytes(_message)))
            {
                IReceiveContext receiveContext = ReceiveContext.FromBodyStream(buffer);
                _serializer.Deserialize(receiveContext);

                IConsumeContext <A> context;
                receiveContext.TryGetContext <A>(out context).ShouldBeTrue();

                context.ShouldNotBeNull();
            }
        }
Esempio n. 24
0
        void ReportConsumerTime(DateTime startTime, TimeSpan receiveDuration, TimeSpan consumeDuration,
                                IReceiveContext context)
        {
            var message = new MessageReceived
            {
                Context         = context,
                ReceivedAt      = startTime,
                ReceiveDuration = receiveDuration,
                ConsumeDuration = consumeDuration,
            };

            _eventChannel.Send(message);
        }
Esempio n. 25
0
        public async Task <ListResponse <GetHospitalResponse> > Handle(IReceiveContext <GetHospitalRequest> context, CancellationToken cancellationToken)
        {
            var payload   = context.Message;
            var hospitals = await _context.Hospital.Where(x => payload.Ids.Contains(x.Id)).Select(x => new GetHospitalResponse
            {
                ConsumeDays = x.ConsumeDays,
                Id          = x.Id,
                Name        = x.Name,
                Remark      = x.Remark,
            }).ToListAsync();

            return(hospitals.ToResponse());
        }
Esempio n. 26
0
        public void Disconnected(IReceiveContext context)
        {
            if(context.GetChannel() != _channel)
                return;

            if (_heartbeatTimer != null)
                _heartbeatTimer.Dispose();
            _heartbeatTimer = null;

            Send("0", "");

            _socketIO.Emit("disconnect", this);
        }
        public async Task <PagerResult <ListHospitalDepartmentResponse> > Handle(IReceiveContext <PagerQuery <ListHospitalDepartmentRequest> > context, CancellationToken cancellationToken)
        {
            var query = context.Message;
            var sql   = from r in _context.HospitalDepartment
                        join u in _context.User on r.CreateUserId equals u.Id
                        join d in _context.DataDepartmentType on r.DepartmentTypeId equals d.Id
                        join rp in _context.HospitalDepartment on r.ParentId equals rp.Id into rp_def
                        from rp_def_t in rp_def.DefaultIfEmpty()
                        orderby r.Id descending
                        select new ListHospitalDepartmentResponse
            {
                CreateTime = r.CreateTime,
                Id         = r.Id,
                Name       = r.Name,
                Hospital   = new GetHospitalResponse
                {
                    Id = r.HospitalId
                },
                CreateUserName  = u.Username,
                DepartmentType  = d,
                IsPurchaseCheck = r.IsPurchaseCheck,
                Parent          = rp_def_t != null ? new IdNameValueModel {
                    Id = rp_def_t.Id, Name = rp_def_t.Name
                } : null,
            };

            if (query.Query?.HospitalId != null)
            {
                sql = sql.Where(x => x.Hospital.Id == query.Query.HospitalId.Value);
            }
            if (query.Query?.DepartmentTypeId != null)
            {
                sql = sql.Where(x => x.DepartmentType.Id == query.Query.DepartmentTypeId.Value);
            }
            if (!string.IsNullOrEmpty(query.Query?.Name))
            {
                sql = sql.Where(x => x.Name.Contains(query.Query.Name));
            }
            var data = new PagerResult <ListHospitalDepartmentResponse>(query.Index, query.Size, sql);

            if (data.Total > 0)
            {
                var hospitals = await _mediator.ListByIdsAsync <GetHospitalRequest, GetHospitalResponse>(data.Select(x => x.Hospital.Id).ToList());

                foreach (var m in data.Result)
                {
                    m.Hospital = hospitals.FirstOrDefault(x => x.Id == m.Hospital.Id);
                }
            }
            return(data);
        }
Esempio n. 28
0
        static object DeserializeHeaderHandler(Header[] headers, IReceiveContext context)
        {
            if (headers == null)
            {
                return(null);
            }

            for (int i = 0; i < headers.Length; i++)
            {
                MapNameValuePair(context, headers[i]);
            }

            return(null);
        }
        public void Deserialize(IReceiveContext context)
        {
            Envelope result;

            using (var inputStream = new NonClosingStream(context.BodyStream))
                using (var bsonReader = new BsonReader(inputStream))
                {
                    result = Deserializer.Deserialize <Envelope>(bsonReader);
                }

            context.SetUsingEnvelope(result);
            context.SetMessageTypeConverter(new JsonMessageTypeConverter(Deserializer, result.Message as JToken,
                                                                         result.MessageType));
        }
        public async Task <Hospital> Handle(IReceiveContext <UpdateHospitalRequest> context, CancellationToken cancellationToken)
        {
            var updated  = context.Message;
            var hospital = _context.Hospital.First(x => x.Id == updated.Id);

            hospital.Name        = updated.Name;
            hospital.Remark      = updated.Remark;
            hospital.ConsumeDays = updated.ConsumeDays;

            _context.Hospital.Update(hospital);
            await _context.SaveChangesAsync();

            return(hospital);
        }
        protected void TestSerialization <T>(T message)
            where T : class
        {
            byte[] data;
            var    serializer = new TSerializer();

            _sourceUri      = new Uri("loopback://localhost/source");
            _responseUri    = new Uri("loopback://localhost/response");
            _faultUri       = new Uri("loopback://localhost/fault");
            _destinationUri = new Uri("loopback://localhost/destination");
            _retryCount     = 69;

            using (var output = new MemoryStream())
            {
                ISendContext <T> context = message.ToSendContext();
                context.SetSourceAddress(_sourceUri);
                context.SendResponseTo(_responseUri);
                context.SendFaultTo(_faultUri);
                context.SetDestinationAddress(_destinationUri);
                context.SetRetryCount(_retryCount);

                serializer.Serialize(output, context);

                data = output.ToArray();
            }

            // Trace.WriteLine(Encoding.UTF8.GetString(data));

            using (MemoryStream input = new MemoryStream(data))
            {
                IReceiveContext context = ReceiveContext.FromBodyStream(input);
                serializer.Deserialize(context);

                IConsumeContext <T> messageContext;
                context.TryGetContext <T>(out messageContext).ShouldBeTrue();

                messageContext.ShouldNotBeNull();
                message.Equals(messageContext.Message).ShouldBeTrue();
                message.ShouldNotBeTheSameAs(messageContext.Message);


                Assert.AreEqual(_retryCount, context.RetryCount);
                Assert.AreEqual(_sourceUri, context.SourceAddress);
                Assert.AreEqual(_responseUri, context.ResponseAddress);
                Assert.AreEqual(_faultUri, context.FaultAddress);
                Assert.AreEqual(_destinationUri, context.DestinationAddress);
                //			Assert.AreEqual(message.GetType().ToMessageName(), CurrentMessage.Headers.MessageType);
            }
        }
Esempio n. 32
0
 /// <summary>
 /// Receives content sent from a session via a topic.
 /// </summary>
 /// <param name="sessionId">Identifies the client session that sent the content.</param>
 /// <param name="topicPath">The path of the topic that the content was sent on.</param>
 /// <param name="content">The content sent by the client.</param>
 /// <param name="context">The context associated with the content.</param>
 public override void OnMessage(
     SessionId sessionId,
     string topicPath,
     IContent content,
     IReceiveContext context)
 {
     theMessagingControl.Send(
         sessionId,
         topicPath,
         content,
         theMessagingControl.CreateSendOptionsBuilder()
         .SetHeaders(context.HeadersList.ToList())
         .Build(),
         theSendCallback);
 }
Esempio n. 33
0
        public async Task <Client> Handle(IReceiveContext <CreateClientRequest> context, CancellationToken cancellationToken)
        {
            var payload = context.Message;
            var client  = new Client
            {
                Name         = payload.Name,
                CreateUserId = payload.UserId,
                CreateTime   = DateTime.Now,
            };

            _context.Client.Add(client);
            await _context.SaveChangesAsync();

            return(client);
        }
        public async Task <SysWhitePhone> Handle(IReceiveContext <CreateWhitePhoneRequest> context, CancellationToken cancellationToken)
        {
            var created = context.Message;
            var phone   = new SysWhitePhone
            {
                Phone        = created.Phone,
                CreateUserId = created.UserId,
                CreateTime   = DateTime.Now,
            };

            _context.SysWhitePhone.Add(phone);
            await _context.SaveChangesAsync();

            return(phone);
        }
Esempio n. 35
0
        public async Task <HospitalDepartment> Handle(IReceiveContext <UpdateHospitalDepartmentRequest> context, CancellationToken cancellationToken)
        {
            var updated    = context.Message;
            var department = _context.HospitalDepartment.First(x => x.Id == updated.Id);

            department.Name             = updated.Name;
            department.DepartmentTypeId = updated.DepartmentTypeId;
            department.ParentId         = updated.ParentId;
            department.IsPurchaseCheck  = updated.IsPurchaseCheck;

            _context.HospitalDepartment.Update(department);
            await _context.SaveChangesAsync();

            return(department);
        }
Esempio n. 36
0
        static IConsumeContext <RoutingSlip> TranslateXmlBody(IReceiveContext context)
        {
            var serializer = new XmlMessageSerializer();

            serializer.Deserialize(context);

            IConsumeContext <RoutingSlip> routingSlipContext;

            if (context.TryGetContext(out routingSlipContext))
            {
                return(routingSlipContext);
            }

            throw new InvalidOperationException("Unable to reprocess message as RoutingSlip");
        }
Esempio n. 37
0
        protected T Return <T>(byte[] serializedMessageData) where T : class
        {
            using (var input = new MemoryStream(serializedMessageData))
            {
                IReceiveContext receiveContext = ReceiveContext.FromBodyStream(input);
                _serializer.Deserialize(receiveContext);

                IConsumeContext <T> context;
                receiveContext.TryGetContext(out context).ShouldBeTrue();

                context.ShouldNotBeNull();

                return(context.Message);
            }
        }
        public async Task <HospitalClient> Handle(IReceiveContext <CreateHospitalClientRequest> context, CancellationToken cancellationToken)
        {
            var created = context.Message;
            var goods   = new HospitalClient
            {
                Name         = created.Name,
                HospitalId   = created.HospitalId,
                CreateUserId = created.UserId,
                CreateTime   = DateTime.Now,
            };

            _context.HospitalClient.Add(goods);
            await _context.SaveChangesAsync();

            return(goods);
        }
Esempio n. 39
0
        public void Deserialize(IReceiveContext context)
        {
            Envelope result;

            using (var inputStream = new NonClosingStream(context.BodyStream))
            {
                result = ProtoBuf.Serializer.Deserialize <Envelope>(inputStream);
            }
            if (result == null || result.Message == null)
            {
                throw new Exception("ProtoBufMessageSerializer::Deserialize. Error Deserializing message.");
            }

            context.SetUsingEnvelope(result);
            context.SetMessageTypeConverter(new StaticMessageTypeConverter(result.Message));
        }
Esempio n. 40
0
        // 클라이언트로부터 메시지가 왔을때 호출
        public void MessageReceive(IReceiveContext context)
        {
            var o = context.GetMessage() as JObject;

            if (o.Value<string>("name") != "test")
                throw new Exception("Error!");

            JObject o2 = new JObject();
            o2.Add("name", "test");
            o2.Add("value", i++);
            context.GetChannel().SendMessage(o2);

            Console.WriteLine("Client Thread " + System.Threading.Thread.CurrentThread.ManagedThreadId + " - " + context.GetMessage());
            if (((JObject) context.GetMessage()).Value<int>("value") == 20)
                SocketChannel.ExitEvent.Set();
        }
        public async Task <Client2HospitalClient> Handle(IReceiveContext <CreateClient2HospitalClientRequest> context, CancellationToken cancellationToken)
        {
            var created = context.Message;
            var mapping = new Client2HospitalClient
            {
                HospitalClientId = created.HospitalClientId,
                ClientId         = created.ClientId,
                CreateUserId     = created.UserId,
                CreateTime       = DateTime.Now,
            };

            _context.Client2HospitalClient.Add(mapping);
            await _context.SaveChangesAsync();

            return(mapping);
        }
Esempio n. 42
0
        void MoveMessageToErrorTransport(IReceiveContext context)
        {
            var moveContext = new MoveMessageSendContext(context);

            _errorTransport.Send(moveContext);

            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("MOVE:{0}:{1}:{2}", Address, _errorTransport.Address, context.MessageId);
            }

            if (SpecialLoggers.Messages.IsInfoEnabled)
            {
                SpecialLoggers.Messages.InfoFormat("MOVE:{0}:{1}:{2}", Address, _errorTransport.Address, context.MessageId);
            }
        }
Esempio n. 43
0
 public void MessageReceive(IReceiveContext context)
 {
     var packet = (JObject)context.GetMessage();
     System.Console.WriteLine(packet);
     string type = packet["type"].Value<string>();
     switch (type)
     {
         case "ant_name_list":
             Kernel.GetKernel().InitAnts(((JArray)packet["args"]));
             break;
         case "approve_join_ant":
             var args = packet["args"].Value<JObject>();
             Kernel.GetKernel().ApproveJoinAnt(args["id"].Value<int>(), args["network"].Value<JArray>().Values<JObject>());
             break;
     }
 }
Esempio n. 44
0
 public static void SetUsingMessageEnvelope(this IReceiveContext context, XmlMessageEnvelope envelope)
 {
     context.SetRequestId(envelope.RequestId);
     context.SetConversationId(envelope.ConversationId);
     context.SetCorrelationId(envelope.CorrelationId);
     context.SetSourceAddress(envelope.SourceAddress.ToUriOrNull());
     context.SetDestinationAddress(envelope.DestinationAddress.ToUriOrNull());
     context.SetResponseAddress(envelope.ResponseAddress.ToUriOrNull());
     context.SetFaultAddress(envelope.FaultAddress.ToUriOrNull());
     context.SetNetwork(envelope.Network);
     context.SetRetryCount(envelope.RetryCount);
     context.SetMessageType(envelope.MessageType);
     if (envelope.ExpirationTime.HasValue)
     {
         context.SetExpirationTime(envelope.ExpirationTime.Value);
     }
 }
        public async Task <Hospital> Handle(IReceiveContext <CreateHospitalRequest> context, CancellationToken cancellationToken)
        {
            var created  = context.Message;
            var hospital = new Hospital
            {
                Name         = created.Name,
                Remark       = created.Remark,
                ConsumeDays  = created.ConsumeDays,
                CreateUserId = created.UserId,
                CreateTime   = DateTime.Now,
            };

            _context.Hospital.Add(hospital);
            await _context.SaveChangesAsync();

            return(hospital);
        }
Esempio n. 46
0
 public void MessageReceive(IReceiveContext context)
 {
     var packet = (JObject)context.GetMessage();
     System.Console.WriteLine(packet);
     string type = packet["type"].Value<string>();
     switch (type)
     {
         case "get_ant_name_list":
             context.GetChannel().SendMessage("ant_name_list", new JArray(QueenAnt.GetQueenAnt().GetAntNameArray()));
             break;
         case "request_join_ant":
             AntManager.GetAntManager().RequestJoinAnt(context.GetChannel(), packet["args"].Value<JObject>());
             break;
         case "start_ant":
             AntManager.GetAntManager().StartAnt(context.GetChannel().GetTag() as Ant);
             break;
     }
 }
Esempio n. 47
0
        public void Connected(IReceiveContext context)
        {
            if (context.GetChannel().ToString().Substring(0, context.GetChannel().ToString().IndexOf(":", StringComparison.Ordinal))
                != _channel.ToString().Substring(0, _channel.ToString().IndexOf(":", StringComparison.Ordinal)))
            {
                context.GetChannel().Disconnect();
                return;
            }

            _channel = context.GetChannel();

            _channel.SetConfig("handler", this);

            _socketIO.Emit("connection", this);

            Send("1", "", _endPoint + "?server=netronics");
            if(_heartbeatTimer == null)
                _heartbeatTimer = new Timer(state => Send("2", ""), null, 0, 10000);
        }
Esempio n. 48
0
 public void MessageReceive(IReceiveContext context)
 {
     var packet = (JObject)context.GetMessage();
     string type = packet["type"].Value<string>();
     switch (type)
     {
         case "hello_ant":
             var args = packet["args"].Value<JObject>();
             Kernel.GetKernel().HelloAnt(context.GetChannel(), args.Value<int>("ant"), args.Value<int>("id"));
             break;
         case "request":
             var ant = context.GetChannel().GetTag() as RemoteAnt;
             ant.ReceiveTask(packet["t_id"].Value<int>(), packet["m_type"].Value<int>(), packet["args"]);
             break;
         case "response":
             ant = context.GetChannel().GetTag() as RemoteAnt;
             ant.ResponseTask(packet["t_id"].Value<int>(), packet["args"]);
             break;
         default:
             System.Console.WriteLine(packet);
             break;
     }
 }
		void DeliverMessageToConsumers(IReceiveContext context)
		{
			try
			{
				NotifyReceiveCompleted();

				_receiveTime.Stop();
				_consumeTime.Start();

				if (_log.IsDebugEnabled)
					_log.DebugFormat("Dispatching message on {0} from thread {1}", _bus.Endpoint.Address.Uri,
						Thread.CurrentThread.ManagedThreadId);

				bool atLeastOneConsumerFailed = false;

				Exception lastException = null;

				do
				{
					try
					{
						_consumers.Current(context);
						_consumeCount++;
					}
					catch (Exception ex)
					{
						_log.Error(string.Format("'{0}' threw an exception consuming message '{1}'",
							_consumers.Current.GetType().FullName,
							context.GetType().FullName), ex);

						atLeastOneConsumerFailed = true;
						lastException = ex;
					}
				} while (_consumers.MoveNext());

				if (atLeastOneConsumerFailed)
				{
					throw new MessageException(context.GetType(),
						"At least one consumer threw an exception",
						lastException);
				}
			}
			finally
			{
				_consumeTime.Stop();

				_consumers.Dispose();
				_consumers = null;

				ReportConsumerTime(_startTime, _receiveTime.Elapsed, _consumeTime.Elapsed, context);
				ReportConsumerCount(context, _consumeCount);
			}
		}
		void ReportConsumerTime(DateTime startTime, TimeSpan receiveDuration, TimeSpan consumeDuration,
		                        IReceiveContext context)
		{
			var message = new MessageReceived
				{
					Context = context,
					ReceivedAt = startTime,
					ReceiveDuration = receiveDuration,
					ConsumeDuration = consumeDuration,
				};

			_eventChannel.Send(message);
		}
Esempio n. 51
0
 public void Connected(IReceiveContext context)
 {
     context.GetChannel().SendMessage(_processor.GetJoinServicePacket());
 }
Esempio n. 52
0
 // 클라이언트 접속종료시 호출
 public void Disconnected(IReceiveContext channel)
 {
 }
Esempio n. 53
0
 // 클라이언트가 접속시 호출
 public void Connected(IReceiveContext channel)
 {
     //channel.GetChannel().SendMessage(System.Text.Encoding.Default.GetBytes("test"));
 }
Esempio n. 54
0
 public void Disconnected(IReceiveContext context)
 {
 }
Esempio n. 55
0
 public int ReceiveSwitching(IReceiveContext context)
 {
     return Random.Next(3);
 }
Esempio n. 56
0
 // 클라이언트로부터 메시지가 왔을때 호출
 public void MessageReceive(IReceiveContext context)
 {
     context.GetChannel().SendMessage(context.GetMessage()); // 에코 서버인 만큼 온 데이터를 그대로 전송
 }
 /// <summary>
 /// Receives content sent from a session via a topic.
 /// </summary>
 /// <param name="sessionId">Identifies the client session that sent the content.</param>
 /// <param name="topicPath">The path of the topic that the content was sent on.</param>
 /// <param name="content">The content sent by the client.</param>
 /// <param name="context">The context associated with the content.</param>
 public override void OnMessage( SessionId sessionId, string topicPath, IContent content,
     IReceiveContext context )
 {
     theMessagingControl.Send( sessionId, topicPath, content,
         theMessagingControl.CreateSendOptionsBuilder().SetHeaders( context.HeadersList.ToList() ).Build(),
         theSendCallback );
 }
Esempio n. 58
0
		void WriteMessageToFile(string pathName, IReceiveContext context, string body)
		{
			string fileName = GetNextFileName(pathName);

			using (StreamWriter stream = System.IO.File.CreateText(fileName))
			{
				if (context.ContentType.IsNotEmpty())
					stream.WriteLine("Content-Type: {0}", context.ContentType);
				if (context.MessageId.IsNotEmpty())
					stream.WriteLine("Message-Id: {0}", context.MessageId);

				stream.WriteLine();
				stream.Write(body);
				stream.Close();
			}
		}
Esempio n. 59
0
 public int ReceiveSwitching(IReceiveContext context)
 {
     return context.GetChannel().GetHashCode();
 }
 /// <summary>
 /// Receives content sent from a session via a topic.
 /// </summary>
 /// <param name="sessionId">Identifies the client session that sent the content.</param>
 /// <param name="topicPath">The path of the topic that the content was sent on.</param>
 /// <param name="content">The content sent by the client.</param>
 /// <param name="context">The context associated with the content.</param>
 public virtual void OnMessage( SessionId sessionId, string topicPath, IContent content,
     IReceiveContext context )
 {
 }